mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 10:53:56 +00:00
Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50fbd51186 | ||
|
|
a94401170c | ||
|
|
197c00a2f0 | ||
|
|
191b604d16 | ||
|
|
c81adf2c9c | ||
|
|
dfb3e2a3a1 | ||
|
|
73473986a0 | ||
|
|
506c1c1a1e | ||
|
|
eba0959bd3 | ||
|
|
e22743ac7d | ||
|
|
82f778d7ef | ||
|
|
ba031d5658 | ||
|
|
32ade8984d | ||
|
|
20ae299359 | ||
|
|
afef08c28d | ||
|
|
f646178c27 | ||
|
|
d1b3038ec1 | ||
|
|
2f7c55e014 | ||
|
|
d370f25858 | ||
|
|
44c616e262 | ||
|
|
6dec3ecab6 | ||
|
|
e5cc0127e7 | ||
|
|
4fc1850299 | ||
|
|
3c9dc8e5ce | ||
|
|
f6ea7661d4 | ||
|
|
d86626fb52 | ||
|
|
997dfa9e4f | ||
|
|
6bcd9a3cea | ||
|
|
3650e23966 | ||
|
|
a23868ee88 | ||
|
|
6829f9b082 | ||
|
|
519c463048 | ||
|
|
14767f6a48 | ||
|
|
e185306e50 | ||
|
|
b864bf55b6 | ||
|
|
9c49a07e16 | ||
|
|
c5a855d885 | ||
|
|
a2e04556b7 | ||
|
|
0fbf1cdc14 | ||
|
|
7bbff7ce6e | ||
|
|
57227dfe1b | ||
|
|
470628b1a3 | ||
|
|
ef99e0daf7 | ||
|
|
18a9000278 | ||
|
|
19ff28528d | ||
|
|
8e862798e4 | ||
|
|
5b9d5351d7 | ||
|
|
112bab7292 | ||
|
|
ed9da31034 | ||
|
|
f987341bf2 | ||
|
|
5e1bdd85d8 | ||
|
|
450d1df2e7 | ||
|
|
3ed22954db | ||
|
|
3260bf4206 | ||
|
|
17d53152ec | ||
|
|
f05ea0c9b7 | ||
|
|
bb81b72ff0 | ||
|
|
d0fffac598 | ||
|
|
106e39a797 | ||
|
|
3bf4c9df1a |
No files matched your search
@@ -0,0 +1,90 @@
|
||||
name: QA official Linux candidate (incremental probe)
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
paths:
|
||||
- .github/workflows/qa-official-linux.yml
|
||||
- scripts/qa-official-linux/**
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
concurrency:
|
||||
group: qa-official-linux-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
official-package-probe:
|
||||
if: >-
|
||||
github.repository == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
|
||||
github.event.pull_request.draft == true
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- candidate: a23868e
|
||||
config: candidate.json
|
||||
- candidate: 9d4e90b
|
||||
config: candidate-9d4e90b.json
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 12
|
||||
env:
|
||||
QA_ROOT: /tmp/netcatty-official-qa-${{ matrix.candidate }}
|
||||
QA_CANDIDATE: ${{ matrix.config }}
|
||||
steps:
|
||||
- name: Checkout QA harness without persisted credentials
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
persist-credentials: false
|
||||
- name: Node for QA harness only
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '24.11.1'
|
||||
- name: Stock desktop runtime dependencies
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y --no-install-recommends xvfb ffmpeg libgtk-3-0 libnss3 libasound2 libgbm1 libatk-bridge2.0-0 libxss1 libsecret-1-0
|
||||
- name: Install isolated QA dependencies without lifecycle scripts
|
||||
run: npm ci --prefix scripts/qa-official-linux --ignore-scripts --no-audit --no-fund
|
||||
- name: Verify official run, artifact ZIP and deb; extract without installer scripts
|
||||
id: provenance
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: node scripts/qa-official-linux/provenance.cjs
|
||||
- name: Persistence through real official Electron restart
|
||||
id: persistence
|
||||
if: success()
|
||||
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs persistence
|
||||
- name: Real SSH disconnect and original-tab reconnect
|
||||
id: ssh
|
||||
if: always() && steps.provenance.outcome == 'success'
|
||||
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs ssh
|
||||
- name: Independent real SFTP pause, stable bytes, resume and SHA-256
|
||||
id: sftp
|
||||
if: always() && steps.provenance.outcome == 'success'
|
||||
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs sftp
|
||||
- name: Independent clipboard UI check (never gates reconnect)
|
||||
if: always() && steps.provenance.outcome == 'success'
|
||||
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs clipboard
|
||||
- name: Independent new host filter compatibility and boundary checks
|
||||
if: always() && steps.provenance.outcome == 'success' && matrix.candidate == '9d4e90b'
|
||||
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs host-filter
|
||||
- name: Record explicit scope
|
||||
if: always()
|
||||
run: |
|
||||
echo 'Candidate ${{ matrix.candidate }}; exact official SHA/run/artifact/digests are recorded in provenance.json' >> "$GITHUB_STEP_SUMMARY"
|
||||
echo 'Read independent persistence, ssh and sftp assertions.json reports and real screenshots; a failure in one scenario does not skip the others. Stock sandbox launch failures are failures, never feature passes. This is extracted-package execution, not system-install acceptance.' >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Upload reviewed QA evidence (3 days)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: official-linux-${{ matrix.candidate }}-qa-${{ github.run_id }}
|
||||
path: /tmp/netcatty-official-qa-${{ matrix.candidate }}/evidence/
|
||||
retention-days: 3
|
||||
if-no-files-found: warn
|
||||
@@ -0,0 +1,74 @@
|
||||
name: QA official macOS native launch and SSH
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
paths:
|
||||
- .github/workflows/qa-official-macos.yml
|
||||
- scripts/qa-official-macos/**
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
concurrency:
|
||||
group: qa-official-macos-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
official-macos-smoke:
|
||||
if: >-
|
||||
github.repository == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
|
||||
github.event.pull_request.draft == true
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: macos-26
|
||||
arch: arm64
|
||||
- runner: macos-15-intel
|
||||
arch: x64
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
QA_ROOT: '${{ github.workspace }}/.qa-macos-${{ matrix.arch }}'
|
||||
QA_ARCH: ${{ matrix.arch }}
|
||||
QA_RUNNER: ${{ matrix.runner }}
|
||||
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
steps:
|
||||
- name: Checkout exact authorized QA head without persisted credentials
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
persist-credentials: false
|
||||
- name: Native Node for isolated QA harness
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '24.11.1'
|
||||
architecture: ${{ matrix.arch }}
|
||||
- name: Install only QA dependencies without lifecycle scripts or browsers
|
||||
run: npm ci --prefix scripts/qa-official-macos --ignore-scripts --no-audit --no-fund
|
||||
- name: Verify exact successful official push artifact and archive digest
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: node scripts/qa-official-macos/provenance.cjs
|
||||
- name: Verify DMG, copy read-only mounted app, require Developer ID and notarized Gatekeeper acceptance
|
||||
run: node scripts/qa-official-macos/verify-install.cjs
|
||||
- name: Actual native first launch and real GUI SSH roundtrip
|
||||
run: node scripts/qa-official-macos/desktop.cjs
|
||||
- name: Record exact scope
|
||||
if: always()
|
||||
run: |
|
||||
echo 'Read provenance.json, verification.json and assertions.json individually. DMG integrity is separate from the inner APP signature/ticket/Gatekeeper result. OS blockers are failures, never bypassed.' >> "$GITHUB_STEP_SUMMARY"
|
||||
echo 'Exact official 9d4e90b candidate only, standard hosted native architecture, fresh synthetic profile, loopback SSH/DevTools. No Finder-quarantine, LAN, updater, personal-device or final merged revision coverage.' >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Retain per-architecture reviewed logs, assertions and actual native PNGs (3 days)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: qa-macos-${{ matrix.arch }}-9d4e90b-${{ github.run_id }}
|
||||
path: '${{ env.QA_ROOT }}/evidence/'
|
||||
retention-days: 3
|
||||
if-no-files-found: warn
|
||||
@@ -0,0 +1,165 @@
|
||||
name: QA official Windows install and AI history
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
paths:
|
||||
- .github/workflows/qa-official-windows.yml
|
||||
- scripts/qa-official-windows/**
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
concurrency:
|
||||
group: qa-official-windows-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
installed-windows-history:
|
||||
if: >-
|
||||
github.repository == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
|
||||
github.event.pull_request.draft == true
|
||||
runs-on: windows-2022
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
mode: [nsis, portable]
|
||||
timeout-minutes: 18
|
||||
env:
|
||||
QA_ROOT: '${{ github.workspace }}\.qa-win-runtime'
|
||||
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
QA_MODE: ${{ matrix.mode }}
|
||||
steps:
|
||||
- name: Checkout only the authorized QA head without saved credentials
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
persist-credentials: false
|
||||
- name: Node for QA harness
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '24.11.1'
|
||||
- name: Install only QA dependencies without lifecycle scripts or browsers
|
||||
run: npm ci --prefix scripts/qa-official-windows --ignore-scripts --no-audit --no-fund
|
||||
- name: Verify released installer and exact official Windows artifact
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: node scripts/qa-official-windows/provenance.cjs
|
||||
- name: Real installed GUI baseline, replacement, migration and restart
|
||||
run: node scripts/qa-official-windows/desktop.cjs
|
||||
- name: Record acceptance scope
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
'Read assertions.json for individual outcomes, provenance.json for hashes, and actual native renderer PNGs. A failed launcher or harness is not a migration pass. The candidate has a 0.0.0-sha version; this is not released automatic-updater acceptance.' >> $env:GITHUB_STEP_SUMMARY
|
||||
'Standard ephemeral windows-2022 runner, normal per-user official NSIS, synthetic data, same isolated profile and app origin, deterministic loopback model only; no security changes. Linux evidence remains in its earlier independent workflow.' >> $env:GITHUB_STEP_SUMMARY
|
||||
- name: Upload reviewed assertions, installer logs and native renderer PNGs (3 days)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: qa-windows-${{ matrix.mode }}-9d4e90b-${{ github.event.pull_request.head.sha }}
|
||||
path: '${{ env.QA_ROOT }}\evidence\'
|
||||
retention-days: 3
|
||||
if-no-files-found: warn
|
||||
|
||||
fixed-windows-package:
|
||||
name: Build exact 4516d3a Windows QA NSIS (unsigned, never publish)
|
||||
if: >-
|
||||
github.repository == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
|
||||
github.event.pull_request.draft == true
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 35
|
||||
env:
|
||||
QA_FIX_SOURCE: '${{ github.workspace }}\fixed-source'
|
||||
QA_BUILD_OUTPUT: '${{ github.workspace }}\qa-fixed-package'
|
||||
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
outputs:
|
||||
installer_sha: ${{ steps.build.outputs.installer_sha }}
|
||||
artifact_id: ${{ steps.package.outputs.artifact-id }}
|
||||
artifact_digest: ${{ steps.package.outputs.artifact-digest }}
|
||||
steps:
|
||||
- name: Checkout authorized QA harness without saved credentials
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
persist-credentials: false
|
||||
- name: Separate exact trusted same-repository fix checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
repository: binaricat/Netcatty
|
||||
ref: 4516d3aed7cb54862dabd53abb56a7f90fba3212
|
||||
path: fixed-source
|
||||
persist-credentials: false
|
||||
- name: Node 22 for repository Windows packaging conventions
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '22.21.1'
|
||||
- name: Build real NSIS with stock MSVC and existing pack:win-x64
|
||||
id: build
|
||||
run: node scripts/qa-official-windows/build-fixed.cjs
|
||||
- name: Retain exact QA installer, build provenance and reviewed logs (3 days)
|
||||
id: package
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: qa-fixed-windows-4516d3a-${{ github.run_id }}
|
||||
path: '${{ env.QA_BUILD_OUTPUT }}\'
|
||||
retention-days: 3
|
||||
if-no-files-found: warn
|
||||
|
||||
fixed-installed-windows-history:
|
||||
name: Test real installed exact 4516d3a fix and positive pointer restart
|
||||
needs: fixed-windows-package
|
||||
if: >-
|
||||
github.repository == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
|
||||
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
|
||||
github.event.pull_request.draft == true
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
QA_ROOT: '${{ github.workspace }}\.qa-fixed-win-runtime'
|
||||
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
QA_MODE: nsis
|
||||
QA_CANDIDATE: fixed-candidate.json
|
||||
QA_FIXED_ARTIFACT: '${{ github.workspace }}\qa-fixed-input'
|
||||
QA_EXPECTED_INSTALLER_SHA: ${{ needs.fixed-windows-package.outputs.installer_sha }}
|
||||
QA_BUILD_ARTIFACT_ID: ${{ needs.fixed-windows-package.outputs.artifact_id }}
|
||||
QA_BUILD_ARTIFACT_DIGEST: ${{ needs.fixed-windows-package.outputs.artifact_digest }}
|
||||
steps:
|
||||
- name: Checkout same QA harness without persisted credentials
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
persist-credentials: false
|
||||
- name: Node for actual native application harness
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '24.11.1'
|
||||
- name: Retrieve only this run's exact SHA QA package
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: qa-fixed-windows-4516d3a-${{ github.run_id }}
|
||||
path: '${{ env.QA_FIXED_ARTIFACT }}'
|
||||
- name: Install QA dependencies without scripts or browsers
|
||||
run: npm ci --prefix scripts/qa-official-windows --ignore-scripts --no-audit --no-fund
|
||||
- name: Verify same-run package SHA and official v1.1.90 baseline
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: node scripts/qa-official-windows/provenance-fixed.cjs
|
||||
- name: Real normal NSIS replacement, UI history, appended reply and strict restart
|
||||
run: node scripts/qa-official-windows/desktop.cjs
|
||||
- name: Retain exact fix assertions and actual native PNGs (3 days)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: qa-fixed-nsis-history-4516d3a-${{ github.event.pull_request.head.sha }}
|
||||
path: '${{ env.QA_ROOT }}\evidence\'
|
||||
retention-days: 3
|
||||
if-no-files-found: warn
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { enAiMessages } from './en/ai';
|
||||
import { esAiMessages } from './es/ai';
|
||||
import { ruAiMessages } from './ru/ai';
|
||||
import { zhCNAiMessages } from './zh-CN/ai';
|
||||
import { zhTWAiMessages } from './zh-TW/ai';
|
||||
|
||||
for (const [locale, messages] of Object.entries({
|
||||
en: enAiMessages, es: esAiMessages, ru: ruAiMessages,
|
||||
'zh-CN': zhCNAiMessages, 'zh-TW': zhTWAiMessages,
|
||||
})) {
|
||||
test(`${locale} translates the Catty iteration limit notice and Continue action`, () => {
|
||||
assert.ok(messages['ai.chat.iterationLimitReached']);
|
||||
assert.match(messages['ai.chat.iterationLimitReached'], /\{limit\}/);
|
||||
assert.ok(messages['ai.chat.continue']);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const enAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
|
||||
'ai.chat.continue': 'Continue',
|
||||
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent Settings',
|
||||
@@ -333,6 +335,7 @@ export const enAiMessages: Messages = {
|
||||
'ai.defaultAgent': 'Default Agent',
|
||||
'ai.defaultAgent.description': 'Agent to use when starting a new AI session',
|
||||
'ai.defaultAgent.catty': 'Catty (Built-in)',
|
||||
'ai.defaultAgent.unavailable': 'Unavailable',
|
||||
'ai.toolAccess.title': 'Tool Access',
|
||||
'ai.toolAccess.mode': 'Netcatty Access Mode',
|
||||
'ai.toolAccess.description': 'Choose how external agents access Netcatty sessions. MCP exposes the built-in server, while Skills + CLI points agents to the local Netcatty skill and CLI commands.',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const esAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
|
||||
'ai.chat.continue': 'Continuar',
|
||||
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Configuración del agente',
|
||||
@@ -333,6 +335,7 @@ export const esAiMessages: Messages = {
|
||||
'ai.defaultAgent': 'Agente predeterminado',
|
||||
'ai.defaultAgent.description': 'Agente que se usará al iniciar una nueva sesión de IA',
|
||||
'ai.defaultAgent.catty': 'Catty (Integrado)',
|
||||
'ai.defaultAgent.unavailable': 'No disponible',
|
||||
'ai.toolAccess.title': 'Acceso a herramientas',
|
||||
'ai.toolAccess.mode': 'Modo de acceso de Netcatty',
|
||||
'ai.toolAccess.description': 'Elige cómo acceden los agentes externos a las sesiones de Netcatty. MCP expone el servidor integrado, mientras que Habilidades + CLI apunta a los agentes hacia las habilidades locales de Netcatty y los comandos de CLI.',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const ruAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
|
||||
'ai.chat.continue': 'Продолжить',
|
||||
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
|
||||
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
|
||||
// AI Settings
|
||||
@@ -273,6 +275,7 @@ export const ruAiMessages: Messages = {
|
||||
'ai.defaultAgent': 'Агент по умолчанию',
|
||||
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
|
||||
'ai.defaultAgent.catty': 'Catty (встроенный)',
|
||||
'ai.defaultAgent.unavailable': 'Недоступен',
|
||||
'ai.toolAccess.title': 'Доступ к инструментам',
|
||||
'ai.toolAccess.mode': 'Режим доступа Netcatty',
|
||||
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
|
||||
'ai.chat.continue': '继续',
|
||||
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 设置',
|
||||
@@ -333,6 +335,7 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.defaultAgent': '默认 Agent',
|
||||
'ai.defaultAgent.description': '创建新 AI 会话时使用的 Agent',
|
||||
'ai.defaultAgent.catty': 'Catty(内置)',
|
||||
'ai.defaultAgent.unavailable': '暂不可用',
|
||||
'ai.toolAccess.title': '工具接入',
|
||||
'ai.toolAccess.mode': 'Netcatty 接入模式',
|
||||
'ai.toolAccess.description': '选择外部 Agent 访问 Netcatty 会话的方式。MCP 会暴露内置服务器,Skills + CLI 会引导 Agent 读取本地 Skill 并调用 Netcatty CLI。',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
|
||||
'ai.chat.continue': '繼續',
|
||||
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 設定',
|
||||
@@ -333,6 +335,7 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.defaultAgent': '預設 Agent',
|
||||
'ai.defaultAgent.description': '建立新 AI 工作階段時使用的 Agent',
|
||||
'ai.defaultAgent.catty': 'Catty(內建)',
|
||||
'ai.defaultAgent.unavailable': '暫時無法使用',
|
||||
'ai.toolAccess.title': '工具介接',
|
||||
'ai.toolAccess.mode': 'Netcatty 介接模式',
|
||||
'ai.toolAccess.description': '選擇外部 Agent 存取 Netcatty 工作階段的方式。MCP 會公開內建伺服器,Skills + CLI 會引導 Agent 讀取本機 Skill 並呼叫 Netcatty CLI。',
|
||||
|
||||
@@ -541,3 +541,98 @@ test("late pause acknowledgement cannot restart a cancelling stream before settl
|
||||
await pause;
|
||||
assert.equal(resumes, 0);
|
||||
});
|
||||
|
||||
for (const rejected of [false, true]) {
|
||||
test(`folder pause retains successful children without claiming failed children paused: rejected=${rejected}`, async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
let fail = true;
|
||||
let resumes = 0;
|
||||
const id = `partial-folder-${rejected}`;
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-ok`), parentTaskId: id },
|
||||
{ ...makeTask(`${id}-bad`), parentTaskId: id },
|
||||
], () => ({
|
||||
pauseTransfer: async (childId) => {
|
||||
if (fail && childId.endsWith('-bad')) {
|
||||
if (rejected) throw new Error('pause IPC unavailable');
|
||||
return { success: false, reason: 'This transfer cannot be paused safely' };
|
||||
}
|
||||
return { success: true, checkpointBytes: 10 };
|
||||
},
|
||||
resumeTransfer: async () => { resumes++; return { success: true }; },
|
||||
}));
|
||||
await softPauseTransfer(host, id);
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.equal(getTasks()[0].status, 'pausing');
|
||||
assert.match(getTasks()[0].pauseUnavailableReason || '', /pause/i);
|
||||
assert.equal(getTasks()[1].status, 'paused');
|
||||
assert.equal(getTasks()[2].status, 'transferring');
|
||||
assert.equal(isTransferPauseLatched(id), true);
|
||||
assert.equal(resumes, 0, 'failed pause must not resume successful siblings');
|
||||
fail = false;
|
||||
await softPauseTransfer(host, id);
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.ok(getTasks().every(row => row.status === 'paused'));
|
||||
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
|
||||
});
|
||||
}
|
||||
|
||||
test('folder pause does not claim success while acknowledgements are pending or retry budget expires', async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
const id = 'slow-start-folder';
|
||||
let calls = 0;
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-child`), parentTaskId: id },
|
||||
], () => ({ pauseTransfer: async () => {
|
||||
calls++;
|
||||
return { success: false, reason: 'This transfer cannot be paused yet' };
|
||||
} }));
|
||||
assert.equal(await softPauseTransfer(host, id), 'pausing');
|
||||
assert.equal(getTasks()[0].status, 'pausing');
|
||||
// Wait for the bounded startup retry budget (four 40ms delays).
|
||||
await new Promise(resolve => setTimeout(resolve, 220));
|
||||
assert.equal(calls, 5);
|
||||
assert.equal(getTasks()[0].status, 'pausing');
|
||||
assert.match(getTasks()[0].pauseUnavailableReason || '', /cannot be paused yet/);
|
||||
assert.equal(getTasks()[1].status, 'transferring');
|
||||
});
|
||||
|
||||
test('explicit resume after partial folder pause releases successful siblings and walk latch', async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
const id = 'resume-partial-folder';
|
||||
const resumed: string[] = [];
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-ok`), parentTaskId: id },
|
||||
{ ...makeTask(`${id}-bad`), parentTaskId: id },
|
||||
], () => ({
|
||||
pauseTransfer: async childId => childId.endsWith('-ok')
|
||||
? { success: true } : { success: false, reason: 'Pause rejected' },
|
||||
resumeTransfer: async childId => { resumed.push(childId); return { success: true }; },
|
||||
}));
|
||||
await softPauseTransfer(host, id);
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.equal((await softResumeTransfer(host, id)).handled, true);
|
||||
assert.equal(isTransferPauseLatched(id), false);
|
||||
assert.ok(getTasks().every(row => row.status === 'transferring'));
|
||||
assert.deepEqual(resumed.sort(), [`${id}-bad`, `${id}-ok`]);
|
||||
});
|
||||
|
||||
test('child completion during a rejected folder pause does not leave a false failure', async (t) => {
|
||||
t.after(resetTransferPauseLatchesForTests);
|
||||
const id = 'completed-during-folder-pause';
|
||||
let finish!: (result: { success: boolean; reason: string }) => void;
|
||||
const { host, getTasks } = createHost([
|
||||
{ ...makeTask(id), isDirectory: true },
|
||||
{ ...makeTask(`${id}-child`), parentTaskId: id },
|
||||
], () => ({ pauseTransfer: () => new Promise(resolve => { finish = resolve; }) }));
|
||||
await softPauseTransfer(host, id);
|
||||
host.setTasks(getTasks().map(row => row.parentTaskId ? { ...row, status: 'completed' } : row));
|
||||
finish({ success: false, reason: 'Pause rejected' });
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
assert.equal(getTasks()[0].status, 'paused');
|
||||
assert.equal(getTasks()[0].pauseUnavailableReason, undefined);
|
||||
assert.equal(getTasks()[1].status, 'completed');
|
||||
});
|
||||
@@ -184,7 +184,7 @@ export async function softPauseTransfer(
|
||||
try { globalSftpTransferScheduler.pause(id); } catch { /* best-effort */ }
|
||||
}
|
||||
|
||||
const immediateStatus = task.isDirectory ? "paused" as const : "pausing" as const;
|
||||
const immediateStatus = "pausing" as const;
|
||||
// Freeze via latch/status; leave lifecycleEpoch alone until bridge responds.
|
||||
host.setTasks(paintTreeStatus(
|
||||
host.getTasks(),
|
||||
@@ -271,7 +271,11 @@ export async function softPauseTransfer(
|
||||
if (!pauseStillCurrent()) {
|
||||
return { id, result: { success: false, reason: "Pause superseded by resume" } };
|
||||
}
|
||||
const result = await pauseOne(id);
|
||||
// A rejected IPC is a failed acknowledgement, not proof of pause.
|
||||
const result: Awaited<ReturnType<NonNullable<TransferControlBridge["pauseTransfer"]>>> = await pauseOne(id).catch((error: unknown) => ({
|
||||
success: false,
|
||||
reason: error instanceof Error ? error.message : "Could not pause transfer",
|
||||
}));
|
||||
if (wasSuperseded(result)) return { id, result };
|
||||
const live = host.getTasks().find((candidate) => candidate.id === taskId);
|
||||
const userResumed = !pauseStillCurrent()
|
||||
@@ -293,16 +297,26 @@ export async function softPauseTransfer(
|
||||
if (after.status !== "paused" && after.status !== "pausing") return;
|
||||
const byId = new Map(pauseResults.map((row) => [row.id, row.result]));
|
||||
const bridgeEpoch = maxBridgeLifecycleEpoch(pauseResults.map((row) => row.result));
|
||||
// Final directory paint: parent + unfinished children all go paused (do not
|
||||
// leave children stuck on transferring under a paused parent).
|
||||
const liveTasks = host.getTasks();
|
||||
const failed = pauseResults.filter(({ id, result }) => {
|
||||
const live = liveTasks.find((candidate) => candidate.id === id);
|
||||
return live && !["completed", "cancelled", "failed"].includes(live.status)
|
||||
&& !result.success && !isBenignPauseMiss(result.reason);
|
||||
});
|
||||
// Keep acknowledged children paused and retain the walk latch. Never
|
||||
// auto-resume siblings to roll back a partial pause. Failed children may
|
||||
// still be streaming; expose that truth and allow an explicit retry.
|
||||
const pauseFailure = failed.length > 0
|
||||
? (failed[0].result.reason || "Could not pause all folder transfers")
|
||||
: undefined;
|
||||
host.setTasks(host.getTasks().map((candidate) => {
|
||||
if (candidate.id === taskId) {
|
||||
return {
|
||||
...candidate,
|
||||
status: "paused" as const,
|
||||
status: pauseFailure ? "pausing" as const : "paused" as const,
|
||||
speed: 0,
|
||||
checkpointBytes: candidate.transferredBytes,
|
||||
pauseUnavailableReason: undefined,
|
||||
pauseUnavailableReason: pauseFailure,
|
||||
phase: undefined,
|
||||
// Bridge epoch only — control-plane pauseEpoch must not poison ingest.
|
||||
...(bridgeEpoch !== undefined ? { lifecycleEpoch: bridgeEpoch } : null),
|
||||
@@ -311,24 +325,25 @@ export async function softPauseTransfer(
|
||||
if (candidate.parentTaskId !== taskId && !backendIds.includes(candidate.id)) return candidate;
|
||||
if (["completed", "cancelled", "failed"].includes(candidate.status)) return candidate;
|
||||
const result = byId.get(candidate.id);
|
||||
const childFailed = result && !result.success && !isBenignPauseMiss(result.reason);
|
||||
const childEpoch = Number.isFinite(result?.lifecycleEpoch)
|
||||
? (result!.lifecycleEpoch as number)
|
||||
: bridgeEpoch;
|
||||
: childFailed ? undefined : bridgeEpoch;
|
||||
return {
|
||||
...candidate,
|
||||
status: "paused" as const,
|
||||
status: childFailed ? "transferring" as const : "paused" as const,
|
||||
speed: 0,
|
||||
checkpointBytes: result?.checkpointBytes ?? candidate.checkpointBytes ?? candidate.transferredBytes,
|
||||
resumeStage: result?.resumeStage ?? candidate.resumeStage,
|
||||
downloadCheckpointBytes: result?.downloadCheckpointBytes ?? candidate.downloadCheckpointBytes,
|
||||
uploadCheckpointBytes: result?.uploadCheckpointBytes ?? candidate.uploadCheckpointBytes,
|
||||
sourceFingerprint: result?.sourceFingerprint ?? candidate.sourceFingerprint,
|
||||
pauseUnavailableReason: undefined,
|
||||
pauseUnavailableReason: childFailed ? (result.reason || "Could not pause transfer") : undefined,
|
||||
...(childEpoch !== undefined ? { lifecycleEpoch: childEpoch } : null),
|
||||
};
|
||||
}));
|
||||
})().catch(() => { /* best-effort */ });
|
||||
return "paused";
|
||||
return "pausing";
|
||||
}
|
||||
|
||||
// Single-file: await soft-drain with supersede guards.
|
||||
|
||||
@@ -122,8 +122,11 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
|
||||
resetGlobals();
|
||||
const resumeCalls: string[] = [];
|
||||
let dedicatedHandlerCalls = 0;
|
||||
let acknowledgePause!: () => void;
|
||||
installBridge(t, {
|
||||
pauseTransfer: async () => ({ success: true, checkpointBytes: 5 }),
|
||||
pauseTransfer: () => new Promise((resolve) => {
|
||||
acknowledgePause = () => resolve({ success: true, checkpointBytes: 5 });
|
||||
}),
|
||||
resumeTransfer: async (id) => {
|
||||
resumeCalls.push(id);
|
||||
return { success: true };
|
||||
@@ -151,6 +154,9 @@ test("runtime soft-resumes live walk after owner teardown simulation (no dedicat
|
||||
]);
|
||||
|
||||
await runtime.pause("folder");
|
||||
assert.equal(runtime.getTask("folder")?.status, "pausing");
|
||||
acknowledgePause();
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(runtime.getTask("folder")?.status, "paused");
|
||||
assert.equal(isTransferPauseLatched("folder"), true);
|
||||
assert.equal(isTransferWalkInFlight("folder"), true);
|
||||
|
||||
@@ -1505,6 +1505,7 @@ test("pause after terminal close works without any React owner", async () => {
|
||||
|
||||
await store.pause("stale-dir");
|
||||
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "stale-dir")?.status, "paused");
|
||||
assert.equal(isTransferPauseLatched("stale-dir"), true);
|
||||
assert.ok(pauseCalls.includes("stale-child"));
|
||||
@@ -2413,6 +2414,7 @@ test("dedicated directory resume after soft-pause winds down then startFresh (no
|
||||
|
||||
// Soft-pause paints paused under dedicated-resume.
|
||||
await store.pause("dir");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "dir")?.status, "paused");
|
||||
|
||||
// Resume must cancel soft-paused children, clear sticky latches, await wind-down, then startFresh.
|
||||
@@ -2621,7 +2623,7 @@ test("async folder soft-drain does not re-pause after immediate resume", async (
|
||||
|
||||
// Pause returns immediately (async soft-drain).
|
||||
await store.pause("dir-race");
|
||||
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "paused");
|
||||
assert.equal(store.getSnapshot().tasks.find((row) => row.id === "dir-race")?.status, "pausing");
|
||||
|
||||
// User hits resume before soft-drain finishes — full store resume (bumps epoch
|
||||
// + releases latch tree), which is what the UI does.
|
||||
@@ -2690,21 +2692,33 @@ test("orphan directory pause stays latched even when some children hard-miss pau
|
||||
|
||||
await store.pause("dir");
|
||||
|
||||
// Folder pause is async: UI is paused immediately; soft-drain may still be running.
|
||||
// Folder pause stays pending until the child acknowledgements settle.
|
||||
const dir = store.getSnapshot().tasks.find((task) => task.id === "dir");
|
||||
assert.equal(dir?.status, "paused", "folder parent must paint paused without waiting on children");
|
||||
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-ok")?.status, "paused");
|
||||
assert.equal(store.getSnapshot().tasks.find((task) => task.id === "c-fail")?.status, "paused");
|
||||
// Soft-drain is fire-and-forget — give it a tick to hit the bridge.
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
assert.equal(dir?.status, "pausing");
|
||||
const ownerSnapshotDuringDrain = store.getSnapshot().tasks.map((row) => ({ ...row }));
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
assert.equal(store.getTask("c-ok")?.status, "paused");
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
assert.deepEqual(pauseCalls.sort(), ["c-fail", "c-ok"]);
|
||||
// Latch-first: do not bridge-resume partial successes (that re-opened the queue).
|
||||
assert.deepEqual(resumeCalls, []);
|
||||
assert.equal(
|
||||
store.getSnapshot().tasks.find((task) => task.id === "dir")?.status,
|
||||
"paused",
|
||||
"hard-miss soft-drain must not demote folder out of paused",
|
||||
"pausing",
|
||||
"hard miss keeps the folder latched without claiming a successful pause",
|
||||
);
|
||||
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
|
||||
store.publishOwner("dedicated-resume", ownerSnapshotDuringDrain);
|
||||
assert.equal(store.getTask("dir")?.status, "pausing");
|
||||
assert.equal(store.getTask("dir")?.pauseUnavailableReason, "This transfer cannot be paused safely");
|
||||
assert.equal(store.getTask("c-ok")?.status, "paused");
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
store.ingestBackgroundEvent({ type: "progress", transferId: "c-fail", transferred: 25, speed: 10 });
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
assert.equal(store.getTask("c-fail")?.transferredBytes, 25);
|
||||
store.patchTask("c-fail", { transferredBytes: 50, speed: 10 });
|
||||
assert.equal(store.getTask("c-fail")?.status, "transferring");
|
||||
assert.equal(store.getTask("c-fail")?.transferredBytes, 50);
|
||||
});
|
||||
|
||||
test("dedicated resume source-changed marks attention and can reset checkpoint", async () => {
|
||||
|
||||
@@ -353,7 +353,22 @@ export function mergeOwnerPublishedTask(
|
||||
// Only a strictly newer lifecycle epoch may re-open transferring (resume).
|
||||
const incomingPaused = incoming.status === "paused" || incoming.status === "pausing";
|
||||
const existingPaused = existing.status === "paused" || existing.status === "pausing";
|
||||
if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
|
||||
// The panel can publish a snapshot from before the child acknowledgements
|
||||
// arrived. Only a newer control decision may clear the folder's failure.
|
||||
const rejectedFolderPause = existing.isDirectory && !existing.parentTaskId
|
||||
&& existing.status === "pausing" && !!existing.pauseUnavailableReason
|
||||
&& incomingLifecycleEpoch <= existingLifecycleEpoch
|
||||
&& isTransferPauseLatched(existing.id);
|
||||
const rejectedChildPause = parentStatus === "pausing"
|
||||
&& !!existing.parentTaskId && existing.status === "transferring" && !!existing.pauseUnavailableReason;
|
||||
if (rejectedFolderPause) {
|
||||
merged.status = "pausing";
|
||||
merged.speed = 0;
|
||||
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
|
||||
} else if (rejectedChildPause && incomingLifecycleEpoch <= existingLifecycleEpoch) {
|
||||
merged.status = "transferring";
|
||||
merged.pauseUnavailableReason = existing.pauseUnavailableReason;
|
||||
} else if (incomingPaused && incomingLifecycleEpoch >= existingLifecycleEpoch) {
|
||||
merged.status = incoming.status;
|
||||
merged.speed = 0;
|
||||
// Pin the visible bar while paused/latched. Soft-drain must not keep
|
||||
@@ -392,6 +407,7 @@ export function mergeOwnerPublishedTask(
|
||||
const parentHoldsPause = parentStatus === "paused" || parentStatus === "pausing";
|
||||
if (
|
||||
parentHoldsPause
|
||||
&& !rejectedChildPause
|
||||
&& !["completed", "cancelled", "failed"].includes(merged.status)
|
||||
&& (merged.status === "transferring" || merged.status === "pending" || merged.status === "queued")
|
||||
) {
|
||||
@@ -1722,17 +1738,15 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
// Soft-drain / walk progress must not move the visible bar after Pause.
|
||||
// Latch or paused/pausing freezes transferredBytes/speed unless this patch
|
||||
// is an explicit resume (transferring + epoch, or dedicated-resume).
|
||||
const pauseHeld = isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|
||||
const parent = task.parentTaskId ? tasks.find((candidate) => candidate.id === task.parentTaskId) : undefined;
|
||||
const rejectedChildPause = parent?.status === "pausing" && !!parent.pauseUnavailableReason
|
||||
&& task.status === "transferring" && !!task.pauseUnavailableReason;
|
||||
const pauseHeld = !rejectedChildPause && (isTransferOrRootPauseLatched(task.parentTaskId ?? task.id, task.id)
|
||||
|| isTransferPauseLatched(task.id)
|
||||
|| task.status === "paused"
|
||||
|| task.status === "pausing"
|
||||
|| (!!task.parentTaskId && (
|
||||
isTransferPauseLatched(task.parentTaskId)
|
||||
|| (() => {
|
||||
const parent = tasks.find((candidate) => candidate.id === task.parentTaskId);
|
||||
return parent?.status === "paused" || parent?.status === "pausing";
|
||||
})()
|
||||
));
|
||||
|| parent?.status === "paused"
|
||||
|| parent?.status === "pausing");
|
||||
if (pauseHeld && !explicitResume) {
|
||||
// Keep lifecycle at paused/pausing; allow checkpoint metadata only.
|
||||
if (task.status === "pausing" || task.status === "paused") {
|
||||
@@ -2451,10 +2465,12 @@ export function createSftpTransferCenterStore(persistence?: StorePersistence): S
|
||||
task.parentTaskId ?? task.id,
|
||||
task.id,
|
||||
) || isTransferPauseLatched(task.id);
|
||||
const uiPauseLatched = task.status === "paused"
|
||||
const rejectedChildPause = parentRow?.status === "pausing" && !!parentRow.pauseUnavailableReason
|
||||
&& task.status === "transferring" && !!task.pauseUnavailableReason;
|
||||
const uiPauseLatched = !rejectedChildPause && (task.status === "paused"
|
||||
|| task.status === "pausing"
|
||||
|| parentHoldsPause
|
||||
|| selfLatched;
|
||||
|| selfLatched);
|
||||
const explicitResume = lifecycleStatus === "transferring"
|
||||
&& event.lifecycleEpoch !== undefined
|
||||
&& incomingEpoch > currentEpoch;
|
||||
|
||||
@@ -55,7 +55,7 @@ interface AIChatPanelContentProps {
|
||||
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
|
||||
inputValue: string;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: () => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
onRenameSession?: (sessionId: string, title: string) => void;
|
||||
@@ -211,6 +211,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
parked = false,
|
||||
sending = false,
|
||||
}) => {
|
||||
const handleContinue = React.useCallback(() => handleSend(t('ai.chat.continue')), [handleSend, t]);
|
||||
const mentionHosts = React.useMemo(
|
||||
() => terminalSessions.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
@@ -345,6 +346,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
<ChatMessageList
|
||||
messages={messages}
|
||||
isStreaming={isStreaming}
|
||||
onContinue={handleContinue}
|
||||
activeSessionId={activeSessionId}
|
||||
activeCompaction={activeCompaction}
|
||||
contextCompaction={activeSession?.contextCompaction}
|
||||
|
||||
@@ -1610,14 +1610,14 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
|
||||
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
const handleSend = useCallback(async (textOverride?: string) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
const currentSessionView = activeSessionRef.current;
|
||||
if (!validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const trimmed = draft?.text.trim() ?? '';
|
||||
if (textOverride === undefined && !validateNoteMentions(draft?.attachments ?? [])) return;
|
||||
const trimmed = (textOverride ?? draft?.text ?? '').trim();
|
||||
const sendScopeKey = scopeKey;
|
||||
const attachments = (draft?.attachments ?? []).map((file) => ({
|
||||
const attachments = (textOverride === undefined ? draft?.attachments ?? [] : []).map((file) => ({
|
||||
base64Data: file.base64Data,
|
||||
mediaType: file.mediaType,
|
||||
filename: file.filename,
|
||||
@@ -1645,12 +1645,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const agentConfig = sendAgentId !== 'catty' ? findEnabledExternalAgent(externalAgents, sendAgentId) : undefined;
|
||||
if (sendAgentId !== 'catty' && !agentConfig) return;
|
||||
|
||||
const selectedSkillSlugs = draft?.selectedUserSkillSlugs ?? [];
|
||||
const selectedSkillSlugs = textOverride === undefined ? draft?.selectedUserSkillSlugs ?? [] : [];
|
||||
const modelPrompt = buildPromptWithTerminalSelectionAttachments(trimmed, attachments);
|
||||
const modelAttachments = attachments.filter((attachment) => !isInlineTextAttachment(attachment));
|
||||
const isDraftMode = currentPanelView.mode === 'draft';
|
||||
|
||||
flushDraftText();
|
||||
if (textOverride === undefined) flushDraftText();
|
||||
const submittedText = draft?.text ?? '';
|
||||
const keepPendingAfterSend = () => {
|
||||
const pending = pendingComposerTextRef.current;
|
||||
@@ -1739,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const createdSession = createSession(scope, sendAgentId);
|
||||
sessionId = createdSession.id;
|
||||
currentSession = createdSession;
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(createdSession.id);
|
||||
setActiveSessionId(createdSession.id);
|
||||
sessionSendGateKey = sessionId;
|
||||
@@ -1770,7 +1770,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProvider'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1785,7 +1785,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
});
|
||||
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProviderModel'), timestamp: Date.now() });
|
||||
if (currentPanelView.mode === 'session') {
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
}
|
||||
return;
|
||||
@@ -1798,7 +1798,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
...(selectedSkillSlugs.length > 0 ? { selectedUserSkillSlugs: selectedSkillSlugs } : {}),
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
if (textOverride === undefined) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
showScopeSessionView(sessionId);
|
||||
setActiveSessionId(sessionId);
|
||||
setStreamingForScope(sessionId, true);
|
||||
|
||||
@@ -436,7 +436,7 @@ function TransferRow({
|
||||
task: TransferTask;
|
||||
children: TransferTask[];
|
||||
} | null>(null);
|
||||
if (task.status === "pausing") {
|
||||
if (task.status === "pausing" && !task.pauseUnavailableReason) {
|
||||
if (!pausingSnapshotRef.current) {
|
||||
pausingSnapshotRef.current = {
|
||||
task: { ...task },
|
||||
@@ -464,20 +464,23 @@ function TransferRow({
|
||||
&& !task.error;
|
||||
const sharedResuming = useSftpTransferResuming(task.id);
|
||||
const isResuming = sharedResuming || storeResuming;
|
||||
const canPause = task.resumable !== false && task.status === "transferring" && canControl && !isResuming;
|
||||
const pauseFailed = task.status === "pausing" && !!task.pauseUnavailableReason;
|
||||
const canPause = task.resumable !== false && (task.status === "transferring" || pauseFailed) && canControl && !isResuming;
|
||||
// Orphaned tasks after app restart (interrupted / attention / paused without a
|
||||
// live panel owner) must still expose resume/cancel from the global center.
|
||||
// Conflict rows must use resolveConflict — Resume would overwrite blindly.
|
||||
// Non-resumable attention rows (e.g. duplicate-destination refusals) are
|
||||
// terminal: resuming them would start a second writer on the same path.
|
||||
// Do not show Resume during soft-drain "pausing" — play + spinner together
|
||||
// makes the row twitch as buttons appear/disappear mid-drain.
|
||||
// makes the row twitch as buttons appear/disappear mid-drain. A settled
|
||||
// partial failure is different: offer Retry Pause and explicit Resume.
|
||||
const canResume = !isResuming && !task.conflict && (
|
||||
["paused", "interrupted"].includes(task.status)
|
||||
|| (pauseFailed && task.resumable !== false)
|
||||
|| (task.status === "attention" && task.resumable !== false)
|
||||
|| (task.status === "failed" && task.resumable !== false && (task.checkpointBytes ?? 0) > 0)
|
||||
) && canControl;
|
||||
const isPausing = task.status === "pausing";
|
||||
const isPausing = task.status === "pausing" && !pauseFailed;
|
||||
const canCancel = ["pending", "queued", "transferring", "pausing", "paused", "interrupted", "attention"].includes(task.status) && canControl;
|
||||
const canRetry = task.status === "failed" && task.retryable !== false && canControl;
|
||||
const isTerminal = ["completed", "failed", "cancelled"].includes(task.status);
|
||||
@@ -577,7 +580,7 @@ function TransferRow({
|
||||
<Pause size={13} />
|
||||
</TransferAction>
|
||||
)}
|
||||
{task.status === "pausing" && (
|
||||
{task.status === "pausing" && !pauseFailed && (
|
||||
<div className="flex h-8 w-8 items-center justify-center" role="status" aria-label={t("sftp.transferCenter.status.pausing")}>
|
||||
<Loader2 size={13} className="animate-spin text-amber-500" />
|
||||
</div>
|
||||
|
||||
@@ -550,6 +550,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
{mountedTabs.has("appearance") && (
|
||||
<SettingsLazyTab value="appearance">
|
||||
<LazySettingsAppearanceTab
|
||||
pluginRuntimeAvailable={pluginRuntimeAvailable}
|
||||
theme={settings.theme}
|
||||
resolvedTheme={settings.resolvedTheme}
|
||||
setTheme={settings.setTheme}
|
||||
|
||||
@@ -206,6 +206,23 @@ test("surfaces pause unavailable reason on a transferring row", () => {
|
||||
assert.match(markup, /This transfer cannot be paused yet/);
|
||||
});
|
||||
|
||||
test("shows a settled folder pause failure with retry and resume instead of a spinner", () => {
|
||||
const markup = renderTransferItem({
|
||||
...baseTask,
|
||||
isDirectory: true,
|
||||
status: "pausing",
|
||||
error: undefined,
|
||||
speed: 0,
|
||||
resumable: true,
|
||||
pauseUnavailableReason: "This transfer cannot be paused yet",
|
||||
}, { onPause: () => {}, onResume: () => {} });
|
||||
|
||||
assert.match(markup, /This transfer cannot be paused yet/);
|
||||
assert.match(markup, /aria-label="Pause: archive\.tar\.gz"/);
|
||||
assert.match(markup, /aria-label="Resume: archive\.tar\.gz"/);
|
||||
assert.doesNotMatch(markup, /aria-busy="true"|aria-label="Pausing:/);
|
||||
});
|
||||
|
||||
test("renders child resize handle as a keyboard-reachable separator", () => {
|
||||
const markup = renderTransferItem(
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
|
||||
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
|
||||
import type { ChatMessage } from "../../infrastructure/ai/types.ts";
|
||||
@@ -644,3 +645,64 @@ test('fork is offered only for safe completed replies and hidden while streaming
|
||||
assert.equal((render(false).match(/Fork from here/g) ?? []).length, 1);
|
||||
assert.equal((render(true).match(/Fork from here/g) ?? []).length, 0);
|
||||
});
|
||||
|
||||
test('ChatMessageList renders a non-error iteration limit notice with a Continue action', () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ id: 'poll', role: 'tool', content: '', timestamp: 1,
|
||||
toolResults: [{ toolCallId: 'poll-1', content: '{"jobId":"job-1","status":"running"}' }] },
|
||||
{ id: 'limit', role: 'assistant', content: '', timestamp: 2, iterationLimit: 20 },
|
||||
];
|
||||
const render = (isStreaming: boolean) => renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<ChatMessageList messages={messages} isStreaming={isStreaming} onContinue={() => {}} />
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
const markup = render(false);
|
||||
assert.match(markup, /Tool-loop limit \(20 iterations\) reached/);
|
||||
assert.match(markup, /<button[^>]*>Continue<\/button>/);
|
||||
assert.doesNotMatch(markup, /bg-destructive/);
|
||||
assert.match(render(true), /<button[^>]*disabled=""[^>]*>Continue<\/button>/);
|
||||
|
||||
const source = readFileSync(new URL('./ChatMessageList.tsx', import.meta.url), 'utf8');
|
||||
const panel = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
|
||||
const sidePanel = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /onClick=\{onContinue\}/);
|
||||
assert.match(panel, /onContinue=\{handleContinue\}/);
|
||||
assert.match(panel, /handleContinue = React.useCallback\(\(\) => handleSend\(t\('ai.chat.continue'\)\)/);
|
||||
assert.match(sidePanel, /const handleSend = useCallback\(async \(textOverride\?: string\)/);
|
||||
assert.match(sidePanel, /const trimmed = \(textOverride \?\? draft\?\.text \?\? ''\)\.trim\(\)/);
|
||||
});
|
||||
|
||||
test('iteration limit Continue button invokes the provided send callback', async t => {
|
||||
const previousWindow = globalThis.window;
|
||||
const actGlobal = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previousActEnvironment = actGlobal.IS_REACT_ACT_ENVIRONMENT;
|
||||
globalThis.window = { setTimeout, clearTimeout } as unknown as Window & typeof globalThis;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
t.after(() => {
|
||||
globalThis.window = previousWindow;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
});
|
||||
let continued = 0;
|
||||
let renderer: ReactTestRenderer;
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<ChatMessageList
|
||||
messages={[{ id: 'limit', role: 'assistant', content: '', timestamp: 1, iterationLimit: 20 }]}
|
||||
onContinue={() => { continued += 1; }}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
const button = renderer!.root.findAllByType('button').find(node => node.children.includes('Continue'));
|
||||
assert.ok(button);
|
||||
assert.equal(button.props.disabled, false);
|
||||
await act(async () => { button.props.onClick(); });
|
||||
assert.equal(continued, 1);
|
||||
await act(async () => { renderer!.unmount(); });
|
||||
});
|
||||
@@ -90,6 +90,7 @@ import ChatJumpNav from './ChatJumpNav';
|
||||
interface ChatMessageListProps {
|
||||
messages: ChatMessage[];
|
||||
isStreaming?: boolean;
|
||||
onContinue?: () => void;
|
||||
/** Active chat session ID — used to filter standalone MCP approval blocks */
|
||||
activeSessionId?: string | null;
|
||||
activeCompaction?: ActiveCompactionUi | null;
|
||||
@@ -185,6 +186,7 @@ export function pruneResolvedApprovals(
|
||||
const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
messages,
|
||||
isStreaming,
|
||||
onContinue,
|
||||
activeSessionId,
|
||||
activeCompaction = null,
|
||||
contextCompaction,
|
||||
@@ -813,6 +815,18 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{message.iterationLimit != null && (
|
||||
<div role="status" className="rounded-md border border-border/60 bg-muted/30 px-3 py-2 text-sm">
|
||||
<p>{t('ai.chat.iterationLimitReached', { limit: message.iterationLimit })}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onContinue}
|
||||
disabled={!!isStreaming || !onContinue}
|
||||
className="mt-2 rounded-md border border-border px-2 py-1 text-xs font-medium hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>{t('ai.chat.continue')}</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error info */}
|
||||
{message.errorInfo && (
|
||||
<div className="flex items-start gap-2 px-3 py-2 rounded-md bg-destructive/10 border border-destructive/20 text-sm">
|
||||
@@ -1079,6 +1093,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
|
||||
function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps): boolean {
|
||||
if (prev.isStreaming !== next.isStreaming) return false;
|
||||
if (prev.onContinue !== next.onContinue) return false;
|
||||
if (prev.activeSessionId !== next.activeSessionId) return false;
|
||||
if (prev.notes !== next.notes) return false;
|
||||
if (prev.hosts !== next.hosts) return false;
|
||||
@@ -1107,6 +1122,7 @@ function areMessagesEqual(prev: ChatMessageListProps, next: ChatMessageListProps
|
||||
p.statusText !== n.statusText ||
|
||||
p.executionStatus !== n.executionStatus ||
|
||||
p.errorInfo !== n.errorInfo ||
|
||||
p.iterationLimit !== n.iterationLimit ||
|
||||
p.toolCalls !== n.toolCalls ||
|
||||
p.toolResults !== n.toolResults ||
|
||||
p.agentActivities !== n.agentActivities ||
|
||||
|
||||
@@ -71,6 +71,30 @@ test('buildManagedAgentState keeps unrelated defaults when removing stale manage
|
||||
assert.equal(state.defaultAgentId, 'custom-agent');
|
||||
});
|
||||
|
||||
test('a failed saved-path probe keeps the override, preferences, and default until recovery', () => {
|
||||
const agent: ExternalAgentConfig = {
|
||||
id: 'discovered_copilot',
|
||||
name: 'GitHub Copilot CLI',
|
||||
command: 'C:/npm/copilot.cmd',
|
||||
commandSource: 'manual',
|
||||
sdkBackend: 'copilot',
|
||||
enabled: false,
|
||||
available: true,
|
||||
};
|
||||
const unavailable = buildManagedAgentState([agent], agent.id, 'copilot', null, 'manual');
|
||||
assert.deepEqual(unavailable.agents, [{ ...agent, available: false }]);
|
||||
assert.equal(unavailable.defaultAgentId, agent.id);
|
||||
assert.equal(getInitialManagedAgentPaths(unavailable.agents).copilot, agent.command);
|
||||
|
||||
const recovered = buildManagedAgentState(unavailable.agents, agent.id, 'copilot', {
|
||||
path: agent.command, version: '1.0.106', available: true,
|
||||
}, 'manual');
|
||||
assert.equal(recovered.agents[0].available, true);
|
||||
assert.equal(recovered.agents[0].enabled, false);
|
||||
assert.equal(recovered.defaultAgentId, agent.id);
|
||||
assert.deepEqual(buildManagedAgentState(recovered.agents, agent.id, 'copilot', null, 'auto').agents, []);
|
||||
});
|
||||
|
||||
test('buildManagedAgentState stores the system Claude executable for SDK runs', () => {
|
||||
const state = buildManagedAgentState(
|
||||
[],
|
||||
|
||||
@@ -392,10 +392,9 @@ test("note editor exposes its modes from a borderless title-row dropdown", () =>
|
||||
// The app-owned NoteToolbar (not MDXEditor's toolbarPlugin) hosts the
|
||||
// formatting controls; MDXEditor must not render its own toolbar.
|
||||
assert.doesNotMatch(source, /toolbarPlugin\(/);
|
||||
assert.match(toolbarSource, /onAction\?\.\("undo"\)/);
|
||||
assert.match(toolbarSource, /onAction\?\.\("redo"\)/);
|
||||
assert.match(toolbarSource, /<Undo2 size=\{14\} \/>/);
|
||||
assert.match(toolbarSource, /<Redo2 size=\{14\} \/>/);
|
||||
assert.match(toolbarSource, /id: "undo", icon: Undo2/);
|
||||
assert.match(toolbarSource, /id: "redo", icon: Redo2/);
|
||||
assert.match(toolbarSource, /onAction\?\.\(item\.id\)/);
|
||||
// Preview and edit both use MDXEditor (readOnly in preview).
|
||||
assert.match(source, /readOnly=\{editorMode === "preview"\}/);
|
||||
assert.match(source, /key=\{editorMode\}/);
|
||||
@@ -439,24 +438,10 @@ test("note markdown toolbar remains usable in narrow panes", () => {
|
||||
styles,
|
||||
/\.netcatty-mdx-editor\s*\{[^}]*transform:\s*translateZ\(0\);/s,
|
||||
);
|
||||
// The app-owned NoteToolbar scrolls horizontally when the pane is narrow so
|
||||
// formatting buttons are never clipped; the scrollbar stays visible.
|
||||
assert.match(
|
||||
toolbarSource,
|
||||
/overflow-x-auto [^"]*\[scrollbar-width:thin\]/,
|
||||
);
|
||||
assert.match(
|
||||
toolbarSource,
|
||||
/\[&::-webkit-scrollbar\]:h-1\.5/,
|
||||
);
|
||||
assert.match(
|
||||
toolbarSource,
|
||||
/\[&::-webkit-scrollbar-thumb\]:bg-border\/70/,
|
||||
);
|
||||
assert.match(
|
||||
toolbarSource,
|
||||
/flex flex-1 items-center gap-0\.5 min-w-0 overflow-x-auto/,
|
||||
);
|
||||
// The app-owned NoteToolbar collapses excess controls into the shared menu.
|
||||
assert.match(toolbarSource, /<ToolbarOverflowMenu/);
|
||||
assert.match(toolbarSource, /data-note-format-toolbar/);
|
||||
assert.doesNotMatch(toolbarSource, /overflow-x-auto|scrollbar-width:thin|webkit-scrollbar/);
|
||||
});
|
||||
|
||||
test("MDX link dialog overlay stays inside the retained notes editor container", () => {
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JSDOM } from "jsdom";
|
||||
|
||||
test("NoteToolbar fits formatting controls to the available row width", async (t) => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
pretendToBeVisual: true,
|
||||
url: "http://localhost",
|
||||
});
|
||||
const { window } = dom;
|
||||
const previousGlobals = new Map<string, PropertyDescriptor | undefined>();
|
||||
const installGlobal = (key: string, value: unknown) => {
|
||||
previousGlobals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
let rowWidth = 900;
|
||||
const observers = new Set<ResizeObserverStub>();
|
||||
class ResizeObserverStub {
|
||||
target: Element | null = null;
|
||||
constructor(readonly callback: ResizeObserverCallback) { observers.add(this); }
|
||||
observe(target: Element) { this.target = target; }
|
||||
unobserve() { this.target = null; }
|
||||
disconnect() { observers.delete(this); }
|
||||
}
|
||||
const originalRect = window.HTMLElement.prototype.getBoundingClientRect;
|
||||
window.HTMLElement.prototype.getBoundingClientRect = function () {
|
||||
if (this.hasAttribute("data-note-format-toolbar")) {
|
||||
return new window.DOMRect(0, 0, rowWidth, 26);
|
||||
}
|
||||
return originalRect.call(this);
|
||||
};
|
||||
for (const key of [
|
||||
"document", "navigator", "HTMLElement", "HTMLInputElement", "HTMLButtonElement",
|
||||
"Element", "SVGElement", "Node", "NodeFilter", "MutationObserver", "CustomEvent",
|
||||
"Event", "MouseEvent", "DOMRect",
|
||||
]) {
|
||||
installGlobal(key, window[key as keyof typeof window]);
|
||||
}
|
||||
installGlobal("window", window);
|
||||
installGlobal("getComputedStyle", window.getComputedStyle.bind(window));
|
||||
installGlobal("requestAnimationFrame", window.requestAnimationFrame.bind(window));
|
||||
installGlobal("cancelAnimationFrame", window.cancelAnimationFrame.bind(window));
|
||||
installGlobal("ResizeObserver", ResizeObserverStub);
|
||||
installGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
|
||||
const { default: React, act } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
|
||||
const { TooltipProvider } = await import("../ui/tooltip.tsx");
|
||||
const { NoteToolbar } = await import("./NoteToolbar.tsx");
|
||||
const { EMPTY_ACTIVE_FORMATS } = await import("./noteEditorTypes.ts");
|
||||
const root = createRoot(window.document.getElementById("root")!);
|
||||
const actions: string[] = [];
|
||||
const sizes: number[] = [];
|
||||
const codeSizes: number[] = [];
|
||||
const fonts: string[] = [];
|
||||
const render = async (mode: "edit" | "source" | "preview" = "edit") => {
|
||||
await act(async () => root.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<NoteToolbar
|
||||
editorMode={mode}
|
||||
onAction={(action) => actions.push(action)}
|
||||
onChangeNoteFontFamily={(font) => fonts.push(font)}
|
||||
onChangeNoteFontSize={(size) => sizes.push(size)}
|
||||
onChangeNoteCodeFontSize={(size) => codeSizes.push(size)}
|
||||
activeFormats={{ ...EMPTY_ACTIVE_FORMATS, bold: true }}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
));
|
||||
};
|
||||
const row = (): HTMLElement => {
|
||||
const element = window.document.querySelector<HTMLElement>("[data-note-format-toolbar]");
|
||||
assert.ok(element);
|
||||
assert.ok(element.classList.contains("overflow-hidden"));
|
||||
assert.doesNotMatch(element.className, /overflow-x-auto|overflow-auto|scrollbar/);
|
||||
assert.ok(!element.classList.contains("flex-wrap"));
|
||||
return element;
|
||||
};
|
||||
const button = (label: string, parent: ParentNode = window.document) => {
|
||||
const element = Array.from(parent.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((candidate) => candidate.title === label || candidate.textContent?.trim() === label);
|
||||
assert.ok(element, `${label} should be reachable`);
|
||||
return element;
|
||||
};
|
||||
const click = async (element: HTMLElement) => {
|
||||
await act(async () => {
|
||||
element.click();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 70));
|
||||
});
|
||||
};
|
||||
const resize = async (width: number) => {
|
||||
rowWidth = width;
|
||||
await act(async () => {
|
||||
for (const observer of observers) {
|
||||
if (observer.target?.hasAttribute("data-note-format-toolbar")) {
|
||||
observer.callback([{
|
||||
target: observer.target,
|
||||
contentRect: new window.DOMRect(0, 0, width, 26),
|
||||
} as ResizeObserverEntry], observer as unknown as ResizeObserver);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
const openOverflow = async (): Promise<HTMLElement> => {
|
||||
const trigger = row().querySelector<HTMLButtonElement>("[data-toolbar-overflow-trigger]");
|
||||
assert.ok(trigger);
|
||||
await click(trigger);
|
||||
const menu = window.document.querySelector<HTMLElement>("[data-toolbar-overflow-menu]");
|
||||
assert.ok(menu);
|
||||
return menu;
|
||||
};
|
||||
|
||||
try {
|
||||
await render();
|
||||
const defaultOrder = Array.from(row().querySelectorAll("button"), (element) => element.title);
|
||||
|
||||
await t.test("wide row preserves all controls inline without a scrollbar track", async () => {
|
||||
assert.equal(defaultOrder.length, 19);
|
||||
assert.deepEqual(defaultOrder.slice(0, 5), ["Undo (Ctrl+Z)", "Redo (Ctrl+Y)", "Code font and typography settings", "Heading Level", "Bold (Ctrl+B)"]);
|
||||
assert.equal(defaultOrder.at(-1), "Insert Image");
|
||||
assert.equal(row().querySelector("[data-toolbar-overflow-trigger]"), null);
|
||||
assert.ok(button("Bold (Ctrl+B)", row()).classList.contains("bg-primary/15"));
|
||||
const mouseDown = new window.MouseEvent("mousedown", { bubbles: true, cancelable: true });
|
||||
button("Bold (Ctrl+B)", row()).dispatchEvent(mouseDown);
|
||||
assert.equal(mouseDown.defaultPrevented, true, "formatting preserves the editor selection");
|
||||
await click(button("Bold (Ctrl+B)", row()));
|
||||
assert.equal(actions.at(-1), "bold");
|
||||
});
|
||||
|
||||
await t.test("narrow row spills the end of the existing order and keeps every action reachable", async () => {
|
||||
await resize(320);
|
||||
const inlineLabels = Array.from(row().querySelectorAll<HTMLButtonElement>("button[title]"), (element) => element.title);
|
||||
assert.ok(inlineLabels.length < defaultOrder.length);
|
||||
assert.deepEqual(inlineLabels, defaultOrder.slice(0, inlineLabels.length));
|
||||
const menu = await openOverflow();
|
||||
const overflowLabels = Array.from(menu.querySelectorAll("button"), (element) => element.title);
|
||||
assert.deepEqual([...inlineLabels, ...overflowLabels], defaultOrder);
|
||||
const expectedActions = ["bullet", "number", "task", "quote", "codeblock", "math", "table", "divider", "link", "image"];
|
||||
for (let index = 0; index < overflowLabels.length; index += 1) {
|
||||
const currentMenu = index === 0 ? menu : await openOverflow();
|
||||
await click(button(overflowLabels[index], currentMenu));
|
||||
assert.equal(actions.at(-1), expectedActions[index]);
|
||||
assert.equal(window.document.querySelector("[data-toolbar-overflow-menu]"), null);
|
||||
}
|
||||
});
|
||||
|
||||
await t.test("very narrow row exposes undo, headings, and typography through nested overflow menus", async () => {
|
||||
await resize(26);
|
||||
assert.equal(row().querySelectorAll("button").length, 1);
|
||||
await click(button("Undo (Ctrl+Z)", await openOverflow()));
|
||||
assert.equal(actions.at(-1), "undo");
|
||||
await click(button("Redo (Ctrl+Y)", await openOverflow()));
|
||||
assert.equal(actions.at(-1), "redo");
|
||||
|
||||
await click(button("Heading Level", await openOverflow()));
|
||||
assert.ok(window.document.querySelector("[data-toolbar-overflow-menu]"));
|
||||
let nested = window.document.querySelector<HTMLElement>("[data-toolbar-nested-menu]");
|
||||
assert.ok(nested);
|
||||
await click(nested.querySelector<HTMLButtonElement>("button")!);
|
||||
assert.equal(actions.at(-1), "h1");
|
||||
assert.equal(window.document.querySelector("[data-toolbar-overflow-menu]"), null);
|
||||
|
||||
for (const setting of ["font", "body", "code"] as const) {
|
||||
await click(button("Code font and typography settings", await openOverflow()));
|
||||
nested = window.document.querySelector<HTMLElement>("[data-toolbar-nested-menu]");
|
||||
assert.ok(nested);
|
||||
assert.ok(window.document.querySelector("[data-toolbar-overflow-menu]"));
|
||||
const sections = nested.children;
|
||||
const section = sections[setting === "font" ? 0 : setting === "body" ? 1 : 2];
|
||||
await click(section.querySelector<HTMLButtonElement>("button")!);
|
||||
assert.equal(window.document.querySelector("[data-toolbar-overflow-menu]"), null);
|
||||
}
|
||||
assert.deepEqual(fonts, [""]);
|
||||
assert.deepEqual(sizes, [12]);
|
||||
assert.deepEqual(codeSizes, [11]);
|
||||
});
|
||||
|
||||
await t.test("resizing back to wide restores controls and removes the overflow trigger", async () => {
|
||||
await resize(900);
|
||||
assert.deepEqual(Array.from(row().querySelectorAll("button"), (element) => element.title), defaultOrder);
|
||||
assert.equal(row().querySelector("[data-toolbar-overflow-trigger]"), null);
|
||||
});
|
||||
|
||||
await t.test("source mode and returning from preview remeasure the same format row", async () => {
|
||||
await render("preview");
|
||||
assert.equal(window.document.querySelector("[data-note-format-toolbar]"), null);
|
||||
rowWidth = 200;
|
||||
await render("source");
|
||||
const menu = await openOverflow();
|
||||
assert.ok(button("Bold (Ctrl+B)", row()).classList.contains("bg-primary/15"));
|
||||
await click(button("Insert Image", menu));
|
||||
assert.equal(actions.at(-1), "image");
|
||||
});
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
||||
});
|
||||
assert.equal(observers.size, 0);
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previousGlobals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("full notes and the sidebar overlay both render the shared format toolbar", async () => {
|
||||
const { renderToStaticMarkup } = await import("react-dom/server");
|
||||
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
|
||||
const { TooltipProvider } = await import("../ui/tooltip.tsx");
|
||||
const { NotesManager } = await import("./NotesManager.tsx");
|
||||
for (const displayMode of ["full", "sidebar"] as const) {
|
||||
const markup = renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<NotesManager
|
||||
notes={[{ id: "note-1", title: "Test note", content: "# Note", group: "", createdAt: 1, updatedAt: 1, order: 1 }]}
|
||||
noteGroups={[]}
|
||||
hosts={[]}
|
||||
onUpdateNotes={() => undefined}
|
||||
onUpdateNoteGroups={() => undefined}
|
||||
displayMode={displayMode}
|
||||
openNoteId="note-1"
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
const dom = new JSDOM(markup);
|
||||
try {
|
||||
const rows = dom.window.document.querySelectorAll("[data-note-format-toolbar]");
|
||||
assert.equal(rows.length, 1, `${displayMode} should use NoteToolbar`);
|
||||
assert.doesNotMatch(rows[0].className, /overflow-x-auto|overflow-auto|scrollbar/);
|
||||
assert.equal(rows[0].querySelectorAll("button").length, 19);
|
||||
assert.equal(dom.window.document.querySelector("[data-note-title-row] button[title='Undo (Ctrl+Z)']"), null);
|
||||
} finally {
|
||||
dom.window.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
+288
-348
@@ -28,13 +28,14 @@ import {
|
||||
Underline,
|
||||
Undo2,
|
||||
} from "lucide-react";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import React, { useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { type MarkdownActionType } from "../../domain/notes";
|
||||
import { useAvailableFonts } from "../../application/state/fontStore";
|
||||
import { useI18n } from "../../application/i18n/I18nProvider";
|
||||
import type { ActiveTextFormats, NoteEditorMode } from "./noteEditorTypes";
|
||||
import { EMPTY_ACTIVE_FORMATS } from "./noteEditorTypes";
|
||||
import { Dropdown, DropdownContent, DropdownTrigger } from "../ui/dropdown";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
||||
import { ToolbarOverflowMenu, useToolbarOverflowClose } from "../ui/toolbar-item-layout";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger } from "../ui/select";
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
@@ -62,6 +63,76 @@ export interface NoteModeDropdownProps {
|
||||
const FONT_SIZES = [12, 13, 14, 15, 16, 18, 20];
|
||||
const CODE_FONT_SIZES = [11, 12, 13, 14, 15, 16, 18];
|
||||
|
||||
const toolbarButtonClass = "flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors";
|
||||
const overflowItemClass = "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors";
|
||||
|
||||
// Preserve the format row's visual order, including the existing group boundaries.
|
||||
const FORMAT_ITEMS = [
|
||||
{ id: "undo", icon: Undo2, label: "undo" },
|
||||
{ id: "redo", icon: Redo2, label: "redo" },
|
||||
{ id: "typography", icon: Type, label: "typography", separator: true },
|
||||
{ id: "heading", icon: Heading, label: "headingLevel" },
|
||||
{ id: "bold", icon: Bold, label: "bold", format: "bold" },
|
||||
{ id: "italic", icon: Italic, label: "italic", format: "italic" },
|
||||
{ id: "strikethrough", icon: Strikethrough, label: "strikethrough", format: "strikethrough" },
|
||||
{ id: "underline", icon: Underline, label: "underline", format: "underline" },
|
||||
{ id: "code", icon: Code, label: "inlineCode", format: "code" },
|
||||
{ id: "bullet", icon: List, label: "bulletList", separator: true },
|
||||
{ id: "number", icon: ListOrdered, label: "orderedList" },
|
||||
{ id: "task", icon: CheckSquare, label: "taskList" },
|
||||
{ id: "quote", icon: Quote, label: "quote", separator: true },
|
||||
{ id: "codeblock", icon: FileCode, label: "codeBlock" },
|
||||
{ id: "math", icon: Sigma, label: "mathFormula" },
|
||||
{ id: "table", icon: TableIcon, label: "table" },
|
||||
{ id: "divider", icon: Minus, label: "divider" },
|
||||
{ id: "link", icon: LinkIcon, label: "link" },
|
||||
{ id: "image", icon: ImageIcon, label: "image" },
|
||||
] as const;
|
||||
|
||||
// 26px icon buttons, 2px gaps; each separator adds 9px plus another gap.
|
||||
const formatRowWidth = (count: number) =>
|
||||
count * 28 - 2 + FORMAT_ITEMS.slice(0, count).filter((item) => "separator" in item).length * 11;
|
||||
|
||||
/** Nested controls follow the same keep-open / leaf-close contract as SFTP. */
|
||||
const NoteToolbarPopover: React.FC<{
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
collapsed: boolean;
|
||||
contentClassName: string;
|
||||
children: React.ReactNode;
|
||||
}> = ({ label, icon, collapsed, contentClassName, children }) => {
|
||||
const closeOverflow = useToolbarOverflowClose();
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className={collapsed ? overflowItemClass : toolbarButtonClass}
|
||||
title={label}
|
||||
aria-label={label}
|
||||
data-toolbar-overflow-keep-open="true"
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
>
|
||||
{icon}
|
||||
{collapsed && <span>{label}</span>}
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className={contentClassName}
|
||||
data-toolbar-nested-menu="true"
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
onCloseAutoFocus={(event) => event.preventDefault()}
|
||||
onClick={(event) => {
|
||||
if ((event.target as Element).closest("button")) closeOverflow();
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
export const NoteModeDropdown: React.FC<NoteModeDropdownProps> = ({
|
||||
editorMode,
|
||||
onChangeMode,
|
||||
@@ -163,360 +234,229 @@ export const NoteToolbar: React.FC<NoteToolbarProps> = ({
|
||||
|
||||
const isEditing = editorMode === "edit" || editorMode === "live" || editorMode === "source";
|
||||
|
||||
const formatRowRef = useRef<HTMLDivElement>(null);
|
||||
const [availableWidth, setAvailableWidth] = useState(Infinity);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const row = formatRowRef.current;
|
||||
if (!row) return;
|
||||
setAvailableWidth(row.getBoundingClientRect().width);
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) setAvailableWidth(entry.contentRect.width);
|
||||
});
|
||||
observer.observe(row);
|
||||
return () => observer.disconnect();
|
||||
}, [isEditing]);
|
||||
|
||||
if (!isEditing) return null;
|
||||
|
||||
// Highlight style for toggles that are active at the current selection.
|
||||
const formatButtonClass = (active: boolean) =>
|
||||
cn(
|
||||
"p-1.5 rounded-md transition-colors",
|
||||
active
|
||||
? "bg-primary/15 text-primary hover:bg-primary/20 hover:text-primary"
|
||||
: "hover:bg-muted text-muted-foreground hover:text-foreground",
|
||||
let inlineCount = FORMAT_ITEMS.length;
|
||||
if (formatRowWidth(inlineCount) > availableWidth) {
|
||||
// Reserve a button and gap for the overflow trigger, then spill from the end.
|
||||
while (inlineCount > 0 && formatRowWidth(inlineCount) + 28 > availableWidth) {
|
||||
inlineCount -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
const renderItem = (item: (typeof FORMAT_ITEMS)[number], collapsed = false) => {
|
||||
const Icon = item.icon;
|
||||
const label = t(`notes.toolbar.${item.label}`);
|
||||
if (item.id === "typography") {
|
||||
return (
|
||||
<NoteToolbarPopover
|
||||
key={item.id}
|
||||
label={label}
|
||||
icon={<Icon size={14} />}
|
||||
collapsed={collapsed}
|
||||
contentClassName="w-64 p-2.5 space-y-2.5 text-xs shadow-lg"
|
||||
>
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-[11px] font-medium text-muted-foreground">
|
||||
<span>{t("notes.toolbar.customCodeFont")}</span>
|
||||
<span className="text-[10px] opacity-70">
|
||||
{t("notes.toolbar.fontsAvailable", { count: systemFontList.length })}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Search Bar */}
|
||||
<div className="relative flex items-center">
|
||||
<Search size={12} className="absolute left-2 text-muted-foreground pointer-events-none" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder={t("notes.toolbar.searchFont")}
|
||||
value={fontSearch}
|
||||
onChange={(e) => setFontSearch(e.target.value)}
|
||||
className="w-full pl-6 pr-2 py-1 rounded border border-border bg-background text-[11px] text-foreground outline-none focus:border-primary placeholder:text-muted-foreground/60"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Scrollable Font List */}
|
||||
<div className="space-y-0.5 max-h-52 overflow-y-auto pr-1">
|
||||
{filteredFonts.length === 0 ? (
|
||||
<div className="py-2 text-center text-muted-foreground text-[11px]">
|
||||
{t("notes.toolbar.noFontsFound")}
|
||||
</div>
|
||||
) : (
|
||||
filteredFonts.map((f) => (
|
||||
<button
|
||||
key={f.value}
|
||||
type="button"
|
||||
style={{ fontFamily: f.value || undefined }}
|
||||
className={cn(
|
||||
"w-full px-2 py-1 rounded text-left text-xs transition-colors flex items-center justify-between gap-1.5",
|
||||
(noteFontFamily || "") === f.value
|
||||
? "bg-primary text-primary-foreground font-medium"
|
||||
: "hover:bg-secondary text-foreground",
|
||||
)}
|
||||
onClick={() => onChangeNoteFontFamily?.(f.value)}
|
||||
>
|
||||
<span className="truncate">{f.label}</span>
|
||||
{(noteFontFamily || "") === f.value && <Check size={12} className="shrink-0" />}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border/60 pt-2">
|
||||
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.bodyFontSize")}</div>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{FONT_SIZES.map((sz) => (
|
||||
<button
|
||||
key={sz}
|
||||
type="button"
|
||||
className={cn(
|
||||
"px-2 py-0.5 rounded text-xs border transition-colors",
|
||||
(noteFontSize || 14) === sz
|
||||
? "bg-primary text-primary-foreground border-primary font-medium"
|
||||
: "border-border hover:bg-secondary text-foreground",
|
||||
)}
|
||||
onClick={() => onChangeNoteFontSize?.(sz)}
|
||||
>
|
||||
{sz}px
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border/60 pt-2">
|
||||
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.codeFontSize")}</div>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{CODE_FONT_SIZES.map((sz) => (
|
||||
<button
|
||||
key={sz}
|
||||
type="button"
|
||||
className={cn(
|
||||
"px-2 py-0.5 rounded text-xs border transition-colors font-mono",
|
||||
(noteCodeFontSize || 13) === sz
|
||||
? "bg-primary text-primary-foreground border-primary font-medium"
|
||||
: "border-border hover:bg-secondary text-foreground",
|
||||
)}
|
||||
onClick={() => onChangeNoteCodeFontSize?.(sz)}
|
||||
>
|
||||
{sz}px
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</NoteToolbarPopover>
|
||||
);
|
||||
}
|
||||
if (item.id === "heading") {
|
||||
return (
|
||||
<NoteToolbarPopover
|
||||
key={item.id}
|
||||
label={label}
|
||||
icon={<Icon size={14} />}
|
||||
collapsed={collapsed}
|
||||
contentClassName="w-32 py-1 text-xs"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h1")}
|
||||
>
|
||||
<Heading1 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h1")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h2")}
|
||||
>
|
||||
<Heading2 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h2")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h3")}
|
||||
>
|
||||
<Heading3 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h3")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h4")}
|
||||
>
|
||||
<Heading4 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h4")}</span>
|
||||
</button>
|
||||
</NoteToolbarPopover>
|
||||
);
|
||||
}
|
||||
const active = "format" in item && activeFormats[item.format];
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
collapsed ? overflowItemClass : toolbarButtonClass,
|
||||
active && "bg-primary/15 text-primary hover:bg-primary/20 hover:text-primary",
|
||||
)}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={() => onAction?.(item.id)}
|
||||
title={label}
|
||||
aria-label={label}
|
||||
>
|
||||
<Icon size={14} />
|
||||
{collapsed && <span>{label}</span>}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 border-b border-border/70 bg-card/40 text-xs select-none min-w-0 ${className}`}
|
||||
>
|
||||
{/* Formatting Tools (Available in Live Preview & Source Mode) */}
|
||||
<div className="flex flex-1 items-center gap-0.5 min-w-0 overflow-x-auto [scrollbar-width:thin] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border/70 [&::-webkit-scrollbar-track]:bg-transparent">
|
||||
|
||||
{/* Undo / Redo */}
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("undo")}
|
||||
title={t("notes.toolbar.undo")}
|
||||
>
|
||||
<Undo2 size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("redo")}
|
||||
title={t("notes.toolbar.redo")}
|
||||
>
|
||||
<Redo2 size={14} />
|
||||
</button>
|
||||
|
||||
<div className="h-4 w-px bg-border mx-1 shrink-0" />
|
||||
|
||||
{/* Code Font & Typography Settings Dropdown */}
|
||||
<Dropdown>
|
||||
<DropdownTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
title={t("notes.toolbar.typography")}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
>
|
||||
<Type size={14} />
|
||||
</button>
|
||||
</DropdownTrigger>
|
||||
<DropdownContent align="start" className="w-64 p-2.5 space-y-2.5 z-50 text-xs shadow-lg">
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-[11px] font-medium text-muted-foreground">
|
||||
<span>{t("notes.toolbar.customCodeFont")}</span>
|
||||
<span className="text-[10px] opacity-70">
|
||||
{t("notes.toolbar.fontsAvailable", { count: systemFontList.length })}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Search Bar */}
|
||||
<div className="relative flex items-center">
|
||||
<Search size={12} className="absolute left-2 text-muted-foreground pointer-events-none" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder={t("notes.toolbar.searchFont")}
|
||||
value={fontSearch}
|
||||
onChange={(e) => setFontSearch(e.target.value)}
|
||||
className="w-full pl-6 pr-2 py-1 rounded border border-border bg-background text-[11px] text-foreground outline-none focus:border-primary placeholder:text-muted-foreground/60"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Scrollable Font List */}
|
||||
<div className="space-y-0.5 max-h-52 overflow-y-auto pr-1">
|
||||
{filteredFonts.length === 0 ? (
|
||||
<div className="py-2 text-center text-muted-foreground text-[11px]">
|
||||
{t("notes.toolbar.noFontsFound")}
|
||||
</div>
|
||||
) : (
|
||||
filteredFonts.map((f) => (
|
||||
<button
|
||||
key={f.value}
|
||||
type="button"
|
||||
style={{ fontFamily: f.value || undefined }}
|
||||
className={cn(
|
||||
"w-full px-2 py-1 rounded text-left text-xs transition-colors flex items-center justify-between gap-1.5",
|
||||
(noteFontFamily || "") === f.value
|
||||
? "bg-primary text-primary-foreground font-medium"
|
||||
: "hover:bg-secondary text-foreground",
|
||||
)}
|
||||
onClick={() => onChangeNoteFontFamily?.(f.value)}
|
||||
>
|
||||
<span className="truncate">{f.label}</span>
|
||||
{(noteFontFamily || "") === f.value && <Check size={12} className="shrink-0" />}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border/60 pt-2">
|
||||
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.bodyFontSize")}</div>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{FONT_SIZES.map((sz) => (
|
||||
<button
|
||||
key={sz}
|
||||
type="button"
|
||||
className={cn(
|
||||
"px-2 py-0.5 rounded text-xs border transition-colors",
|
||||
(noteFontSize || 14) === sz
|
||||
? "bg-primary text-primary-foreground border-primary font-medium"
|
||||
: "border-border hover:bg-secondary text-foreground",
|
||||
)}
|
||||
onClick={() => onChangeNoteFontSize?.(sz)}
|
||||
>
|
||||
{sz}px
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border/60 pt-2">
|
||||
<div className="text-[11px] font-medium text-muted-foreground mb-1">{t("notes.toolbar.codeFontSize")}</div>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{CODE_FONT_SIZES.map((sz) => (
|
||||
<button
|
||||
key={sz}
|
||||
type="button"
|
||||
className={cn(
|
||||
"px-2 py-0.5 rounded text-xs border transition-colors font-mono",
|
||||
(noteCodeFontSize || 13) === sz
|
||||
? "bg-primary text-primary-foreground border-primary font-medium"
|
||||
: "border-border hover:bg-secondary text-foreground",
|
||||
)}
|
||||
onClick={() => onChangeNoteCodeFontSize?.(sz)}
|
||||
>
|
||||
{sz}px
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</DropdownContent>
|
||||
</Dropdown>
|
||||
|
||||
{/* Heading Dropdown (Using Portal Dropdown to avoid clipping) */}
|
||||
<Dropdown>
|
||||
<DropdownTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-1 p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
title={t("notes.toolbar.headingLevel")}
|
||||
>
|
||||
<Heading size={14} />
|
||||
</button>
|
||||
</DropdownTrigger>
|
||||
<DropdownContent align="start" className="w-32 py-1 z-50 text-xs">
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h1")}
|
||||
>
|
||||
<Heading1 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h1")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h2")}
|
||||
>
|
||||
<Heading2 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h2")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h3")}
|
||||
>
|
||||
<Heading3 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h3")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full px-3 py-1.5 flex items-center gap-2 hover:bg-secondary text-foreground transition-colors text-left"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("h4")}
|
||||
>
|
||||
<Heading4 size={14} className="text-primary" />
|
||||
<span>{t("notes.toolbar.h4")}</span>
|
||||
</button>
|
||||
</DropdownContent>
|
||||
</Dropdown>
|
||||
|
||||
{/* Inline Styles */}
|
||||
<button
|
||||
type="button"
|
||||
className={formatButtonClass(activeFormats.bold)}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("bold")}
|
||||
title={t("notes.toolbar.bold")}
|
||||
>
|
||||
<Bold size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={formatButtonClass(activeFormats.italic)}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("italic")}
|
||||
title={t("notes.toolbar.italic")}
|
||||
>
|
||||
<Italic size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={formatButtonClass(activeFormats.strikethrough)}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("strikethrough")}
|
||||
title={t("notes.toolbar.strikethrough")}
|
||||
>
|
||||
<Strikethrough size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={formatButtonClass(activeFormats.underline)}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("underline")}
|
||||
title={t("notes.toolbar.underline")}
|
||||
>
|
||||
<Underline size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={formatButtonClass(activeFormats.code)}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("code")}
|
||||
title={t("notes.toolbar.inlineCode")}
|
||||
>
|
||||
<Code size={14} />
|
||||
</button>
|
||||
|
||||
<div className="h-4 w-px bg-border mx-1 shrink-0" />
|
||||
|
||||
{/* Lists */}
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("bullet")}
|
||||
title={t("notes.toolbar.bulletList")}
|
||||
>
|
||||
<List size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("number")}
|
||||
title={t("notes.toolbar.orderedList")}
|
||||
>
|
||||
<ListOrdered size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("task")}
|
||||
title={t("notes.toolbar.taskList")}
|
||||
>
|
||||
<CheckSquare size={14} />
|
||||
</button>
|
||||
|
||||
<div className="h-4 w-px bg-border mx-1 shrink-0" />
|
||||
|
||||
{/* Blocks */}
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("quote")}
|
||||
title={t("notes.toolbar.quote")}
|
||||
>
|
||||
<Quote size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("codeblock")}
|
||||
title={t("notes.toolbar.codeBlock")}
|
||||
>
|
||||
<FileCode size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("math")}
|
||||
title={t("notes.toolbar.mathFormula")}
|
||||
>
|
||||
<Sigma size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("table")}
|
||||
title={t("notes.toolbar.table")}
|
||||
>
|
||||
<TableIcon size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("divider")}
|
||||
title={t("notes.toolbar.divider")}
|
||||
>
|
||||
<Minus size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("link")}
|
||||
title={t("notes.toolbar.link")}
|
||||
>
|
||||
<LinkIcon size={14} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => onAction?.("image")}
|
||||
title={t("notes.toolbar.image")}
|
||||
>
|
||||
<ImageIcon size={14} />
|
||||
</button>
|
||||
<div
|
||||
ref={formatRowRef}
|
||||
data-note-format-toolbar
|
||||
className="flex flex-1 items-center gap-[2px] min-w-0 overflow-hidden"
|
||||
>
|
||||
{FORMAT_ITEMS.slice(0, inlineCount).map((item) => (
|
||||
<React.Fragment key={item.id}>
|
||||
{"separator" in item && <div className="h-4 w-px bg-border mx-[4px] shrink-0" />}
|
||||
{renderItem(item)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
<ToolbarOverflowMenu
|
||||
hasItems={inlineCount < FORMAT_ITEMS.length}
|
||||
label={t("terminal.toolbar.more")}
|
||||
orientation="vertical"
|
||||
buttonClassName={toolbarButtonClass}
|
||||
contentClassName="max-h-[min(32rem,var(--radix-popover-content-available-height))] overflow-y-auto"
|
||||
align="start"
|
||||
>
|
||||
<div className="flex min-w-[140px] flex-col">
|
||||
{FORMAT_ITEMS.slice(inlineCount).map((item) => renderItem(item, true))}
|
||||
</div>
|
||||
</ToolbarOverflowMenu>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -36,7 +36,7 @@ export const Toggle: React.FC<ToggleProps> = ({ checked, onChange, disabled, ari
|
||||
|
||||
interface SelectProps {
|
||||
value: string;
|
||||
options: { value: string; label: string; icon?: React.ReactNode }[];
|
||||
options: { value: string; label: string; icon?: React.ReactNode; disabled?: boolean }[];
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
@@ -87,6 +87,7 @@ export const Select: React.FC<SelectProps> = ({
|
||||
<SelectPrimitive.Item
|
||||
key={opt.value}
|
||||
value={opt.value}
|
||||
disabled={opt.disabled}
|
||||
className="relative flex w-full min-w-0 cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
|
||||
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import vm from "node:vm";
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import TestRenderer, { act } from "react-test-renderer";
|
||||
import ts from "typescript";
|
||||
import { canSendWithAgent } from "../../ai/agentSendEligibility";
|
||||
import { buildManagedAgentState, getUnavailablePreferredHarness } from "./ai/managedAgentState";
|
||||
import type { ExternalAgentConfig } from "../../../infrastructure/ai/types";
|
||||
|
||||
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
@@ -94,3 +97,61 @@ test("an older AI detection result cannot replace or finish the newer request",
|
||||
assert.equal(h.state.busy, false);
|
||||
} finally { await act(async () => h.root.unmount()); }
|
||||
});
|
||||
|
||||
|
||||
// Mount the same option computation and normalization effect that the
|
||||
// Settings tab runs after a probe has updated the actual saved agent state.
|
||||
const pickerStart = source.indexOf(" // Agent options for default agent");
|
||||
const pickerEnd = source.indexOf("\n useEffect(() => {\n const bridge", pickerStart);
|
||||
assert.ok(pickerStart >= 0 && pickerEnd > pickerStart);
|
||||
const runDefaultPicker = vm.runInNewContext(ts.transpile(`(function(ctx) {
|
||||
const { useMemo, useEffect, externalAgents, defaultAgentId, setDefaultAgentId, t,
|
||||
canSendWithAgent, getUnavailablePreferredHarness, React, AgentIconBadge } = ctx;
|
||||
${source.slice(pickerStart, pickerEnd)}
|
||||
return agentOptions;
|
||||
})`, { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React }), { console }) as
|
||||
(ctx: Record<string, unknown>) => { value: string; disabled?: boolean }[];
|
||||
|
||||
test("Settings retains the unavailable saved default, blocks sends and restores the same choice", async () => {
|
||||
const agent: ExternalAgentConfig = {
|
||||
id: "discovered_copilot",
|
||||
name: "GitHub Copilot CLI",
|
||||
command: "/fixture/copilot",
|
||||
commandSource: "manual",
|
||||
sdkBackend: "copilot",
|
||||
enabled: true,
|
||||
available: true,
|
||||
};
|
||||
let options: ReturnType<typeof runDefaultPicker> = [];
|
||||
let choice = "";
|
||||
function Harness({ agents }: { agents: ExternalAgentConfig[] }) {
|
||||
const [defaultAgentId, setDefaultAgentId] = useState(agent.id);
|
||||
options = runDefaultPicker({
|
||||
useMemo, useEffect, externalAgents: agents, defaultAgentId, setDefaultAgentId,
|
||||
t: (key: string) => key, canSendWithAgent, getUnavailablePreferredHarness, React,
|
||||
AgentIconBadge: () => null,
|
||||
});
|
||||
choice = defaultAgentId;
|
||||
return null;
|
||||
}
|
||||
const failed = buildManagedAgentState([agent], agent.id, "copilot", null, "manual");
|
||||
const recovered = buildManagedAgentState(failed.agents, agent.id, "copilot", {
|
||||
path: agent.command, available: true, version: "1.0.106",
|
||||
}, "manual");
|
||||
let root!: TestRenderer.ReactTestRenderer;
|
||||
const render = (agents: ExternalAgentConfig[]) => React.createElement(Harness, { agents });
|
||||
try {
|
||||
await act(async () => { root = TestRenderer.create(render([agent])); });
|
||||
await act(async () => { root.update(render(failed.agents)); });
|
||||
assert.equal(choice, agent.id);
|
||||
assert.equal(options.find(option => option.value === agent.id)?.disabled, true);
|
||||
assert.equal(canSendWithAgent(choice, failed.agents), false);
|
||||
await act(async () => { root.update(render(recovered.agents)); });
|
||||
assert.equal(choice, agent.id);
|
||||
assert.equal(options.find(option => option.value === agent.id)?.disabled, undefined);
|
||||
assert.equal(canSendWithAgent(choice, recovered.agents), true);
|
||||
const reset = buildManagedAgentState(recovered.agents, agent.id, "copilot", null, "auto");
|
||||
await act(async () => { root.update(render(reset.agents)); });
|
||||
assert.equal(choice, "catty");
|
||||
} finally { await act(async () => root.unmount()); }
|
||||
});
|
||||
@@ -68,6 +68,7 @@ import {
|
||||
areExternalAgentListsEqual,
|
||||
buildManagedAgentState,
|
||||
getInitialManagedAgentPaths,
|
||||
getUnavailablePreferredHarness,
|
||||
updateCodebuddyManagedEnv,
|
||||
updateCodebuddyManagedOptions,
|
||||
} from "./ai/managedAgentState";
|
||||
@@ -392,6 +393,10 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
: setMimoPathInfo;
|
||||
|
||||
setInfo(result);
|
||||
const savedPaths = initialManagedPathsRef.current;
|
||||
if (savedPaths && (commandSource === "auto" || (result?.available && result.path))) {
|
||||
savedPaths[agentKey] = commandSource === "manual" ? result?.path ?? "" : "";
|
||||
}
|
||||
|
||||
let nextDefaultId: string | null = null;
|
||||
setExternalAgents((prev) => {
|
||||
@@ -414,7 +419,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
apiKeyPresent?: boolean;
|
||||
refreshShellEnv?: boolean;
|
||||
commandSource?: "manual" | "auto";
|
||||
removeUnavailableManualPath?: boolean;
|
||||
recheckSavedPath?: boolean;
|
||||
},
|
||||
) => {
|
||||
const bridge = getBridge();
|
||||
@@ -461,7 +466,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
options?.commandSource === "manual"
|
||||
&& customPath.trim()
|
||||
&& !result?.available
|
||||
&& !options.removeUnavailableManualPath
|
||||
&& !options.recheckSavedPath
|
||||
) {
|
||||
const setInfo = agentKey === "codex"
|
||||
? setCodexPathInfo
|
||||
@@ -525,9 +530,14 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
void resolveAgentPath(task.key, task.path, {
|
||||
...task.options,
|
||||
commandSource: task.path ? "manual" : "auto",
|
||||
removeUnavailableManualPath: Boolean(task.path),
|
||||
}).finally(() => {
|
||||
autoResolvedAgentStateRef.current[task.key] = "done";
|
||||
recheckSavedPath: Boolean(task.path),
|
||||
}).then((result) => {
|
||||
if (result?.available) {
|
||||
autoResolvedAgentStateRef.current[task.key] = "done";
|
||||
} else {
|
||||
// Retry a failed check on the next visit to the Agents tab.
|
||||
delete autoResolvedAgentStateRef.current[task.key];
|
||||
}
|
||||
});
|
||||
}, task.delayMs));
|
||||
return () => {
|
||||
@@ -646,13 +656,22 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
[removeProvider, editingProviderId, removeProviderConfirm],
|
||||
);
|
||||
|
||||
// Agent options for default agent
|
||||
const agentOptions = useMemo(() => [
|
||||
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
|
||||
...externalAgents
|
||||
.filter((a) => canSendWithAgent(a.id, externalAgents))
|
||||
.map((a) => ({ value: a.id, label: a.name, icon: <AgentIconBadge agent={a} size="xs" variant="plain" /> })),
|
||||
], [externalAgents, t]);
|
||||
// Agent options for default agent. Include a saved default that is temporarily offline as a disabled option.
|
||||
// This preserves the setting without offering that harness for new selections.
|
||||
const agentOptions = useMemo(() => {
|
||||
const unavailable = getUnavailablePreferredHarness(externalAgents, defaultAgentId);
|
||||
return [
|
||||
{ value: "catty", label: t('ai.defaultAgent.catty'), icon: <AgentIconBadge agent={{ id: "catty", type: "builtin" }} size="xs" variant="plain" /> },
|
||||
...externalAgents
|
||||
.filter((a) => a === unavailable || canSendWithAgent(a.id, externalAgents))
|
||||
.map((a) => ({
|
||||
value: a.id,
|
||||
label: a === unavailable ? `${a.name} (${t('ai.defaultAgent.unavailable')})` : a.name,
|
||||
icon: <AgentIconBadge agent={a} size="xs" variant="plain" />,
|
||||
disabled: a === unavailable ? true : undefined,
|
||||
})),
|
||||
];
|
||||
}, [externalAgents, defaultAgentId, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!agentOptions.some((option) => option.value === defaultAgentId)) {
|
||||
|
||||
@@ -40,6 +40,7 @@ const CUSTOM_CSS_HELP_PROSE_CLASS =
|
||||
"text-xs text-foreground/90 leading-relaxed [&>*:first-child]:mt-0 [&>*:last-child]:mb-0";
|
||||
|
||||
function SettingsAppearanceTab(props: {
|
||||
pluginRuntimeAvailable: boolean;
|
||||
theme: "dark" | "light" | "system";
|
||||
resolvedTheme: "dark" | "light";
|
||||
setTheme: (theme: "dark" | "light" | "system") => void;
|
||||
@@ -366,7 +367,9 @@ function SettingsAppearanceTab(props: {
|
||||
{renderThemeSwatches(visibleUiThemes, visibleUiThemeId, setVisibleUiThemeId)}
|
||||
</div>
|
||||
</SettingsAnchor>
|
||||
<PluginThemePicker mode={resolvedTheme} onRestore={() => (resolvedTheme === "dark" ? setDarkUiThemeId : setLightUiThemeId)(resolvedTheme === "dark" ? "midnight" : "snow")} />
|
||||
{props.pluginRuntimeAvailable && (
|
||||
<PluginThemePicker mode={resolvedTheme} onRestore={() => (resolvedTheme === "dark" ? setDarkUiThemeId : setLightUiThemeId)(resolvedTheme === "dark" ? "midnight" : "snow")} />
|
||||
)}
|
||||
{pluginThemeError && <p role="alert" className="text-xs text-destructive">{pluginThemeError}</p>}
|
||||
<SettingRow
|
||||
anchorId="appearance-accent-mode"
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
buildExternalMcpHttpUrl,
|
||||
buildGenericHttpMcpJson,
|
||||
DEFAULT_EXTERNAL_MCP_HTTP_PORT,
|
||||
isExternalMcpHttpIpAddress,
|
||||
} from "../../../../domain/externalMcpHttp";
|
||||
import { useI18n } from "../../../../application/i18n/I18nProvider";
|
||||
import { Button } from "../../../ui/button";
|
||||
@@ -58,15 +59,6 @@ function isWildcardAddress(value: string): boolean {
|
||||
return address === "0.0.0.0" || address === "::";
|
||||
}
|
||||
|
||||
function isIpAddress(value: string): boolean {
|
||||
const address = value.trim();
|
||||
const ipv4 = address.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
if (ipv4) {
|
||||
return ipv4.slice(1).every((part) => Number(part) <= 255 && String(Number(part)) === part);
|
||||
}
|
||||
return address.includes(":") && /^[0-9a-fA-F:]+$/.test(address);
|
||||
}
|
||||
|
||||
function parsePort(value: string): number | null {
|
||||
if (!/^\d+$/.test(value.trim())) return null;
|
||||
const port = Number(value);
|
||||
@@ -157,7 +149,7 @@ export const ExternalMcpHttpSection: React.FC<ExternalMcpHttpSectionProps> = ({
|
||||
|
||||
const commitClientHost = () => {
|
||||
const clientHost = clientHostDraft.trim();
|
||||
if (clientHost && (!isIpAddress(clientHost) || isWildcardAddress(clientHost))) {
|
||||
if (clientHost && (!isExternalMcpHttpIpAddress(clientHost) || isWildcardAddress(clientHost))) {
|
||||
setClientHostError(true);
|
||||
return;
|
||||
}
|
||||
@@ -168,7 +160,7 @@ export const ExternalMcpHttpSection: React.FC<ExternalMcpHttpSectionProps> = ({
|
||||
|
||||
const commitAddress = () => {
|
||||
const address = addressDraft.trim();
|
||||
if (!isIpAddress(address)) {
|
||||
if (!isExternalMcpHttpIpAddress(address)) {
|
||||
setAddressError(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,26 @@
|
||||
import type { ExternalAgentConfig } from "../../../../infrastructure/ai/types";
|
||||
import {
|
||||
type ManagedAgentKey,
|
||||
getExternalAgentSdkBackend,
|
||||
isPathLikeCommand,
|
||||
} from "../../../../infrastructure/ai/managedAgents";
|
||||
import type { AgentPathInfo } from "./types";
|
||||
import { AGENT_DEFAULTS, isCursorAvailableForMode } from "./types";
|
||||
import { buildCodebuddyEnv } from "./codebuddyConfigEnv";
|
||||
|
||||
/** A saved, enabled harness can remain preferred while its version probe fails. */
|
||||
export function getUnavailablePreferredHarness(
|
||||
agents: ExternalAgentConfig[],
|
||||
defaultAgentId: string,
|
||||
): ExternalAgentConfig | undefined {
|
||||
return agents.find((agent) =>
|
||||
agent.id === defaultAgentId &&
|
||||
Object.keys(AGENT_DEFAULTS).some((key) => agent.id === `discovered_${key}`) &&
|
||||
agent.enabled && agent.available === false &&
|
||||
agent.commandSource !== "auto" && isPathLikeCommand(agent.command) &&
|
||||
Boolean(getExternalAgentSdkBackend(agent)));
|
||||
}
|
||||
|
||||
function getAutoManagedAgentStoredPath(
|
||||
agents: ExternalAgentConfig[],
|
||||
agentKey: ManagedAgentKey,
|
||||
@@ -34,9 +48,17 @@ export function buildManagedAgentState(
|
||||
const managedId = `discovered_${agentKey}`;
|
||||
const managedAgents = prevAgents.filter((agent) => agent.id === managedId);
|
||||
const otherAgents = prevAgents.filter((agent) => agent.id !== managedId);
|
||||
const existingManaged = managedAgents[0];
|
||||
const savedManualPath = commandSource === "manual" && existingManaged?.commandSource !== "auto"
|
||||
&& isPathLikeCommand(existingManaged?.command);
|
||||
|
||||
if (!pathInfo?.available || !pathInfo.path) {
|
||||
const existingManaged = managedAgents.find((agent) => agent.id === managedId);
|
||||
if (savedManualPath && existingManaged) {
|
||||
return {
|
||||
agents: prevAgents.map((agent) => agent.id === managedId ? { ...agent, available: false } : agent),
|
||||
defaultAgentId,
|
||||
};
|
||||
}
|
||||
if (agentKey === "cursor" && (existingManaged?.apiKey || existingManaged?.cursorAuthMode === "cli-login")) {
|
||||
const defaults = AGENT_DEFAULTS[agentKey];
|
||||
const {
|
||||
@@ -97,7 +119,6 @@ export function buildManagedAgentState(
|
||||
};
|
||||
}
|
||||
|
||||
const existingManaged = managedAgents.find((agent) => agent.id === managedId);
|
||||
const {
|
||||
acpCommand: _legacyCommand,
|
||||
acpArgs: _legacyArgs,
|
||||
@@ -139,7 +160,9 @@ export function buildManagedAgentState(
|
||||
available: cursorModeAvailable,
|
||||
// Do not force-disable when only the current auth mode is temporarily
|
||||
// unavailable (user may switch modes). Send paths already require available.
|
||||
enabled: managedAgents.length === 0
|
||||
enabled: savedManualPath && existingManaged
|
||||
? existingManaged.enabled
|
||||
: managedAgents.length === 0
|
||||
|| (agentKey === "codebuddy" && existingManaged && !isPathLikeCommand(existingManaged.command))
|
||||
? true
|
||||
: managedAgents.some((agent) => agent.enabled) || managedAgents.every((agent) => agent.available === false),
|
||||
|
||||
@@ -139,6 +139,8 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
// panel setTransfersState for every tick — that re-rendered the whole SFTP
|
||||
// tree and pegged the renderer during large copies.
|
||||
const task = useSftpTransferTask(propsTask.id, propsTask);
|
||||
const pauseFailed = task.status === 'pausing' && !!task.pauseUnavailableReason;
|
||||
const isPausing = task.status === 'pausing' && !pauseFailed;
|
||||
|
||||
// Same progress model as the global transfer center (done · found for folders).
|
||||
const isDirParent = isDirectoryParentTask(task);
|
||||
@@ -196,7 +198,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
? (fileCountDisplay
|
||||
? `${t('sftp.transferCenter.phase.scanning')} · ${fileCountDisplay}`
|
||||
: t('sftp.transferCenter.phase.scanning'))
|
||||
: task.status === 'pausing'
|
||||
: isPausing
|
||||
? pausingLabel
|
||||
: isDirParent
|
||||
? (fileCountDisplay
|
||||
@@ -227,7 +229,9 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
|
||||
const statusIcon = isResuming
|
||||
? <Loader2 size={12} className="animate-spin text-primary" />
|
||||
: task.status === 'pausing'
|
||||
: pauseFailed
|
||||
? <Pause size={12} className="text-amber-500" />
|
||||
: isPausing
|
||||
? <Loader2 size={12} className="animate-spin text-amber-500" />
|
||||
: task.status === 'transferring'
|
||||
? <Loader2 size={12} className="animate-spin text-primary" />
|
||||
@@ -290,7 +294,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
// Surface hard pause misses (e.g. "cannot be paused yet") so the panel
|
||||
// pause button never looks dead when the backend refuses.
|
||||
const showPauseUnavailable = !!task.pauseUnavailableReason
|
||||
&& (task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
|
||||
&& (pauseFailed || task.status === 'transferring' || task.status === 'queued' || task.status === 'pending');
|
||||
const showWarning = task.status === 'completed' && !!task.warning;
|
||||
const hasFooterContent = showTransferSizeCalculation || showFailedError || showPauseUnavailable || showWarning || childWarningCount > 0;
|
||||
const retryActionLabel = t('sftp.transfers.retryAction');
|
||||
@@ -352,7 +356,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{task.status === 'transferring' && task.resumable !== false && onPause && !isResuming && (
|
||||
{(task.status === 'transferring' || pauseFailed) && task.resumable !== false && onPause && !isResuming && (
|
||||
<IconButtonWithTooltip label={pauseActionLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -367,7 +371,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{task.status === 'pausing' && (
|
||||
{isPausing && (
|
||||
<IconButtonWithTooltip label={pausingLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -397,7 +401,7 @@ const SftpTransferItemInner: React.FC<SftpTransferItemProps> = ({
|
||||
</Button>
|
||||
</IconButtonWithTooltip>
|
||||
)}
|
||||
{(task.status === 'paused' || task.status === 'interrupted') && onResume && !isResuming && (
|
||||
{(task.status === 'paused' || task.status === 'interrupted' || (pauseFailed && task.resumable !== false)) && onResume && !isResuming && (
|
||||
<IconButtonWithTooltip label={resumeActionLabel}>
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -2,9 +2,11 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { TerminalComposeBar } from './TerminalComposeBar';
|
||||
import { TerminalContextMenu } from './TerminalContextMenu';
|
||||
import { TooltipProvider } from '../ui/tooltip';
|
||||
import { getComposeBarHistory, pruneComposeBarHistory, recordComposeBarHistory } from '../../application/state/composeBarHistoryStore';
|
||||
import { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry';
|
||||
@@ -303,3 +305,54 @@ test('compose send target toggle shows all vs active without looking like broadc
|
||||
assert.equal(stillPulsing.length, 0);
|
||||
await act(async () => { root.unmount(); });
|
||||
});
|
||||
|
||||
|
||||
test('compose right-click never pastes into the terminal behind it', async (t) => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { url: 'http://localhost' });
|
||||
const globals = ['window', 'document', 'localStorage', 'Element', 'HTMLElement', 'Node'] as const;
|
||||
const originals = globals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
|
||||
for (const name of globals) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value: dom.window[name] });
|
||||
}
|
||||
const rootElement = dom.window.document.querySelector('#root')!;
|
||||
const root = createRoot(rootElement);
|
||||
t.after(async () => {
|
||||
await act(async () => root.unmount());
|
||||
dom.window.close();
|
||||
for (const [name, descriptor] of originals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, name);
|
||||
}
|
||||
});
|
||||
let pasteCount = 0;
|
||||
const render = (broadcast: boolean) => (
|
||||
<I18nProvider locale="en"><TooltipProvider>
|
||||
<TerminalContextMenu sessionId="right-click-test" status="connected" rightClickBehavior="paste" onPaste={() => { pasteCount++; }}>
|
||||
<div>
|
||||
<div data-terminal-cell />
|
||||
<TerminalComposeBar sessionId="right-click-test" isBroadcastEnabled={broadcast} onSend={() => true} onClose={() => {}} />
|
||||
</div>
|
||||
</TerminalContextMenu>
|
||||
</TooltipProvider></I18nProvider>
|
||||
);
|
||||
const rightClick = async (target: string) => {
|
||||
const element = rootElement.querySelector(target);
|
||||
assert.ok(element, target);
|
||||
await act(async () => {
|
||||
element.dispatchEvent(new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 }));
|
||||
});
|
||||
};
|
||||
|
||||
await act(async () => root.render(render(false)));
|
||||
await rightClick('textarea');
|
||||
assert.equal(pasteCount, 0, 'the solo composer must not paste into the PTY');
|
||||
await rightClick('[data-terminal-cell]');
|
||||
assert.equal(pasteCount, 1, 'ordinary terminal right-click paste still works');
|
||||
|
||||
await act(async () => root.render(render(true)));
|
||||
await rightClick('textarea');
|
||||
assert.equal(pasteCount, 1, 'broadcast compose opens only its own menu');
|
||||
assert.ok(rootElement.querySelector('[data-compose-broadcast-menu]'));
|
||||
await rightClick('[data-compose-broadcast-menu]');
|
||||
assert.equal(pasteCount, 1, 'right-click on the compose menu must not paste into the PTY');
|
||||
});
|
||||
@@ -360,9 +360,11 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
|
||||
const sendToAll = composeSendToAll ?? Boolean(isBroadcastEnabled);
|
||||
const handleBroadcastContextMenu = useCallback((event: React.MouseEvent) => {
|
||||
// A solo composer is inside the terminal's context-menu trigger, but this
|
||||
// gesture must never run a terminal action (such as paste into the PTY).
|
||||
event.stopPropagation();
|
||||
if (!isBroadcastEnabled && !sendToAll) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setBroadcastMenuAnchor({
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
|
||||
@@ -110,6 +110,7 @@ import {
|
||||
createTerminalLigatureController,
|
||||
terminalFontLigaturesEnabled,
|
||||
} from "./terminalFontLigatures";
|
||||
import { createPaneBidiJoiner, findRightToLeftRuns } from "./terminalBidiJoiner";
|
||||
import { createWebglRendererController } from "./webglRendererController";
|
||||
import { getSharedWebglContextBudget } from "./webglContextBudget";
|
||||
import {
|
||||
@@ -1074,6 +1075,22 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
term.loadAddon(unicodeGraphemes);
|
||||
term.unicode.activeVersion = '15-graphemes';
|
||||
|
||||
// Draw Arabic, Persian and Hebrew runs in display order with joined letters.
|
||||
// Display only: the buffer, selection and copy keep the logical text.
|
||||
term.registerCharacterJoiner(performanceConfig.useWebGLAddon
|
||||
? createPaneBidiJoiner(
|
||||
() => webglController.getAddon() !== null,
|
||||
() => {
|
||||
if (runtimeDisposed) return;
|
||||
// The pinned WebGL addon allocates a maximum-size atlas page for a
|
||||
// wide joined glyph. Prevent attach/recovery again for just this pane.
|
||||
webglController.dispose();
|
||||
logger.info("[XTerm] Using DOM renderer for right-to-left text in this pane");
|
||||
repaintTerminal();
|
||||
},
|
||||
)
|
||||
: findRightToLeftRuns);
|
||||
|
||||
trackRenderer();
|
||||
|
||||
const appLevelActions = getAppLevelActions();
|
||||
@@ -2601,6 +2618,18 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
}
|
||||
}
|
||||
|
||||
// Claim Shift+Insert as clipboard paste before Kitty/Win32 or xterm can
|
||||
// encode it as an Insert key, while preserving user shortcut precedence.
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void ctx.terminalContextActionsRef?.current?.onPaste?.();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Sogou/macOS CJK punctuation: keydown still reports ASCII "," while the
|
||||
// full-width "," arrives on insertText. Returning false (without
|
||||
// preventDefault) stops xterm/Kitty from sending the half-width key so the
|
||||
@@ -2776,15 +2805,6 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
};
|
||||
return true;
|
||||
}
|
||||
// xterm leaves Shift+Insert to the browser's native paste handler. Fan out
|
||||
// the clipboard data from onData instead of encoding an Insert key for
|
||||
// peers or treating the paste as that key's pending legacy data (#4142).
|
||||
if (
|
||||
e.key === "Insert" && e.shiftKey
|
||||
&& !e.ctrlKey && !e.altKey && !e.metaKey
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!shouldDeferKittyKeyEvent(normalizedKittyEvent)) {
|
||||
const identity = kittyKeyIdentity(e);
|
||||
if (
|
||||
|
||||
@@ -65,3 +65,24 @@ test('disabled or mouse-owned gestures retain the full original event sequence',
|
||||
dispose();
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
|
||||
test('right-click in the compose bar is never captured or replayed as terminal paste', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const dom = new JSDOM('<div id="root"><div data-section="terminal-compose-bar"><textarea></textarea></div></div>');
|
||||
const root = dom.window.document.querySelector<HTMLElement>('#root')!;
|
||||
const compose = root.querySelector('textarea')!;
|
||||
const dispose = installRightClickLongPress(root, () => true);
|
||||
const seen: EventTarget[] = [];
|
||||
root.addEventListener('contextmenu', (event) => seen.push(event.target!));
|
||||
const fire = (type: string) => compose.dispatchEvent(new dom.window.MouseEvent(type, {
|
||||
bubbles: true, cancelable: true, button: 2, buttons: type === 'mouseup' ? 0 : 2,
|
||||
}));
|
||||
fire('mousedown');
|
||||
fire('contextmenu');
|
||||
t.mock.timers.tick(RIGHT_CLICK_LONG_PRESS_MS);
|
||||
fire('mouseup');
|
||||
assert.deepEqual(seen, [compose], 'only the original composer event should be delivered');
|
||||
dispose();
|
||||
dom.window.close();
|
||||
});
|
||||
@@ -37,7 +37,7 @@ export function installRightClickLongPress(
|
||||
suppressContextMenu = false;
|
||||
if (event.button !== 2 || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey
|
||||
|| !canStart()
|
||||
|| (event.target as Element | null)?.closest('[data-terminal-history-preview]')) return;
|
||||
|| (event.target as Element | null)?.closest('[data-terminal-history-preview], [data-section="terminal-compose-bar"]')) return;
|
||||
press = event;
|
||||
suppressContextMenu = true;
|
||||
timer = setTimeout(() => {
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { createPaneBidiJoiner, findRightToLeftRuns, mightContainRightToLeft } from "./terminalBidiJoiner";
|
||||
|
||||
const slice = (text: string, ranges: [number, number][]) =>
|
||||
ranges.map(([start, end]) => text.slice(start, end));
|
||||
|
||||
test("pure left-to-right text is left alone", () => {
|
||||
assert.deepEqual(findRightToLeftRuns("ls -la /var/log 2>&1 | grep error"), []);
|
||||
assert.deepEqual(findRightToLeftRuns("10.0.0.138 (eth0) 100%"), []);
|
||||
assert.deepEqual(findRightToLeftRuns(""), []);
|
||||
});
|
||||
|
||||
test("the cheap detection gate rejects the ASCII and unrelated astral characters", () => {
|
||||
assert.equal(mightContainRightToLeft(String.raw`update DEPLOY 0 2 3 \uD802`), false);
|
||||
assert.equal(mightContainRightToLeft("shell 🛠️ 👍"), false);
|
||||
assert.equal(mightContainRightToLeft("𞤀𞤤"), true);
|
||||
});
|
||||
|
||||
test("supplementary RTL stays whole and returns xterm UTF-16 offsets", () => {
|
||||
const adlam = "𞤀𞤤";
|
||||
const text = `🛠 ${adlam} x`;
|
||||
assert.deepEqual(findRightToLeftRuns(text), [[3, 7]]);
|
||||
assert.deepEqual(findRightToLeftRuns(`${adlam} 123`), [[0, 8]]);
|
||||
});
|
||||
|
||||
test("Persian prose is one run so the browser can order and join it", () => {
|
||||
const text = "سلام دنیا";
|
||||
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
|
||||
});
|
||||
|
||||
test("Arabic prose keeps its interior spaces and drops trailing ones", () => {
|
||||
const text = "مرحبا بالعالم ";
|
||||
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["مرحبا بالعالم"]);
|
||||
});
|
||||
|
||||
test("a Persian word typed after a shell command is its own run", () => {
|
||||
const text = 'echo "سلام"';
|
||||
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["سلام"]);
|
||||
});
|
||||
|
||||
test("numbers inside Persian text stay in the run", () => {
|
||||
const text = "قیمت 100 تومان";
|
||||
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
|
||||
});
|
||||
|
||||
test("an IP address after Arabic text belongs to the Arabic run", () => {
|
||||
const text = "العنوان 10.0.0.138";
|
||||
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
|
||||
});
|
||||
|
||||
test("Persian digits inside Persian text stay in the run", () => {
|
||||
const text = "تعداد ۵۰ فایل";
|
||||
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
|
||||
});
|
||||
|
||||
test("mixed Persian and English splits at the English words", () => {
|
||||
const text = "فایل config.yaml پیدا نشد";
|
||||
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["فایل", "پیدا نشد"]);
|
||||
});
|
||||
|
||||
test("English with a Persian phrase in the middle only joins the phrase", () => {
|
||||
const text = "Error: فایل پیدا نشد (code 2)";
|
||||
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["فایل پیدا نشد"]);
|
||||
});
|
||||
|
||||
test("brackets around RTL text inside an RTL run are kept with it", () => {
|
||||
const text = "مثال (نص) هنا";
|
||||
assert.deepEqual(findRightToLeftRuns(text), [[0, text.length]]);
|
||||
});
|
||||
|
||||
test("Hebrew is handled like Arabic", () => {
|
||||
const text = "ls שלום עולם";
|
||||
assert.deepEqual(slice(text, findRightToLeftRuns(text)), ["שלום עולם"]);
|
||||
});
|
||||
|
||||
test("a single right-to-left character is not worth joining", () => {
|
||||
assert.deepEqual(findRightToLeftRuns("a ب c"), []);
|
||||
});
|
||||
|
||||
test("ranges are sorted and do not overlap", () => {
|
||||
const text = "الف abc باء def جيم";
|
||||
const ranges = findRightToLeftRuns(text);
|
||||
assert.deepEqual(slice(text, ranges), ["الف", "باء", "جيم"]);
|
||||
for (let i = 1; i < ranges.length; i++) {
|
||||
assert.ok(ranges[i][0] >= ranges[i - 1][1]);
|
||||
}
|
||||
});
|
||||
|
||||
test("ASCII output never requests a DOM-only renderer", async () => {
|
||||
let switches = 0;
|
||||
const join = createPaneBidiJoiner(() => true, () => { switches++; });
|
||||
assert.deepEqual(join("192.0.2.1: ready"), []);
|
||||
assert.deepEqual(join("100 lines of output"), []);
|
||||
await Promise.resolve();
|
||||
assert.equal(switches, 0);
|
||||
});
|
||||
|
||||
test("RTL joins are withheld from WebGL until the pane switches once to DOM", async () => {
|
||||
let webgl = true;
|
||||
let switches = 0;
|
||||
const join = createPaneBidiJoiner(() => webgl, () => {
|
||||
switches++;
|
||||
webgl = false;
|
||||
});
|
||||
const short = "سلام دنیا";
|
||||
const long = "این یک جمله فارسی معمولی برای بررسی خوانایی متن در یک پنجره عریض است";
|
||||
assert.deepEqual(join(short), []);
|
||||
assert.deepEqual(join(long), []);
|
||||
assert.equal(switches, 0);
|
||||
|
||||
await Promise.resolve();
|
||||
assert.equal(switches, 1);
|
||||
assert.deepEqual(join(short), [[0, short.length]]);
|
||||
assert.deepEqual(join(long), [[0, long.length]]);
|
||||
await Promise.resolve();
|
||||
assert.equal(switches, 1);
|
||||
});
|
||||
|
||||
test("RTL received before deferred WebGL activation keeps the pane on DOM", async () => {
|
||||
let switches = 0;
|
||||
const text = "سلام";
|
||||
const join = createPaneBidiJoiner(() => false, () => { switches++; });
|
||||
assert.deepEqual(join(text), [[0, text.length]]);
|
||||
await Promise.resolve();
|
||||
assert.equal(switches, 1);
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import bidiFactory from "bidi-js";
|
||||
import rtlCharacterPattern from "../../../lib/terminalRtlCharacter.json";
|
||||
|
||||
/**
|
||||
* Display-only right-to-left support for xterm.js (issue #4261).
|
||||
*
|
||||
* xterm.js draws every cell on its own and in buffer (logical) order, so
|
||||
* Arabic, Persian and Hebrew words come out reversed, and Arabic letters are
|
||||
* drawn in their isolated forms. xterm.js has no bidi support of its own
|
||||
* (xtermjs/xterm.js#701).
|
||||
*
|
||||
* The DOM renderer draws joined ranges as one string, allowing the browser to
|
||||
* reorder and shape Arabic letters and mirror brackets. The WebGL addon also
|
||||
* supports joiners, but long joined RTL runs can exhaust its glyph texture,
|
||||
* so a pane that needs RTL shaping stays on DOM. The buffer is never changed, so selection, copy, search
|
||||
* and cursor positions keep working on the logical text. xterm.js also draws
|
||||
* a range cell by cell again while the cursor is inside it or a selection
|
||||
* only partly covers it, so editing an RTL word shows the logical cells.
|
||||
*
|
||||
* This joiner returns the parts of a line that the Unicode Bidirectional
|
||||
* Algorithm puts at a right-to-left (or number) embedding level when the
|
||||
* paragraph direction is left-to-right, which is the default for terminals
|
||||
* (https://terminal-wg.pages.freedesktop.org/bidi/). Runs separated by
|
||||
* left-to-right text therefore keep their left-to-right order, and lines are
|
||||
* not right-aligned.
|
||||
*/
|
||||
|
||||
// RTL scripts and directional controls in the BMP and supplementary planes.
|
||||
// The Unicode flag makes the supplementary bounds code points, not UTF-16
|
||||
// lead surrogates (which would also match unrelated non-RTL characters).
|
||||
const RTL_CHARACTER = new RegExp(rtlCharacterPattern, "u");
|
||||
const SURROGATE_PAIR = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
|
||||
|
||||
// bidi-js 1.0.3 looks up string[i] rather than a full code point. Project
|
||||
// astral characters to BMP characters of the same bidi class for this
|
||||
// calculation only. Two copies retain the original UTF-16 offsets expected
|
||||
// by xterm; the actual glyphs (and terminal buffer) are never replaced.
|
||||
const BIDI_CLASS_PROXY: Readonly<Record<string, string>> = {
|
||||
L: "a", R: "א", AL: "ا", EN: "0", AN: "٠", NSM: "\u0301",
|
||||
ON: "!", BN: "\u00ad", ET: "$", CS: ",", ES: "+",
|
||||
};
|
||||
|
||||
let bidi: ReturnType<typeof bidiFactory> | null = null;
|
||||
|
||||
export function mightContainRightToLeft(text: string): boolean {
|
||||
return RTL_CHARACTER.test(text);
|
||||
}
|
||||
|
||||
export function findRightToLeftRuns(text: string): [number, number][] {
|
||||
if (!mightContainRightToLeft(text)) return [];
|
||||
|
||||
bidi ??= bidiFactory();
|
||||
const classifier = bidi;
|
||||
const projected = text.replace(SURROGATE_PAIR, (character) =>
|
||||
(BIDI_CLASS_PROXY[classifier.getBidiCharTypeName(character)] ?? "!").repeat(2),
|
||||
);
|
||||
const { levels } = classifier.getEmbeddingLevels(projected, "ltr");
|
||||
|
||||
const ranges: [number, number][] = [];
|
||||
let start = -1;
|
||||
for (let i = 0; i <= text.length; i++) {
|
||||
const inRun = i < text.length && levels[i] > 0;
|
||||
if (inRun && start < 0) {
|
||||
start = i;
|
||||
} else if (!inRun && start >= 0) {
|
||||
// A single cell looks the same joined or not.
|
||||
if (i - start > 1) ranges.push([start, i]);
|
||||
start = -1;
|
||||
}
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
/** Keep wide RTL glyphs out of the WebGL atlas, without changing other panes. */
|
||||
export function createPaneBidiJoiner(
|
||||
isWebglActive: () => boolean,
|
||||
stayOnDom: () => void,
|
||||
): typeof findRightToLeftRuns {
|
||||
let requestedDom = false;
|
||||
return (text) => {
|
||||
const ranges = findRightToLeftRuns(text);
|
||||
if (ranges.length === 0) return ranges;
|
||||
|
||||
if (!requestedDom) {
|
||||
requestedDom = true;
|
||||
// Do not dispose the current renderer from inside its render callback.
|
||||
queueMicrotask(stayOnDom);
|
||||
}
|
||||
return isWebglActive() ? [] : ranges;
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { buildSync } from "esbuild";
|
||||
import { JSDOM } from "jsdom";
|
||||
import ts from "typescript";
|
||||
|
||||
test("native Shift+Insert broadcasts clipboard bytes once without an Insert key", async () => {
|
||||
test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keyboard modes", async () => {
|
||||
const root = fileURLToPath(new URL("../../..", import.meta.url));
|
||||
const layer = readFileSync(new URL("../../TerminalLayer.tsx", import.meta.url), "utf8");
|
||||
const start = layer.indexOf(" const handleBroadcastInput = useCallback(");
|
||||
@@ -21,6 +21,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
contents: `
|
||||
export { createXTermRuntime } from "./components/terminal/runtime/createXTermRuntime";
|
||||
export { DEFAULT_TERMINAL_SETTINGS } from "./domain/models/terminal";
|
||||
export { DEFAULT_KEY_BINDINGS } from "./domain/models/keyBindings";
|
||||
export { pasteTextIntoTerminal } from "./components/terminal/runtime/terminalUserPaste";
|
||||
export { resolveTerminalBroadcastTargetIds } from "./domain/terminalBroadcast";
|
||||
export { dispatchKittyKeyboardBroadcastInput } from "./components/terminal/runtime/kittyKeyboardBroadcast";
|
||||
export * from "./components/terminal/runtime/terminalPacedBroadcast";
|
||||
@@ -50,7 +52,8 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
`);
|
||||
dom.window.eval(bundle);
|
||||
const results = await dom.window.eval(`(async () => {
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, resolveTerminalBroadcastTargetIds,
|
||||
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, DEFAULT_KEY_BINDINGS,
|
||||
pasteTextIntoTerminal, resolveTerminalBroadcastTargetIds,
|
||||
dispatchKittyKeyboardBroadcastInput, markTerminalBroadcastUserInput,
|
||||
captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent} = runtimeTest;
|
||||
const ref = current => ({current});
|
||||
@@ -60,71 +63,123 @@ test("native Shift+Insert broadcasts clipboard bytes once without an Insert key"
|
||||
const canUseDirectSessionWriteFallback = () => true;
|
||||
const isTerminalSensitiveInputActive = () => false;
|
||||
const wires = new Map();
|
||||
const pasteCalls = new Map();
|
||||
const terminalBackend = {
|
||||
writeToSession:(id,data)=>wires.get(id).push(data), resizeSession(){}, openExternalAvailable:false,
|
||||
};
|
||||
${dispatcher}
|
||||
const make = (id, kittyKeyboardProtocolEnabled) => {
|
||||
const make = (id, kittyKeyboardProtocolEnabled, options = {}) => {
|
||||
const container = document.createElement('div'); document.body.appendChild(container);
|
||||
wires.set(id, []);
|
||||
pasteCalls.set(id, 0);
|
||||
const terminalContextActionsRef = ref({});
|
||||
const host = {id,label:id,hostname:'localhost',protocol:'ssh',sshInputCompatibility:false};
|
||||
return createXTermRuntime({
|
||||
const runtime = createXTermRuntime({
|
||||
container, host, getHost:()=>host, sessionId:id, sessionRef:ref(id), statusRef:ref('connected'),
|
||||
fontFamilyId:'jetbrains-mono',resolvedFontFamily:'monospace',fontSize:14,
|
||||
terminalTheme:{colors:{background:'#111111',foreground:'#eeeeee',cursor:'#ffffff',selection:'#444444'}},
|
||||
terminalSettingsRef:ref({...DEFAULT_TERMINAL_SETTINGS,rendererType:'dom',fontLigatures:false,cursorBlink:false}),
|
||||
terminalBackend,hotkeySchemeRef:ref('disabled'),keyBindingsRef:ref([]),onHotkeyActionRef:ref(undefined),
|
||||
terminalBackend,hotkeySchemeRef:ref('pc'),
|
||||
keyBindingsRef:ref(options.bindings ?? DEFAULT_KEY_BINDINGS),onHotkeyActionRef:ref(undefined),
|
||||
terminalContextActionsRef, snippetsRef:ref(options.snippets ?? []),
|
||||
onSnippetShortkeyRef:ref(options.onSnippet),
|
||||
isBroadcastEnabledRef:ref(true),onBroadcastInputRef:ref(handleBroadcastInput),
|
||||
commandBufferRef:ref(''),requestSearchFocus(){},kittyKeyboardProtocolEnabled,
|
||||
commandBufferRef:ref(''),requestSearchFocus:options.onSearch ?? (()=>{}),kittyKeyboardProtocolEnabled,
|
||||
});
|
||||
terminalContextActionsRef.current.onPaste = async () => {
|
||||
pasteCalls.set(id, pasteCalls.get(id) + 1);
|
||||
if (options.delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
pasteTextIntoTerminal(runtime.term, 'clipboard', {scrollOnPaste:false});
|
||||
};
|
||||
return runtime;
|
||||
};
|
||||
const results = [];
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', false), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
const beforePaste = [...wires.get('peer')];
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,10));
|
||||
// Supply the native clipboard event which Chromium emits for this chord.
|
||||
const paste = new Event('paste', {bubbles:true,cancelable:true});
|
||||
Object.defineProperty(paste,'clipboardData',{value:{getData:()=> 'clipboard'}});
|
||||
source.term.textarea.dispatchEvent(paste);
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({bracketed,delayed,peerKitty,beforePaste,
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty) {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
const modes = [
|
||||
{name:'legacy',kitty:false,setup:''},
|
||||
{name:'native-kitty',kitty:false,setup:'\\x1b[>1u'},
|
||||
{name:'native-kitty-all-keys',kitty:false,setup:'\\x1b[>8u'},
|
||||
{name:'netcatty-kitty',kitty:true,setup:'\\x1b[>1u'},
|
||||
{name:'win32',kitty:false,setup:'\\x1b[?9001h'},
|
||||
];
|
||||
for (const mode of modes) {
|
||||
for (const bracketed of [false,true]) {
|
||||
for (const delayed of [true,false]) {
|
||||
for (const peerKitty of [false,true]) {
|
||||
const source = make('source', mode.kitty, {delayed}), peer = make('peer', peerKitty);
|
||||
try {
|
||||
sessionsRef.current = ['source','peer'].map(id=>({id,protocol:'ssh',workspaceId:'workspace'}));
|
||||
if (mode.setup) await new Promise(resolve=>source.term.write(mode.setup,resolve));
|
||||
if (peerKitty) await new Promise(resolve=>peer.term.write('\\x1b[>8u',resolve));
|
||||
if (bracketed) await new Promise(resolve=>source.term.write('\\x1b[?2004h',resolve));
|
||||
const key = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(key);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({plainInsert:true,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
results.push({mode:mode.name,bracketed,delayed,peerKitty,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:key.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
// Ordinary Insert still uses the physical-key broadcast path.
|
||||
if (!peerKitty && mode.name !== 'win32') {
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,
|
||||
}));
|
||||
results.push({plainInsert:true,mode:mode.name,pasteCalls:pasteCalls.get('source'),
|
||||
source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
}
|
||||
wires.get('source').length=0; wires.get('peer').length=0;
|
||||
const pasteShortcut = new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
});
|
||||
source.term.textarea.dispatchEvent(pasteShortcut);
|
||||
if (delayed) await new Promise(resolve=>setTimeout(resolve,20));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keyup', {
|
||||
bubbles:true,key:'V',code:'KeyV',keyCode:86,ctrlKey:true,shiftKey:true,
|
||||
}));
|
||||
results.push({configuredPaste:true,mode:mode.name,bracketed,pasteCalls:pasteCalls.get('source'),
|
||||
prevented:pasteShortcut.defaultPrevented,source:[...wires.get('source')],peer:[...wires.get('peer')]});
|
||||
} finally { source.dispose(); peer.dispose(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const shortcut of ['binding','snippet']) {
|
||||
let searchCalls = 0, snippetCalls = 0;
|
||||
const source = make('source', true, shortcut === 'binding'
|
||||
? {onSearch:()=>searchCalls++,bindings:DEFAULT_KEY_BINDINGS.map(binding=>binding.action === 'searchTerminal'
|
||||
? {...binding,pc:'Shift + Insert'} : binding)}
|
||||
: {snippets:[{id:'snippet',shortkey:'Shift + Insert'}],onSnippet:()=>snippetCalls++});
|
||||
try {
|
||||
await new Promise(resolve=>source.term.write('\\x1b[>1u',resolve));
|
||||
source.term.textarea.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
bubbles:true,cancelable:true,key:'Insert',code:'Insert',keyCode:45,shiftKey:true,
|
||||
}));
|
||||
results.push({shortcut,pasteCalls:pasteCalls.get('source'),snippetCalls,searchCalls,
|
||||
source:[...wires.get('source')]});
|
||||
} finally { source.dispose(); }
|
||||
}
|
||||
return JSON.stringify(results);
|
||||
})()`);
|
||||
for (const result of JSON.parse(results)) {
|
||||
if (result.plainInsert) {
|
||||
assert.equal(result.pasteCalls, 1);
|
||||
assert.deepEqual(result.source, ["\x1b[2~"]);
|
||||
assert.deepEqual(result.peer, ["\x1b[2~"]);
|
||||
continue;
|
||||
}
|
||||
if (result.shortcut) {
|
||||
assert.equal(result.pasteCalls, 0, result.shortcut);
|
||||
assert.equal(result.snippetCalls, result.shortcut === 'snippet' ? 1 : 0);
|
||||
assert.equal(result.searchCalls, result.shortcut === 'binding' ? 1 : 0);
|
||||
assert.deepEqual(result.source, []);
|
||||
continue;
|
||||
}
|
||||
const label = JSON.stringify(result);
|
||||
assert.deepEqual(result.beforePaste, [], label);
|
||||
assert.equal(result.prevented, false, "native paste must remain enabled: " + label);
|
||||
assert.equal(result.pasteCalls, result.configuredPaste ? 2 : 1, label);
|
||||
assert.equal(result.prevented, true, label);
|
||||
const expected = result.bracketed ? "\x1b[200~clipboard\x1b[201~" : "clipboard";
|
||||
assert.deepEqual(result.source, [expected], label);
|
||||
assert.deepEqual(result.peer, [expected], label);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createRequire } from "node:module";
|
||||
import { isIP } from "node:net";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
@@ -9,11 +10,38 @@ import {
|
||||
buildCodexHttpToml,
|
||||
buildExternalMcpHttpUrl,
|
||||
buildGenericHttpMcpJson,
|
||||
isExternalMcpHttpIpAddress,
|
||||
} from "./externalMcpHttp.ts";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const security = require("../electron/bridges/externalMcp/httpSecurity.cjs");
|
||||
|
||||
test("HTTP IP validation accepts valid literals and agrees with the runtime", () => {
|
||||
const valid = [
|
||||
"::1", "::", "0.0.0.0", "127.0.0.1", "255.255.255.255",
|
||||
"1:2:3:4:5:6:7:8", "fe80::1", "2001:db8::1", "::ffff:127.0.0.1",
|
||||
"1:2:3:4:5:6:127.0.0.1", "FE80::ABCD", "fe80::1%eth0",
|
||||
];
|
||||
for (const address of valid) {
|
||||
assert.equal(isExternalMcpHttpIpAddress(address), true, address);
|
||||
assert.equal(isExternalMcpHttpIpAddress(address), isIP(address) !== 0, address);
|
||||
}
|
||||
});
|
||||
|
||||
test("HTTP IP validation rejects malformed literals and agrees with the runtime", () => {
|
||||
const invalid = [
|
||||
"1::2::3", ":", "1:2:3:4:5:6:7:8:9", "1:::2", ":::", "12345::", "g::1",
|
||||
"127.000.0.1", "", " ", "\t\n", "127.0.0", "256.0.0.1", "-1.0.0.1",
|
||||
"1:2:3:4:5:6:7", "1:2:3:4:5:6:7:8::", ":1:2:3:4:5:6:7", "1:2:3:4:5:6:7:",
|
||||
"::ffff:127.000.0.1", "::ffff:256.0.0.1", "1:2:3:4:5:127.0.0.1",
|
||||
"1:2:3:4:5:6::127.0.0.1", "[::1]", "localhost", "fe80::1%", "fe80::1%a%b",
|
||||
];
|
||||
for (const address of invalid) {
|
||||
assert.equal(isExternalMcpHttpIpAddress(address), false, JSON.stringify(address));
|
||||
assert.equal(isExternalMcpHttpIpAddress(address), isIP(address) !== 0, JSON.stringify(address));
|
||||
}
|
||||
});
|
||||
|
||||
test("HTTP client URL stays on loopback unless a specific listen address is set", () => {
|
||||
assert.equal(DEFAULT_EXTERNAL_MCP_HTTP_PORT, security.DEFAULT_EXTERNAL_MCP_HTTP_PORT);
|
||||
assert.equal(
|
||||
|
||||
@@ -3,6 +3,35 @@ export const DEFAULT_EXTERNAL_MCP_HTTP_PORT = 47391;
|
||||
export const DEFAULT_EXTERNAL_MCP_HTTP_HOST = "127.0.0.1";
|
||||
export const EXTERNAL_MCP_HTTP_PATH = "/mcp";
|
||||
|
||||
function isIpv4Address(value: string): boolean {
|
||||
const parts = value.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
return parts !== null && parts.slice(1).every(
|
||||
(part) => Number(part) <= 255 && String(Number(part)) === part,
|
||||
);
|
||||
}
|
||||
|
||||
export function isExternalMcpHttpIpAddress(value: string): boolean {
|
||||
if (isIpv4Address(value)) return true;
|
||||
|
||||
const [literal, zone, ...extraZones] = value.split("%");
|
||||
if (extraZones.length || (zone !== undefined && !/^[0-9a-zA-Z.:-]+$/.test(zone))) return false;
|
||||
if (!literal.includes(":")) return false;
|
||||
|
||||
let address = literal;
|
||||
if (address.includes(".")) {
|
||||
const lastColon = address.lastIndexOf(":");
|
||||
if (!isIpv4Address(address.slice(lastColon + 1))) return false;
|
||||
// An embedded IPv4 tail occupies two IPv6 groups.
|
||||
address = `${address.slice(0, lastColon + 1)}0:0`;
|
||||
}
|
||||
|
||||
const halves = address.split("::");
|
||||
if (halves.length > 2) return false;
|
||||
const groups = halves.flatMap((half) => half ? half.split(":") : []);
|
||||
if (!groups.every((group) => /^[0-9a-fA-F]{1,4}$/.test(group))) return false;
|
||||
return halves.length === 2 ? groups.length < 8 : groups.length === 8;
|
||||
}
|
||||
|
||||
function formatHostForUrl(host: string): string {
|
||||
if (host.includes(":") && !host.startsWith("[")) return `[${host}]`;
|
||||
return host;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import type { TransferTask } from './models';
|
||||
import { getGlobalTransferBatchEligibility, listGloballyPausableTransferIds } from './sftpTransferActions';
|
||||
|
||||
test('a partially failed folder pause can be retried or explicitly resumed', () => {
|
||||
const task = { id: 'folder', status: 'pausing', isDirectory: true, resumable: true,
|
||||
pauseUnavailableReason: 'This transfer cannot be paused yet' } as TransferTask;
|
||||
assert.equal(getGlobalTransferBatchEligibility([task]).pausableCount, 1);
|
||||
assert.equal(getGlobalTransferBatchEligibility([task]).resumableCount, 1);
|
||||
assert.deepEqual(listGloballyPausableTransferIds([task]), ['folder']);
|
||||
assert.equal(getGlobalTransferBatchEligibility([{ ...task, pauseUnavailableReason: undefined }]).pausableCount, 0);
|
||||
});
|
||||
@@ -5,7 +5,8 @@ export function getGlobalTransferBatchEligibility(tasks: readonly TransferTask[]
|
||||
return {
|
||||
cancellableCount: listGloballyCancellableTransferIds(tasks).length,
|
||||
pausableCount: topLevel.filter((task) => (
|
||||
["pending", "queued", "transferring"].includes(task.status)
|
||||
(["pending", "queued", "transferring"].includes(task.status)
|
||||
|| (task.status === "pausing" && !!task.pauseUnavailableReason))
|
||||
&& task.resumable !== false
|
||||
&& !(task.ownerId === "dedicated-resume" && task.reconnectRequired)
|
||||
)).length,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
function configureAppProfile(app, devServerUrl) {
|
||||
const unpackaged = !app.isPackaged;
|
||||
const isDev = unpackaged && Boolean(devServerUrl);
|
||||
if (unpackaged) {
|
||||
// Keep the existing development profile path for both Vite and dist.
|
||||
app.setName("Netcatty Dev");
|
||||
const devProfile = path.join(app.getPath("userData"), "dev");
|
||||
fs.mkdirSync(devProfile, { recursive: true });
|
||||
app.setPath("userData", devProfile);
|
||||
// Chromium's Local Storage, IndexedDB and other session state must
|
||||
// follow the profile even if Electron has already resolved sessionData.
|
||||
app.setPath("sessionData", devProfile);
|
||||
}
|
||||
return { isDev, effectiveDevServerUrl: isDev ? devServerUrl : undefined };
|
||||
}
|
||||
|
||||
module.exports = { configureAppProfile };
|
||||
@@ -0,0 +1,51 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { configureAppProfile } = require("./appProfile.cjs");
|
||||
|
||||
function fakeApp(t, isPackaged) {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-profile-"));
|
||||
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
|
||||
const production = path.join(tmp, "netcatty");
|
||||
const paths = { userData: production, sessionData: production };
|
||||
const app = {
|
||||
isPackaged,
|
||||
name: "Netcatty",
|
||||
setName(name) { this.name = name; },
|
||||
getPath(name) { return paths[name]; },
|
||||
setPath(name, value) {
|
||||
assert.ok(fs.statSync(value).isDirectory());
|
||||
paths[name] = value;
|
||||
},
|
||||
};
|
||||
return { app, paths, production };
|
||||
}
|
||||
|
||||
test("unpackaged dist launches isolate both application and Chromium state", (t) => {
|
||||
const { app, paths, production } = fakeApp(t, false);
|
||||
assert.deepEqual(configureAppProfile(app, undefined), {
|
||||
isDev: false, effectiveDevServerUrl: undefined,
|
||||
});
|
||||
const dev = path.join(production, "dev");
|
||||
assert.deepEqual(paths, { userData: dev, sessionData: dev });
|
||||
assert.equal(app.name, "Netcatty Dev");
|
||||
});
|
||||
|
||||
test("Vite launches keep the development profile and URL", (t) => {
|
||||
const { app, paths, production } = fakeApp(t, false);
|
||||
const url = "http://localhost:5173";
|
||||
assert.deepEqual(configureAppProfile(app, url), { isDev: true, effectiveDevServerUrl: url });
|
||||
const dev = path.join(production, "dev");
|
||||
assert.deepEqual(paths, { userData: dev, sessionData: dev });
|
||||
});
|
||||
|
||||
test("packaged launches keep their data paths and ignore a Vite URL", (t) => {
|
||||
const { app, paths, production } = fakeApp(t, true);
|
||||
assert.deepEqual(configureAppProfile(app, "http://localhost:5173"), {
|
||||
isDev: false, effectiveDevServerUrl: undefined,
|
||||
});
|
||||
assert.deepEqual(paths, { userData: production, sessionData: production });
|
||||
assert.equal(app.name, "Netcatty");
|
||||
});
|
||||
@@ -254,19 +254,25 @@ function buildCodebuddyQueryOptions({
|
||||
elicitation, canUseTool,
|
||||
}) {
|
||||
const builtinTools = codebuddyBuiltinTools(toolIntegrationMode);
|
||||
const mcpMode = builtinTools.length === 0;
|
||||
const mcpServers = toSdkMcpServers(injectedMcpServers);
|
||||
if (mcpMode) {
|
||||
// These are only the app-managed servers. Show their tools directly without
|
||||
// enabling the CLI’s general-purpose discovery tools.
|
||||
for (const server of Object.values(mcpServers)) {
|
||||
if (server.type !== "sdk") server.defer_loading = false;
|
||||
}
|
||||
}
|
||||
const options = {
|
||||
cwd,
|
||||
includePartialMessages: true,
|
||||
permissionMode: "bypassPermissions",
|
||||
allowDangerouslySkipPermissions: true,
|
||||
extraArgs: { "dangerously-skip-permissions": null },
|
||||
mcpServers: toSdkMcpServers(injectedMcpServers),
|
||||
mcpServers,
|
||||
...(mcpMode ? { strictMcpConfig: true } : {}),
|
||||
// Keep unrelated CLI built-ins disabled by default, including future tools.
|
||||
tools: builtinTools,
|
||||
// `tools` is the built-in tool whitelist. In mcp mode it is [], so CodeBuddy
|
||||
// built-ins stay disabled while injected Netcatty MCP tools remain visible.
|
||||
// Do not mirror that empty list into allowedTools: the SDK treats
|
||||
// allowedTools as an auto-approval list, and allowedTools: [] prevents MCP
|
||||
// tool calls from running under bypassPermissions.
|
||||
disallowedTools: [...UI_DISALLOWED_TOOLS],
|
||||
// Keep the SDK isolated from user/project settings so local hooks, plugins,
|
||||
// or extra MCP servers cannot expand Netcatty's controlled tool boundary.
|
||||
|
||||
@@ -60,14 +60,38 @@ test("buildCodebuddyQueryOptions wires SDK options in isolated mode", () => {
|
||||
assert.equal(opts.abortController, ac);
|
||||
assert.equal(opts.resume, "sess-1");
|
||||
assert.deepEqual(opts.tools, []);
|
||||
// allowedTools must stay unset in mcp mode: tools:[] disables built-ins, while
|
||||
// allowedTools:[] would prevent injected Netcatty MCP tools from running.
|
||||
assert.ok(!("allowedTools" in opts));
|
||||
assert.equal(opts.strictMcpConfig, true);
|
||||
assert.equal(opts.mcpServers["netcatty-remote-hosts"].defer_loading, false);
|
||||
assert.ok(opts.disallowedTools.includes("AskUserQuestion"));
|
||||
assert.equal(opts.mcpServers["netcatty-remote-hosts"].type, "stdio");
|
||||
assert.deepEqual(opts.mcpServers["netcatty-remote-hosts"].env, { NETCATTY_MCP_PORT: "1" });
|
||||
});
|
||||
|
||||
test("mcp and default mode allow only the app-managed MCP configuration", () => {
|
||||
for (const toolIntegrationMode of ["mcp", undefined]) {
|
||||
const opts = buildCodebuddyQueryOptions({
|
||||
toolIntegrationMode,
|
||||
injectedMcpServers: [{ name: "netcatty", command: "/abs/electron" }],
|
||||
});
|
||||
assert.deepEqual(opts.tools, []);
|
||||
assert.ok(!("allowedTools" in opts));
|
||||
assert.deepEqual(opts.settingSources, []);
|
||||
assert.equal(opts.strictMcpConfig, true);
|
||||
assert.equal(opts.mcpServers.netcatty.command, "/abs/electron");
|
||||
assert.equal(opts.mcpServers.netcatty.defer_loading, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("skills mode keeps the Bash whitelist and UI exclusions", () => {
|
||||
const opts = buildCodebuddyQueryOptions({ toolIntegrationMode: "skills" });
|
||||
assert.deepEqual(opts.tools, ["Bash"]);
|
||||
assert.deepEqual(opts.disallowedTools, ["AskUserQuestion"]);
|
||||
assert.ok(!opts.disallowedTools.includes("Bash"));
|
||||
assert.ok(!("allowedTools" in opts));
|
||||
});
|
||||
|
||||
test("built-in tools are mode-aware", () => {
|
||||
assert.deepEqual(codebuddyBuiltinTools("mcp"), []);
|
||||
assert.deepEqual(codebuddyBuiltinTools(undefined), []);
|
||||
|
||||
+4
-9
@@ -88,6 +88,10 @@ const path = require("node:path");
|
||||
const os = require("node:os");
|
||||
const fs = require("node:fs");
|
||||
const { execFile } = require("node:child_process");
|
||||
// Separate profile selection from renderer loading. In particular, source
|
||||
// builds serving dist/ still need a non-production profile.
|
||||
const { configureAppProfile } = require("./appProfile.cjs");
|
||||
const { isDev, effectiveDevServerUrl } = configureAppProfile(app, process.env.VITE_DEV_SERVER_URL);
|
||||
const { getCliDiscoveryFilePath } = require("./cli/discoveryPath.cjs");
|
||||
const {
|
||||
SSH_DEEP_LINK_CHANNEL,
|
||||
@@ -291,15 +295,6 @@ app.on("web-contents-created", (_event, contents) => {
|
||||
});
|
||||
});
|
||||
|
||||
// Application configuration
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL;
|
||||
// Never treat a packaged app as "dev" even if the user has VITE_DEV_SERVER_URL set globally.
|
||||
const isDev = !app.isPackaged && !!devServerUrl;
|
||||
const effectiveDevServerUrl = isDev ? devServerUrl : undefined;
|
||||
if (isDev) {
|
||||
app.setName("Netcatty Dev");
|
||||
app.setPath("userData", path.join(app.getPath("userData"), "dev"));
|
||||
}
|
||||
const { applyPortableDataDirectory } = require("./portableData.cjs");
|
||||
const portableData = applyPortableDataDirectory({ app });
|
||||
if (portableData) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const NETCATTY_MCP_SERVER_INSTRUCTIONS =
|
||||
"Use Netcatty tools for terminals, hosts, SFTP, vault, snippets/scripts, and port forwards. For terminal work, call get_environment first; select by label or hostname and pass sessionId to terminal_execute/terminal_start. Never use the local shell for Netcatty session commands. If none matches, use vault_hosts_list and host_open. 15 core tools start loaded. For attachments, advanced SFTP, vault/notes, snippets, scripts, or port forwards, call load_netcatty_tools with a toolset; use all for every tool.";
|
||||
"Call get_environment first; select by label or hostname and pass sessionId to terminal tools. Never use the local shell for Netcatty session commands. If none matches, use vault_hosts_list and host_open. 15 core tools start loaded. Use load_netcatty_tools: sessions, attachments, sftp_advanced, vault_hosts, vault_notes, snippets, scripts, portforward, or all. For disconnected in-scope sessions, load sessions; use session_reconnect/session_recover instead of host_open (creates a new tab).";
|
||||
|
||||
module.exports = { NETCATTY_MCP_SERVER_INSTRUCTIONS };
|
||||
@@ -18,6 +18,9 @@ test("MCP server instructions route Netcatty terminal work through environment d
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /vault_hosts_list and host_open/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /load_netcatty_tools/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /15 core tools/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /load_netcatty_tools: sessions,/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /disconnected in-scope sessions, load sessions/);
|
||||
assert.match(NETCATTY_MCP_SERVER_INSTRUCTIONS, /session_reconnect\/session_recover instead of host_open \(creates a new tab\)/);
|
||||
});
|
||||
|
||||
test("stdio MCP server publishes the routing instructions during initialization", () => {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
"use strict";
|
||||
|
||||
const { isPluginDevelopmentEnabled } = require("./constants.cjs");
|
||||
|
||||
function startPluginHost(options) {
|
||||
// The plugin platform is not shipping in this release. Keep its data
|
||||
// untouched and allow existing developer workflows to opt in as before.
|
||||
if (!isPluginDevelopmentEnabled(options.env)) return null;
|
||||
|
||||
const reportFailure = (message, error) => {
|
||||
try { options.logger?.error?.(message, error); } catch {}
|
||||
};
|
||||
|
||||
@@ -5,16 +5,15 @@ const test = require("node:test");
|
||||
|
||||
const { startPluginHost } = require("./hostBootstrap.cjs");
|
||||
|
||||
test("normal release constructs the browser plugin host without a developer flag", async () => {
|
||||
let created = 0;
|
||||
const service = { manager: { async initialize() {}, async shutdown() {} } };
|
||||
test("default startup leaves the plugin host and stored plugin data untouched", () => {
|
||||
const effects = [];
|
||||
assert.equal(startPluginHost({
|
||||
env: {},
|
||||
createService() { created += 1; return service; },
|
||||
registerShutdown() {},
|
||||
logger: { error() {} },
|
||||
}), service);
|
||||
assert.equal(created, 1);
|
||||
createService() { effects.push("create"); },
|
||||
registerShutdown() { effects.push("register"); },
|
||||
logger: { error() { effects.push("error"); } },
|
||||
}), null);
|
||||
assert.deepEqual(effects, []);
|
||||
});
|
||||
|
||||
test("synchronous plugin host construction failure leaves Netcatty available", () => {
|
||||
|
||||
@@ -804,7 +804,7 @@ function registerPluginBridge(ipcMain, options) {
|
||||
if (!options.interactionService) throw new Error("Host interactions unavailable");
|
||||
return options.interactionService.setTerminalTarget(event.sender, target);
|
||||
});
|
||||
handle(CHANNELS.themeCatalog, async () => {
|
||||
handlePassive(CHANNELS.themeCatalog, null, async () => {
|
||||
if (!options.themeService) throw new Error("Plugin themes are unavailable");
|
||||
return options.themeService.catalog();
|
||||
});
|
||||
|
||||
@@ -53,6 +53,7 @@ test("disabled plugin runtime keeps passive host integration channels quiet", as
|
||||
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.terminalProviders)({}, {}), []);
|
||||
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.terminalSessionEvent)({}, {}), []);
|
||||
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.extensionProviders)({}, {}), []);
|
||||
assert.equal(await ipcMain.handlers.get(CHANNELS.themeCatalog)({}), null);
|
||||
assert.equal(await ipcMain.handlers.get(CHANNELS.credentialCatalogUpdate)({}, { entries: [] }), 0);
|
||||
assert.equal(await ipcMain.handlers.get(CHANNELS.setScopeCatalog)({}, {}), null);
|
||||
assert.deepEqual(await ipcMain.handlers.get(CHANNELS.getScopeCatalog)({}, {}), {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { jsonSchema, tool } from 'ai';
|
||||
import { MockLanguageModelV4, simulateReadableStream } from 'ai/test';
|
||||
import { processCattyStream, shouldEmitAgentEventsForStreamChunk } from './turnDrivers/cattyStreamProcessor';
|
||||
import type { CattyToolsBundle } from './capabilityTools';
|
||||
import { createInitialCattyRuntimeContext } from './cattyRuntimeContext';
|
||||
import type { ChatMessage } from '../types';
|
||||
|
||||
@@ -111,3 +113,100 @@ describe('processCattyStream reasoning continuation', () => {
|
||||
assert.match(continuation?.reasoningParts?.map(part => part.text).join('') ?? '', /thinking/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('processCattyStream iteration limit', () => {
|
||||
const usage = {
|
||||
inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined },
|
||||
outputTokens: { total: 1, text: 1, reasoning: undefined },
|
||||
};
|
||||
|
||||
async function run(t: import('node:test').TestContext, replies: ('poll' | 'summary')[], maxIterations: number) {
|
||||
const originalRaf = globalThis.requestAnimationFrame;
|
||||
const originalCancelRaf = globalThis.cancelAnimationFrame;
|
||||
t.after(() => {
|
||||
globalThis.requestAnimationFrame = originalRaf;
|
||||
globalThis.cancelAnimationFrame = originalCancelRaf;
|
||||
});
|
||||
globalThis.requestAnimationFrame = callback => setTimeout(() => callback(0), 0) as unknown as number;
|
||||
globalThis.cancelAnimationFrame = id => clearTimeout(id);
|
||||
|
||||
const messages: ChatMessage[] = [{ id: 'assistant-1', role: 'assistant', content: '', timestamp: 0 }];
|
||||
let calls = 0;
|
||||
const model = new MockLanguageModelV4({
|
||||
doStream: async () => {
|
||||
const reply = replies[calls++];
|
||||
assert.ok(reply, 'unexpected extra model step');
|
||||
return {
|
||||
stream: simulateReadableStream({ chunks: [
|
||||
{ type: 'stream-start', warnings: [] },
|
||||
...(reply === 'poll' ? [{
|
||||
type: 'tool-call' as const,
|
||||
toolCallId: `poll-${calls}`,
|
||||
toolName: 'terminal_poll',
|
||||
input: '{"jobId":"job-1"}',
|
||||
}] : [
|
||||
{ type: 'text-start' as const, id: 'summary' },
|
||||
{ type: 'text-delta' as const, id: 'summary', delta: 'The job completed.' },
|
||||
{ type: 'text-end' as const, id: 'summary' },
|
||||
]),
|
||||
{ type: 'finish', finishReason: { unified: reply === 'poll' ? 'tool-calls' : 'stop', raw: undefined }, usage },
|
||||
] }),
|
||||
};
|
||||
},
|
||||
});
|
||||
await processCattyStream({
|
||||
streamSessionId: 'session-1', model, systemPrompt: 'test',
|
||||
toolsBundle: {
|
||||
tools: {
|
||||
terminal_poll: tool({
|
||||
inputSchema: jsonSchema<{ jobId: string }>({
|
||||
type: 'object', properties: { jobId: { type: 'string' } }, required: ['jobId'],
|
||||
}),
|
||||
execute: async ({ jobId }) => ({ jobId, status: 'running', output: 'buffered output' }),
|
||||
}),
|
||||
} as unknown as CattyToolsBundle['tools'],
|
||||
toolsContext: {},
|
||||
},
|
||||
sdkMessages: [{ role: 'user', content: 'Check the job' }],
|
||||
signal: new AbortController().signal,
|
||||
currentAssistantMsgId: 'assistant-1', maxIterations,
|
||||
runtimeContext: createInitialCattyRuntimeContext({
|
||||
chatSessionId: 'session-1', turnId: 'turn-1', permissionMode: 'auto', scopeType: 'terminal',
|
||||
}),
|
||||
ui: {
|
||||
addMessageToSession: (sessionId, message) => {
|
||||
assert.equal(sessionId, 'session-1');
|
||||
messages.push(message);
|
||||
},
|
||||
updateMessageById: (_sessionId, id, updater) => {
|
||||
const index = messages.findIndex(message => message.id === id);
|
||||
if (index >= 0) messages[index] = updater(messages[index]);
|
||||
},
|
||||
},
|
||||
});
|
||||
return { messages, calls };
|
||||
}
|
||||
|
||||
it('adds a non-error assistant notice after terminal_poll exhausts the step cap', async t => {
|
||||
const { messages, calls } = await run(t, ['poll', 'poll'], 2);
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(messages.at(-2)?.role, 'tool');
|
||||
assert.match(messages.at(-2)?.toolResults?.[0].content ?? '', /job-1/);
|
||||
const notice = messages.at(-1)!;
|
||||
assert.equal(notice.role, 'assistant');
|
||||
assert.equal(notice.iterationLimit, 2);
|
||||
assert.equal(notice.errorInfo, undefined);
|
||||
});
|
||||
|
||||
for (const [name, replies, maxIterations] of [
|
||||
['natural stop before the cap', ['summary'], 2],
|
||||
['natural stop on the last allowed step', ['summary'], 1],
|
||||
['post-tool summary on the last allowed step', ['poll', 'summary'], 2],
|
||||
] as const) {
|
||||
it(`does not add a limit notice for ${name}`, async t => {
|
||||
const { messages } = await run(t, [...replies], maxIterations);
|
||||
assert.equal(messages.at(-1)?.content, 'The job completed.');
|
||||
assert.ok(messages.every(message => message.iterationLimit === undefined));
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -141,6 +141,8 @@ export async function processCattyStream(input: ProcessCattyStreamInput): Promis
|
||||
: undefined;
|
||||
const promptCache = createCattyPromptCache(systemPrompt, model.provider, endpoint);
|
||||
|
||||
let reachedIterationLimit = false;
|
||||
const stopAtIterationLimit = isStepCount(maxIterations);
|
||||
const result = streamText({
|
||||
model,
|
||||
messages: promptCache.prepareMessages(sdkMessages),
|
||||
@@ -152,7 +154,12 @@ export async function processCattyStream(input: ProcessCattyStreamInput): Promis
|
||||
permissionMode: runtimeContext.permissionMode,
|
||||
chatSessionId: runtimeContext.chatSessionId,
|
||||
}),
|
||||
stopWhen: isStepCount(maxIterations),
|
||||
// The SDK evaluates stopWhen only when tool work would allow another
|
||||
// step. A natural final reply (even on the last allowed step) bypasses it.
|
||||
stopWhen: async (options) => {
|
||||
reachedIterationLimit = await stopAtIterationLimit(options);
|
||||
return reachedIterationLimit;
|
||||
},
|
||||
abortSignal: signal,
|
||||
include: { rawChunks: true },
|
||||
timeout: buildCattyStreamTimeouts({
|
||||
@@ -580,6 +587,16 @@ export async function processCattyStream(input: ProcessCattyStreamInput): Promis
|
||||
const usage = await result.usage;
|
||||
const finalStep = await result.finalStep;
|
||||
const performance = finalStep?.performance;
|
||||
if (reachedIterationLimit && !signal.aborted) {
|
||||
clearCompactionStatusFromAssistant(activeMsgId);
|
||||
ui.addMessageToSession(streamSessionId, {
|
||||
id: generateId(),
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
timestamp: Date.now(),
|
||||
iterationLimit: maxIterations,
|
||||
});
|
||||
}
|
||||
// onEnd can run before this consumer flushes its final text and creates the
|
||||
// post-tool assistant message. Attach turn totals only after that flush.
|
||||
if (usage) {
|
||||
|
||||
@@ -171,6 +171,8 @@ export interface ChatMessage {
|
||||
timestamp: number;
|
||||
model?: string;
|
||||
providerId?: AIProviderId;
|
||||
/** Catty stopped at its tool-loop cap; rendered as a non-error notice. */
|
||||
iterationLimit?: number;
|
||||
errorInfo?: {
|
||||
type: 'network' | 'auth' | 'timeout' | 'provider' | 'agent' | 'unknown';
|
||||
message: string;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"[\\u0590-\\u08ff\\u200f\\u202b\\u202e\\u2067\\ufb1d-\\ufdff\\ufe70-\\ufefc\\u{10800}-\\u{10fff}\\u{1e800}-\\u{1eeff}]"
|
||||
Generated
+1
-1
@@ -27,6 +27,7 @@
|
||||
"@withfig/autocomplete": "^2.692.3",
|
||||
"ajv": "8.18.0",
|
||||
"ajv-formats": "3.0.1",
|
||||
"bidi-js": "1.0.3",
|
||||
"css-tree": "^3.2.1",
|
||||
"electron-updater": "^6.8.3",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
@@ -10231,7 +10232,6 @@
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
|
||||
"integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"require-from-string": "^2.0.2"
|
||||
|
||||
+2
-1
@@ -42,7 +42,7 @@
|
||||
"pack:linux": "npm run build && cross-env NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --publish=never",
|
||||
"pack:linux-x64": "npm run build && cross-env npm_config_arch=x64 NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --x64 --publish=never",
|
||||
"pack:linux-arm64": "npm run build && cross-env npm_config_arch=arm64 NODE_OPTIONS=--disable-warning=DEP0190 electron-builder --config electron-builder.config.cjs --linux --arm64 --publish=never",
|
||||
"postinstall": "patch-package && node scripts/patch-xterm-macos-column-selection.cjs && node scripts/patch-xterm-foreground-intense.cjs && node scripts/patch-xterm-ligatures-font-cache.cjs && node scripts/patch-xterm-image-tile-stride.cjs && node scripts/patch-xterm-image-iip-type.cjs && electron-builder install-app-deps && node scripts/rebuildPatchedNodePty.cjs && node scripts/patch-xterm-webgl-atlas.cjs",
|
||||
"postinstall": "patch-package && node scripts/patch-xterm-macos-column-selection.cjs && node scripts/patch-xterm-foreground-intense.cjs && node scripts/patch-xterm-joined-width.cjs && node scripts/patch-xterm-ligatures-font-cache.cjs && node scripts/patch-xterm-image-tile-stride.cjs && node scripts/patch-xterm-image-iip-type.cjs && electron-builder install-app-deps && node scripts/rebuildPatchedNodePty.cjs && node scripts/patch-xterm-webgl-atlas.cjs",
|
||||
"rebuild": "electron-builder install-app-deps",
|
||||
"tool:cli": "node electron/cli/netcatty-tool-cli.cjs",
|
||||
"generate:capability-tools": "node scripts/generate-capability-tools.cjs",
|
||||
@@ -97,6 +97,7 @@
|
||||
"@withfig/autocomplete": "^2.692.3",
|
||||
"ajv": "8.18.0",
|
||||
"ajv-formats": "3.0.1",
|
||||
"bidi-js": "1.0.3",
|
||||
"css-tree": "^3.2.1",
|
||||
"electron-updater": "^6.8.3",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env node
|
||||
/* global console, process */
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
// xterm 6.1 beta applies a joined run's *total* width correction as
|
||||
// letter-spacing, which Chromium can apply once per glyph. Joined cells are
|
||||
// already sized in terminal columns; use that width instead of changing the
|
||||
// text spacing (which can also interfere with contextual shaping).
|
||||
const VERSION = "6.1.0-beta.292";
|
||||
// Share the terminalBidiJoiner gate. Scope this fix to the new RTL
|
||||
// shaping path; leave the existing ASCII font-ligature renderer unchanged.
|
||||
const rtl = new RegExp(require("../lib/terminalRtlCharacter.json"), "u");
|
||||
// Keep the outer span exactly on the grid. When wider fallback glyphs would
|
||||
// extend into the next cell, compress the complete shaped text horizontally
|
||||
// in an inner span. Keep the untouched text together for browser bidi/shaping,
|
||||
// and avoid measuring DOM layout during rendering: xterm's existing spacing
|
||||
// calculation already supplies the difference from the cached natural width.
|
||||
const patches = [
|
||||
{ file: "xterm.js", joined: "H", chars: "$", span: "w", width: "y*_", spacing: "k", rows: "m" },
|
||||
{ file: "xterm.mjs", joined: "fi", chars: "_i", span: "I", width: "Rr*h", spacing: "Ot", rows: "p" },
|
||||
].map(({ file, joined, chars, span, width, spacing, rows }) => {
|
||||
const defaultSpacing = `${spacing}!==this.defaultSpacing&&(${span}.style.letterSpacing=\`\${${spacing}}px\`)`;
|
||||
const original = `,${defaultSpacing},${rows}.push(${span}),`;
|
||||
const replacement = [
|
||||
`;if(${joined}&&${rtl}.test(${chars})){`,
|
||||
`const allocated=${width};${span}.style.width=allocated+"px";${span}.style.letterSpacing="0px";`,
|
||||
`if(${spacing}<0&&allocated>0){`,
|
||||
'const run=this._document.createElement("span");',
|
||||
`run.textContent=${span}.textContent;`,
|
||||
'run.style.transformOrigin="left center";',
|
||||
`run.style.transform="scaleX("+allocated/(allocated-${spacing})+")";`,
|
||||
`${span}.replaceChildren(run);`,
|
||||
`}}else{${defaultSpacing}}${rows}.push(${span}),`,
|
||||
].join("");
|
||||
return [file, original, replacement];
|
||||
});
|
||||
|
||||
function patchJoinedWidth(source, original, replacement) {
|
||||
if (source.split(replacement).length === 2 && !source.replace(replacement, "").includes(original)) return source;
|
||||
if (source.split(original).length !== 2) throw new Error("unexpected xterm joined-width patch anchor");
|
||||
return source.replace(original, replacement);
|
||||
}
|
||||
|
||||
function patchInstalledXterm(root = process.cwd()) {
|
||||
const base = path.resolve(root, "node_modules/@xterm/xterm");
|
||||
const version = JSON.parse(fs.readFileSync(path.join(base, "package.json"), "utf8")).version;
|
||||
if (version !== VERSION) throw new Error(`unsupported @xterm/xterm ${version}; expected ${VERSION}`);
|
||||
const files = patches.map(([file, original, replacement]) => {
|
||||
const filename = path.join(base, "lib", file);
|
||||
const source = fs.readFileSync(filename, "utf8");
|
||||
return [filename, source, patchJoinedWidth(source, original, replacement)];
|
||||
});
|
||||
for (const [filename, source, patched] of files) {
|
||||
if (source !== patched) fs.writeFileSync(filename, patched);
|
||||
}
|
||||
if (files.some(([, source, patched]) => source !== patched)) {
|
||||
fs.rmSync(path.resolve(root, "node_modules/.vite"), { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
try { patchInstalledXterm(); }
|
||||
catch (error) { console.error(error.message); process.exitCode = 1; }
|
||||
}
|
||||
module.exports = { patchInstalledXterm };
|
||||
@@ -0,0 +1,76 @@
|
||||
# Official Linux package QA
|
||||
|
||||
Temporary same-repository **Draft** PR only. Do not merge or publish this branch.
|
||||
The workflow uses standard GitHub-hosted Ubuntu 22.04, read-only contents/actions
|
||||
permissions, pinned official actions and checkout without persisted credentials.
|
||||
No release workflow is dispatched.
|
||||
|
||||
Candidate metadata is explicit JSON. `candidate.json` pins a23868e, official run
|
||||
44901156879 / artifact 14706239224. `candidate-9d4e90b.json` pins the independently
|
||||
verified 9d4e90b run 44903060405 / artifact 14707251480. No floating latest or older
|
||||
fallback is used. Each report records its full candidate SHA; never mix results.
|
||||
The downloader checks repository/run/job/artifact metadata, archive SHA-256, deb
|
||||
SHA-256 from the official build log, and amd64 architecture before extraction.
|
||||
|
||||
The official deb is extracted as the non-root runner. Installer scripts are
|
||||
never executed because those scripts change SUID/AppArmor. This is extracted
|
||||
package execution, not system-install acceptance. The application archive is
|
||||
never patched. No --no-sandbox, sysctl, AppArmor, SUID or system security changes
|
||||
are used. A normal launch failure is a failure with actual reviewed stderr.
|
||||
The stock renderer preference is sandbox:false; the report states this honestly
|
||||
and does not certify full renderer sandboxing.
|
||||
|
||||
Only the downloader receives the GitHub token. Electron gets an explicit
|
||||
environment allowlist with fresh scenario-specific HOME/XDG/temp/profile paths.
|
||||
Xvfb's temporary XAUTHORITY is passed through for the isolated display. No model
|
||||
credentials, business data or production account is used. SSH/SFTP and DevTools
|
||||
listen only on loopback. SSH credentials and host keys are generated per run.
|
||||
|
||||
Independent scenarios prevent one functional assertion from skipping another:
|
||||
|
||||
- `persistence`: real packaged launch, synthetic saved host visible in the vault,
|
||||
graceful full process quit, restart with the same profile, same data visible.
|
||||
- `ssh`: actual encrypted SSH2 loopback transport through the production UI.
|
||||
Explicitly focus xterm's real input element, use native renderer input events,
|
||||
assert server receive and real terminal echo, destroy the server connection,
|
||||
reconnect the original tab, assert a second shell and stable tab ID. Accept the stock automatic reconnect
|
||||
path or the visible manual reconnect path, recording which occurred. Receive
|
||||
hex, focus and echo diagnostics distinguish harness input failures from an
|
||||
established product regression.
|
||||
- `sftp`: establish a separate real SSH connection and SFTP subsystem, then invoke
|
||||
the production preload transfer API into the actual packaged native runtime.
|
||||
This covers real transport/control behavior, not a certification of UI button
|
||||
gestures. Capture transfer-center screenshots; pause mid-file; drain pending
|
||||
reads and asynchronous checkpoint fingerprint work; retain every settling
|
||||
sample; require at least 2.5 s of sustained actual server bytes and current
|
||||
native-progress stability;
|
||||
assert both are unchanged; resume and assert both grow; finish and compare
|
||||
file length and SHA-256 to a deterministic 32 MiB payload. Record every READ
|
||||
receive/reply with subsystem, unique handle, path, offset and logical range.
|
||||
Separate the isolated payload handle from shared source-fingerprint reads;
|
||||
permit only already-started payload ranges to drain after pause, forbid new
|
||||
payload range starts before resume, and reject completion before resume.
|
||||
Sample the production committed checkpoint, verify its actual local prefix
|
||||
bytes against the source, and check the full staging-content hash remains
|
||||
unchanged. Logical file length / preallocation is not counted as progress. No component fixture,
|
||||
injected transfer implementation, or checkout-sourced bridge substitutes for
|
||||
the official package's transfer code.
|
||||
- `clipboard`: independently test real terminal Select All / Copy after proving
|
||||
the command reached the server and the production terminal buffer. This
|
||||
independent step cannot gate SSH reconnect or SFTP.
|
||||
- `host-filter` (9d4e90b only): seed synthetic vault hosts and call the actual
|
||||
packaged public/vault/hosts/list dispatcher and renderer bridge. Independently
|
||||
check no-filter compatibility, empty/non-string filters, multiword keyword
|
||||
matching, group path boundaries, case sensitivity and combined filters.
|
||||
|
||||
Evidence lives under scenario directories: `assertions.json`, reviewed
|
||||
`electron-output.log`, `sftp-protocol.json` for the SFTP request/reply audit,
|
||||
optional actual-display `sftp-pause-resume.mp4`, and real application screenshots named for each scene.
|
||||
`provenance.json` at the artifact root identifies the official package. Raw
|
||||
profiles and payloads are never uploaded. Save tested assertions and reviewed
|
||||
evidence before cleanup; cleanup uses ssh2 end(), while only the intentional
|
||||
transport-loss scene destroys the test server socket. Logs and assertion diagnostics are
|
||||
checked for the ephemeral password, private keys, GitHub credentials and bearer
|
||||
headers before logs/screenshots are published; matches withhold those files and
|
||||
fail. Artifacts expire after three days. Read each assertion report: environment
|
||||
and harness failures never count as feature passes.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"repository": "binaricat/Netcatty",
|
||||
"repositoryId": 1111357457,
|
||||
"sha": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
|
||||
"run": 44903060405,
|
||||
"artifact": 14707251480,
|
||||
"name": "netcatty-linux-x64",
|
||||
"zipSha256": "26c11c14501f58616600dc648a61dc36c256c558b86cc8fcff62bd0f38a9ade7",
|
||||
"deb": "Netcatty-0.0.0-sha-9d4e90b-linux-amd64.deb",
|
||||
"debSha256": "45781c366dcf9715eb681293e58e2ed47eba3cc9872a52cd2e1b8f3cf3de6ae0"
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"repository": "binaricat/Netcatty",
|
||||
"repositoryId": 1111357457,
|
||||
"sha": "a23868ee88603d0182c5370fca851cb9d05d7f8f",
|
||||
"run": 44901156879,
|
||||
"artifact": 14706239224,
|
||||
"name": "netcatty-linux-x64",
|
||||
"zipSha256": "c6a3a18fd44592f6c8207aa5bbf82e6a034e7c15bf54e1633296f3ab0e0fb15c",
|
||||
"deb": "Netcatty-0.0.0-sha-a23868e-linux-amd64.deb",
|
||||
"debSha256": "d06498511d6298a3e0a46c3bed6626843ba3d9bed987b1d9a20c41874bc98929"
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
// Adapted from terminal-broadcast-ssh.live.cjs: packaged app, real SSH, native input.
|
||||
const assert = require('node:assert/strict');
|
||||
const crypto = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const net = require('node:net');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
const { Server } = require('ssh2');
|
||||
const loginPassword = crypto.randomBytes(24).toString('hex');
|
||||
const root = path.resolve(process.env.QA_ROOT);
|
||||
const scenario = process.argv[2] || 'persistence';
|
||||
assert(['persistence', 'ssh', 'sftp', 'host-filter', 'clipboard'].includes(scenario));
|
||||
const pinned = require(path.resolve(__dirname, process.env.QA_CANDIDATE || 'candidate.json'));
|
||||
const evidence = path.join(root, 'evidence', scenario);
|
||||
const executable = path.join(root, 'package/opt/Netcatty/netcatty');
|
||||
const report = { candidate: pinned.sha, scenario, launcher: 'not_run', persistence: 'not_run', sshReconnect: 'not_run', sftpPauseResume: 'not_run', install: 'not_covered: extracted official deb; postinst never executed', sandbox: 'stock application configuration; no disabling switches or security changes' };
|
||||
const logs = [];
|
||||
const screenshots = new Map();
|
||||
let videoChild;
|
||||
const videoPath = path.join(root, 'sftp-pause-resume.mp4');
|
||||
let child, cdp, mainCdp, fixture;
|
||||
const profile = path.join(root, `profile-${scenario}`);
|
||||
let watchdog;
|
||||
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const deadline = (ms) => Date.now() + ms;
|
||||
function waitForExit(child, ms) {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
const onExit = () => { clearTimeout(timer); resolve(true); };
|
||||
const timer = setTimeout(() => { child.off('exit', onExit); resolve(false); }, ms);
|
||||
child.once('exit', onExit);
|
||||
});
|
||||
}
|
||||
async function until(label, check, ms = 15000) {
|
||||
const end = deadline(ms);
|
||||
let last;
|
||||
while (Date.now() < end) {
|
||||
try {
|
||||
const value = await check();
|
||||
if (value) return value;
|
||||
} catch (error) { last = error; }
|
||||
await pause(100);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${label}${last ? `: ${last.message}` : ''}`);
|
||||
}
|
||||
async function freePort() {
|
||||
const server = net.createServer();
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
return port;
|
||||
}
|
||||
|
||||
class Devtools {
|
||||
constructor(url) {
|
||||
this.ws = new WebSocket(url);
|
||||
this.nextId = 0;
|
||||
this.pending = new Map();
|
||||
this.ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
const item = this.pending.get(message.id);
|
||||
if (!item) return;
|
||||
this.pending.delete(message.id);
|
||||
if (message.error) item.reject(new Error(message.error.message));
|
||||
else item.resolve(message.result);
|
||||
});
|
||||
}
|
||||
async connect() {
|
||||
await new Promise((resolve, reject) => {
|
||||
this.ws.addEventListener('open', resolve, { once: true });
|
||||
this.ws.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
}
|
||||
send(method, params = {}, timeoutMs = 10000) {
|
||||
const id = ++this.nextId;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, timeoutMs);
|
||||
this.pending.set(id, { resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } });
|
||||
this.ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
}
|
||||
async eval(expression, timeoutMs = 10000) {
|
||||
const result = await this.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, timeoutMs);
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
return result.result.value;
|
||||
}
|
||||
close() { this.ws.close(); }
|
||||
}
|
||||
|
||||
async function clickPoint(cdp, { x, y }, button = 'left') {
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button, clickCount: 1 });
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button, clickCount: 1 });
|
||||
}
|
||||
async function clickElement(cdp, selector, index = 0, button = 'left') {
|
||||
const point = await cdp.eval(`(() => {const items=[...document.querySelectorAll(${JSON.stringify(selector)})].filter(e=>{const r=e.getBoundingClientRect();return r.width>0&&r.height>0&&r.x>=0&&r.y>=0});const e=items[${index}];if(!e)throw new Error('Missing visible element: '+${JSON.stringify(selector)});const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()`);
|
||||
await clickPoint(cdp, point, button);
|
||||
}
|
||||
async function clickText(cdp, label, selector = 'button') {
|
||||
const point = await cdp.eval(`(() => {const e=[...document.querySelectorAll(${JSON.stringify(selector)})].find(x=>x.textContent.trim()===${JSON.stringify(label)}&&x.getBoundingClientRect().x>=0);if(!e)throw new Error('Missing button: '+${JSON.stringify(label)});const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()`);
|
||||
await clickPoint(cdp, point);
|
||||
}
|
||||
async function insertText(mainCdp, value) {
|
||||
await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')).webContents.insertText(${JSON.stringify(value)})`);
|
||||
}
|
||||
async function key(mainCdp, code, type = 'keyDown') {
|
||||
await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')).webContents.sendInputEvent({type:${JSON.stringify(type)},keyCode:${JSON.stringify(code)}})`);
|
||||
}
|
||||
async function typeLine(mainCdp, value) {
|
||||
for (const letter of value) await key(mainCdp, letter, 'char');
|
||||
await key(mainCdp, 'Enter');
|
||||
await key(mainCdp, 'Enter', 'keyUp');
|
||||
}
|
||||
async function terminalLine(cdp, mainCdp, value) {
|
||||
await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')).focus()`);
|
||||
await until('connected terminal without overlay', () => cdp.eval(`!![...document.querySelectorAll('.xterm-helper-textarea')].find(e => e.closest('.xterm')?.getBoundingClientRect().width > 0) && !document.querySelector('[data-terminal-disconnected-dialog="true"]')`));
|
||||
const focus = await cdp.eval(`(() => { const e = [...document.querySelectorAll('.xterm-helper-textarea')].find(e => e.closest('.xterm')?.getBoundingClientRect().width > 0); e.focus(); return {focused: document.activeElement === e, tag: document.activeElement.tagName, className: document.activeElement.className}; })()`);
|
||||
assert.equal(focus.focused, true, 'Harness must focus actual xterm input');
|
||||
report.inputFocus = focus;
|
||||
await pause(350);
|
||||
await cdp.send('Input.insertText', {text: value});
|
||||
await cdp.send('Input.dispatchKeyEvent', {type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13, text: '\r', unmodifiedText: '\r'});
|
||||
await cdp.send('Input.dispatchKeyEvent', {type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
|
||||
}
|
||||
function startSshFixture() {
|
||||
const { privateKey } = crypto.generateKeyPairSync('rsa', {
|
||||
modulusLength: 2048,
|
||||
privateKeyEncoding: { type: 'pkcs1', format: 'pem' },
|
||||
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
||||
});
|
||||
const sessions = [];
|
||||
const clients = new Set();
|
||||
const payload = Buffer.alloc(32 * 1024 * 1024);
|
||||
for (let i = 0; i < payload.length; i++) payload[i] = i % 251;
|
||||
const sftpStats = { reads: 0, bytesSent: 0, activeReads: 0 };
|
||||
let nextReadAt = 0;
|
||||
const protocol = {channels: [], opens: [], reads: [], closes: []};
|
||||
let nextChannel = 0, nextHandle = 0, nextRead = 0;
|
||||
const server = new Server({ hostKeys: [privateKey] }, (client) => {
|
||||
clients.add(client);
|
||||
client.on('error', () => {});
|
||||
client.on('close', () => clients.delete(client));
|
||||
const session = { receivedHex: '', sent: [], commands: [], prompts: 0, answers: [], pending: false, ready: false };
|
||||
sessions.push(session);
|
||||
client.on('close', () => { session.closedAt = Date.now(); });
|
||||
client.on('authentication', (ctx) => {
|
||||
if (ctx.method === 'password' && ctx.password === loginPassword) ctx.accept();
|
||||
else ctx.reject(['password']);
|
||||
});
|
||||
client.on('ready', () => {
|
||||
client.on('session', (accept) => {
|
||||
const channel = accept();
|
||||
channel.on('pty', (acceptPty) => acceptPty && acceptPty());
|
||||
channel.on('sftp', acceptSftp => {
|
||||
const remote = acceptSftp();
|
||||
const channelId = ++nextChannel;
|
||||
protocol.channels.push({id: channelId, openedAt: Date.now()});
|
||||
const handles = new Map();
|
||||
remote.on('error', () => {});
|
||||
const attrs = { size: payload.length, mode: 0o100644, uid: 1, gid: 1, atime: 1700000000, mtime: 1700000000 };
|
||||
remote.on('REALPATH', id => remote.name(id, [{ filename: '/', longname: '/', attrs: {...attrs, mode: 0o40755} }]));
|
||||
for (const operation of ['STAT', 'LSTAT', 'FSTAT']) remote.on(operation, id => remote.attrs(id, attrs));
|
||||
remote.on('OPEN', (id, filePath, flags) => {
|
||||
const handle = `qa-handle-${++nextHandle}`;
|
||||
const info = {handle, channelId, path: String(filePath), flags, openedAt: Date.now()};
|
||||
handles.set(handle, info); protocol.opens.push(info);
|
||||
remote.handle(id, Buffer.from(handle));
|
||||
});
|
||||
remote.on('CLOSE', (id, handleBytes) => {
|
||||
const handle = handleBytes.toString();
|
||||
const info = handles.get(handle); if (info) info.closedAt = Date.now();
|
||||
protocol.closes.push({handle, channelId, at: Date.now()});
|
||||
remote.status(id, 0);
|
||||
});
|
||||
remote.on('READ', (id, handleBytes, position, length) => {
|
||||
const handle = handleBytes.toString();
|
||||
const request = {sequence: ++nextRead, channelId, handle, path: handles.get(handle)?.path, offset: position, length, logicalRangeStart: Math.floor(position / 32768) * 32768, receivedAt: Date.now()};
|
||||
protocol.reads.push(request);
|
||||
sftpStats.reads++; sftpStats.activeReads++;
|
||||
const due = Math.max(Date.now(), nextReadAt); nextReadAt = due + 20;
|
||||
setTimeout(() => {
|
||||
sftpStats.activeReads--;
|
||||
if (remote.destroyed) { request.droppedAt = Date.now(); return; }
|
||||
request.repliedAt = Date.now();
|
||||
if (position >= payload.length) { request.replyBytes = 0; remote.status(id, 1); }
|
||||
else { const bytes = payload.subarray(position, Math.min(payload.length, position + length)); request.replyBytes = bytes.length; remote.data(id, bytes); sftpStats.bytesSent += bytes.length; }
|
||||
}, due - Date.now());
|
||||
});
|
||||
});
|
||||
channel.on('shell', (acceptShell) => {
|
||||
const stream = acceptShell();
|
||||
session.ready = true; session.readyAt = Date.now();
|
||||
stream.on('error', () => {});
|
||||
let line = '';
|
||||
stream.write('fixture$ ');
|
||||
stream.on('data', (buffer) => {
|
||||
session.receivedHex = (session.receivedHex + buffer.toString('hex')).slice(-8192);
|
||||
for (const char of buffer.toString('utf8')) {
|
||||
if (char === '\r' || char === '\n') {
|
||||
if (!line && char === '\n') continue;
|
||||
const submitted = line;
|
||||
line = '';
|
||||
if (session.pending) {
|
||||
session.answers.push(submitted);
|
||||
session.pending = false;
|
||||
stream.write('\r\naccepted\r\nfixture$ ');
|
||||
} else if (submitted === 'ask') {
|
||||
session.commands.push(submitted);
|
||||
session.prompts += 1;
|
||||
session.pending = true;
|
||||
stream.write('\r\nPassword:');
|
||||
} else if (submitted) {
|
||||
session.commands.push(submitted);
|
||||
session.sent.push(`ran: ${submitted}`);
|
||||
stream.write(`\r\nran: ${submitted}\r\nfixture$ `);
|
||||
}
|
||||
} else if (char === '\x7f') line = line.slice(0, -1);
|
||||
else line += char;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
return { server, sessions, clients, sftpStats, payload, protocol };
|
||||
}
|
||||
|
||||
async function launch() {
|
||||
const debugPort = await freePort();
|
||||
const inspectPort = await freePort();
|
||||
// Build an allowlist environment. No GitHub/Actions tokens, provider credentials,
|
||||
// development server, NODE_OPTIONS, preload overrides or no-sandbox escape hatch.
|
||||
const env = { PATH: process.env.PATH, DISPLAY: process.env.DISPLAY, XAUTHORITY: process.env.XAUTHORITY, LANG: 'en_US.UTF-8',
|
||||
HOME: path.join(root, scenario, 'home'), XDG_CONFIG_HOME: path.join(root, scenario, 'config'),
|
||||
XDG_CACHE_HOME: path.join(root, scenario, 'cache'), XDG_DATA_HOME: path.join(root, scenario, 'data'),
|
||||
XDG_RUNTIME_DIR: path.join(root, scenario, 'runtime'), TMPDIR: path.join(root, scenario, 'tmp') };
|
||||
for (const key of ['HOME', 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME', 'XDG_RUNTIME_DIR', 'TMPDIR']) fs.mkdirSync(env[key], { recursive: true, mode: 0o700 });
|
||||
child = spawn(executable, [`--user-data-dir=${profile}`, '--remote-debugging-address=127.0.0.1', `--remote-debugging-port=${debugPort}`, `--inspect=127.0.0.1:${inspectPort}`], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
child.on('error', error => logs.push(`launcher: ${error.message}\n`));
|
||||
for (const stream of [child.stdout, child.stderr]) stream.on('data', bytes => {
|
||||
logs.push(bytes.toString());
|
||||
if (logs.reduce((n, item) => n + item.length, 0) > 2_000_000) child.kill('SIGTERM');
|
||||
});
|
||||
const target = await until('official packaged renderer (stock sandbox required)', async () => {
|
||||
assert.equal(child.exitCode, null, `Official Electron exited ${child.exitCode}; inspect stderr`);
|
||||
const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json();
|
||||
return targets.find(item => item.type === 'page' && /index\.html/.test(item.url));
|
||||
}, 30000);
|
||||
const rendererUrl = new URL(target.url);
|
||||
assert.equal(rendererUrl.protocol, 'app:', 'Official production renderer protocol');
|
||||
assert.equal(rendererUrl.host, 'netcatty');
|
||||
assert.equal(rendererUrl.pathname, '/index.html');
|
||||
cdp = new Devtools(target.webSocketDebuggerUrl);
|
||||
await cdp.connect();
|
||||
await cdp.send('Page.bringToFront');
|
||||
const inspector = await until('official Electron main inspector', async () => (await (await fetch(`http://127.0.0.1:${inspectPort}/json/list`)).json())[0]);
|
||||
mainCdp = new Devtools(inspector.webSocketDebuggerUrl);
|
||||
await mainCdp.connect();
|
||||
report.rendererTarget = { id: target.id, url: target.url };
|
||||
await until('production renderer DOM loaded', () => cdp.eval(`Boolean(document.querySelector('input[placeholder^="Find a host"]'))`));
|
||||
report.nativeWindows = await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().map(w => ({id: w.id, url: w.webContents.getURL()}))`);
|
||||
await until('native production window URL committed', () => mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().some(w => w.webContents.getURL().startsWith('app://netcatty/index.html'))`));
|
||||
const runtime = await mainCdp.eval(`(() => { const { app, BrowserWindow } = process.mainModule.require('electron'); const win = BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')); win.focus(); return { packaged: app.isPackaged, appPath: app.getAppPath(), profile: app.getPath('userData'), argv: process.argv, uid: process.getuid(), electron: process.versions.electron, rendererPreferences: { sandbox: win.webContents.getLastWebPreferences().sandbox, contextIsolation: win.webContents.getLastWebPreferences().contextIsolation, nodeIntegration: win.webContents.getLastWebPreferences().nodeIntegration } }; })()`);
|
||||
assert.equal(runtime.packaged, true);
|
||||
assert(runtime.appPath.endsWith('/resources/app.asar'));
|
||||
assert.equal(runtime.profile, profile);
|
||||
assert.notEqual(runtime.uid, 0);
|
||||
assert(!runtime.argv.some(arg => /no-sandbox|disable.*sandbox/.test(arg)));
|
||||
assert.equal(runtime.rendererPreferences.contextIsolation, true);
|
||||
assert.equal(runtime.rendererPreferences.nodeIntegration, false);
|
||||
// Report the stock app's sandbox:false renderer preference honestly. Do not
|
||||
// rewrite its preferences or call this a full renderer-sandbox verification.
|
||||
report.runtime = runtime;
|
||||
report.launcher = 'pass';
|
||||
await until('real vault UI', () => cdp.eval(`Boolean(document.querySelector('input[placeholder^="Find a host"]'))`));
|
||||
}
|
||||
async function capture(name) {
|
||||
const result = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
|
||||
const bytes = Buffer.from(result.data, 'base64');
|
||||
assert(bytes.length > 10000, 'Screenshot must contain a real application window');
|
||||
screenshots.set(name, bytes);
|
||||
}
|
||||
async function assertEcho(expected) {
|
||||
const sessionId = await cdp.eval(`document.querySelector('[data-tab-type="session"]').getAttribute('data-tab-id')`);
|
||||
const params = {sessionId, scopedSessionIds: [sessionId], range: 'tail', maxLines: 80};
|
||||
await until('server echo in production xterm reader', async () => {
|
||||
const result = await mainCdp.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/mcpServerBridge.cjs').dispatchBuiltinRpc('netcatty/readContext', ${JSON.stringify(params)})`);
|
||||
report.terminalRead = result;
|
||||
return result.ok === true && result.content.includes(expected);
|
||||
}, 10000);
|
||||
}
|
||||
function disconnectFixtureClients(transportLoss = false) {
|
||||
for (const client of fixture?.clients || []) {
|
||||
// ssh2 Server.Connection exposes end(), not Client.destroy(). A socket
|
||||
// destruction here is an actual transport loss, not a renderer status edit.
|
||||
if (transportLoss) client._sock?.destroy();
|
||||
else client.end();
|
||||
}
|
||||
}
|
||||
async function quit() {
|
||||
if (mainCdp) await mainCdp.eval(`process.mainModule.require('electron').app.quit()`).catch(() => {});
|
||||
if (child && !await waitForExit(child, 5000)) {
|
||||
child.kill('SIGTERM');
|
||||
if (!await waitForExit(child, 3000)) { child.kill('SIGKILL'); await waitForExit(child, 2000); }
|
||||
}
|
||||
cdp?.close(); mainCdp?.close(); cdp = mainCdp = undefined;
|
||||
}
|
||||
function observeLocalStage(stagePath, checkpointBytes) {
|
||||
const stats = fs.statSync(stagePath);
|
||||
const actual = fs.readFileSync(stagePath);
|
||||
const prefix = actual.subarray(0, checkpointBytes);
|
||||
const committedPrefixSha256 = crypto.createHash('sha256').update(prefix).digest('hex');
|
||||
const expectedPrefix = crypto.createHash('sha256').update(fixture.payload.subarray(0, checkpointBytes)).digest('hex');
|
||||
return {logicalSize: stats.size, allocatedBytes: stats.blocks * 512, committedBytesRead: prefix.length, committedPrefixSha256, committedPrefixMatchesPayload: prefix.length === checkpointBytes && committedPrefixSha256 === expectedPrefix, fullStageSha256: crypto.createHash('sha256').update(actual).digest('hex')};
|
||||
}
|
||||
function startPauseRecording() {
|
||||
report.recording = {path: 'sftp-pause-resume.mp4', startedAt: Date.now(), source: 'actual isolated Xvfb display; 5 fps; no generated frames'};
|
||||
videoChild = spawn('/usr/bin/ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', '-f', 'x11grab', '-video_size', '1440x1000', '-framerate', '5', '-i', process.env.DISPLAY, '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '30', '-t', '120', videoPath], {env: {PATH: process.env.PATH, DISPLAY: process.env.DISPLAY, XAUTHORITY: process.env.XAUTHORITY}, stdio: ['ignore', 'ignore', 'pipe']});
|
||||
videoChild.on('error', error => { report.recording.error = error.message; });
|
||||
videoChild.stderr.on('data', bytes => logs.push('Recording: ' + bytes.toString()));
|
||||
}
|
||||
async function stopPauseRecording() {
|
||||
if (!videoChild) return;
|
||||
if (videoChild.exitCode === null && videoChild.signalCode === null) { videoChild.kill('SIGINT'); if (!await waitForExit(videoChild, 3000)) videoChild.kill('SIGKILL'); }
|
||||
report.recording.endedAt = Date.now();
|
||||
report.recording.exitCode = videoChild.exitCode;
|
||||
videoChild = undefined;
|
||||
}
|
||||
async function verifySftp() {
|
||||
report.sftpPauseResume = 'incomplete';
|
||||
const sessionId = await cdp.eval(`document.querySelector('[data-tab-type="session"]').getAttribute('data-tab-id')`);
|
||||
report.stage = 'SFTP open on existing production SSH session';
|
||||
const sftpId = await cdp.eval(`window.netcatty.openSftpForSession(${JSON.stringify(sessionId)}, {reuseExactSessionOnly: true})`);
|
||||
assert(sftpId, 'Real packaged app must open SFTP on the SSH transport');
|
||||
const transferId = `qa-${crypto.randomUUID()}`;
|
||||
const targetPath = path.join(root, `download-${scenario}.bin`);
|
||||
const expectedSha256 = crypto.createHash('sha256').update(fixture.payload).digest('hex');
|
||||
const stagePath = await mainCdp.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/tempDirBridge.cjs').getTransferTempFilePath(${JSON.stringify(transferId)}, ${JSON.stringify(path.basename(targetPath))})`);
|
||||
report.sftpStagePath = stagePath;
|
||||
const options = { transferId, sourcePath: '/qa-payload.bin', targetPath, sourceType: 'sftp', targetType: 'local', sourceSftpId: sftpId, totalBytes: fixture.payload.length, resumable: true };
|
||||
await cdp.eval(`(() => { window.__qaTransfer = {events: [], done: false}; window.netcatty.onGlobalSftpTransferEvent(e => { if (e.transferId === ${JSON.stringify(transferId)}) window.__qaTransfer.events.push({...e, qaObservedAt: Date.now()}); }); window.netcatty.startStreamTransfer(${JSON.stringify(options)}).then(result => { window.__qaTransfer.result = result; window.__qaTransfer.done = true; }, error => { window.__qaTransfer.error = String(error); window.__qaTransfer.done = true; }); return true; })()`);
|
||||
const progress = () => cdp.eval(`window.__qaTransfer.events.filter(e => typeof e.transferred === 'number').at(-1)?.transferred || 0`);
|
||||
report.stage = 'SFTP bytes and native progress';
|
||||
await until('real SFTP bytes and native progress', async () => fixture.sftpStats.bytesSent > 262144 && await progress() > 131072, 30000);
|
||||
await clickElement(cdp, 'button[aria-label="File Transfers"]');
|
||||
await pause(200);
|
||||
await capture('03-sftp-transferring.png');
|
||||
const sharedChannel = fixture.protocol.channels[0].id;
|
||||
const isolated = fixture.protocol.opens.filter(open => open.channelId !== sharedChannel && !open.closedAt && open.path === '/qa-payload.bin');
|
||||
assert.equal(isolated.length, 1, 'Harness must identify one active isolated download handle');
|
||||
const transferHandle = isolated[0].handle;
|
||||
report.sftpHandleClassification = {sharedVerificationChannel: sharedChannel, isolatedDownload: {...isolated[0]}, basis: 'official concurrent-isolated download uses an isolated subsystem; fingerprint ranges use the shared browse subsystem; inspect sftp-protocol.json for every OPEN/READ/CLOSE'};
|
||||
report.stage = 'SFTP pause';
|
||||
const paused = await cdp.eval(`window.netcatty.pauseTransfer(${JSON.stringify(transferId)})`);
|
||||
const pauseAcknowledgedAt = Date.now();
|
||||
assert.equal(paused.success, true, paused.reason);
|
||||
await until('native paused lifecycle event', () => cdp.eval(`window.__qaTransfer.events.some(e => e.type === 'paused')`));
|
||||
report.sftpControl = {transferId, pauseAcknowledgedAt, paused};
|
||||
const allowedRanges = new Set(fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt <= pauseAcknowledgedAt).map(read => read.logicalRangeStart));
|
||||
report.sftpControl.alreadyStartedDownloadRanges = [...allowedRanges].sort((a,b) => a-b);
|
||||
report.sftpControl.inFlightDownloadReadsAtAcknowledgement = fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt <= pauseAcknowledgedAt && (!read.repliedAt || read.repliedAt > pauseAcknowledgedAt)).map(read => read.sequence);
|
||||
report.sftpPauseDrain = {startedAt: Date.now(), initial: {...fixture.sftpStats}, samples: []};
|
||||
// A transient zero in-flight count is not quiescence: the production runtime
|
||||
// may start checkpoint fingerprint reads asynchronously after acknowledging
|
||||
// pause. Keep the complete settling timeline and require sustained stability.
|
||||
let stable = [];
|
||||
await until('sustained actual SFTP bytes and native progress stop', async () => {
|
||||
const native = await cdp.eval(`({done: window.__qaTransfer.done, completed: window.__qaTransfer.events.some(e => e.type === 'completed'), checkpoint: window.__qaTransfer.events.filter(e => typeof e.checkpointBytes === 'number').at(-1)?.checkpointBytes})`);
|
||||
assert.equal(native.done, false, 'Transfer resolved before explicit resume');
|
||||
assert.equal(native.completed, false, 'Transfer completed before explicit resume');
|
||||
const checkpointBytes = native.checkpoint ?? paused.checkpointBytes ?? 0;
|
||||
const sample = {at: Date.now(), serverBytes: fixture.sftpStats.bytesSent, activeReads: fixture.sftpStats.activeReads, progressBytes: await progress(), checkpointBytes, done: native.done, local: observeLocalStage(stagePath, checkpointBytes)};
|
||||
report.sftpPauseDrain.samples.push(sample);
|
||||
const previous = stable.at(-1);
|
||||
if (previous && (previous.serverBytes !== sample.serverBytes || previous.progressBytes !== sample.progressBytes || previous.checkpointBytes !== sample.checkpointBytes || previous.local.fullStageSha256 !== sample.local.fullStageSha256 || sample.activeReads !== 0)) stable = [];
|
||||
stable.push(sample);
|
||||
if (stable.length < 6) { await pause(500); return false; }
|
||||
return sample.activeReads === 0 && sample.at - stable[0].at >= 2500;
|
||||
}, 60000);
|
||||
const samples = stable;
|
||||
report.sftpPauseDrain.endedAt = Date.now();
|
||||
report.sftpPauseDrain.final = {...fixture.sftpStats};
|
||||
report.sftpPauseSamples = samples;
|
||||
assert(samples[0].progressBytes > 0 && samples[0].progressBytes < fixture.payload.length, 'Pause must happen mid-transfer');
|
||||
assert(samples.every(s => s.serverBytes === samples[0].serverBytes), 'Actual SFTP server bytes changed in stable pause window');
|
||||
assert(samples.every(s => s.progressBytes === samples[0].progressBytes), 'Native progress changed in stable pause window');
|
||||
const unexpectedRangeStarts = fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt > pauseAcknowledgedAt && !allowedRanges.has(read.logicalRangeStart));
|
||||
report.sftpRangePauseAssertions = {transferHandle, logicalChunkBytes: 32768, noNewLogicalDownloadRangeStarts: unexpectedRangeStarts.length === 0, unexpectedRangeStarts, noCompleteBeforeResume: true};
|
||||
assert.equal(unexpectedRangeStarts.length, 0, 'New logical download ranges started after pause acknowledgement');
|
||||
assert(samples.every(sample => sample.local.committedPrefixMatchesPayload), 'Committed checkpoint bytes do not match source payload');
|
||||
assert(samples.every(sample => sample.local.fullStageSha256 === samples[0].local.fullStageSha256), 'Local file contents changed during stable pause');
|
||||
assert(samples.every(sample => sample.checkpointBytes === samples[0].checkpointBytes), 'Committed checkpoint changed during stable pause');
|
||||
await capture('04-sftp-paused.png');
|
||||
startPauseRecording();
|
||||
await pause(2000);
|
||||
report.stage = 'SFTP resume';
|
||||
const finalPausedNative = await cdp.eval(`({done: window.__qaTransfer.done, completed: window.__qaTransfer.events.some(e => e.type === 'completed')})`);
|
||||
assert.equal(finalPausedNative.done, false, 'Transfer resolved before resume request');
|
||||
assert.equal(finalPausedNative.completed, false, 'Transfer completed before resume request');
|
||||
report.sftpControl.resumeRequestedAt = Date.now();
|
||||
const lateNewRanges = fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt > pauseAcknowledgedAt && read.receivedAt < report.sftpControl.resumeRequestedAt && !allowedRanges.has(read.logicalRangeStart));
|
||||
const newIsolatedHandles = fixture.protocol.opens.filter(open => open.channelId !== sharedChannel && open.handle !== transferHandle && open.openedAt > pauseAcknowledgedAt && open.openedAt < report.sftpControl.resumeRequestedAt);
|
||||
report.sftpRangePauseAssertions.unexpectedRangeStarts = lateNewRanges;
|
||||
report.sftpRangePauseAssertions.unclassifiedNewIsolatedHandles = newIsolatedHandles;
|
||||
assert.equal(lateNewRanges.length, 0, 'New logical download range started before explicit resume');
|
||||
assert.equal(newIsolatedHandles.length, 0, 'Unclassified isolated file handle opened while paused');
|
||||
const resumed = await cdp.eval(`window.netcatty.resumeTransfer(${JSON.stringify(transferId)})`, 60000);
|
||||
report.sftpControl.resumed = resumed;
|
||||
assert.equal(resumed.success, true, resumed.reason);
|
||||
await until('server and progress resume', async () => fixture.sftpStats.bytesSent > samples[0].serverBytes && await progress() > samples[0].progressBytes, 15000);
|
||||
await capture('05-sftp-resumed.png');
|
||||
await pause(1500);
|
||||
await stopPauseRecording();
|
||||
await until('native transfer completes', () => cdp.eval(`window.__qaTransfer.done`), 90000);
|
||||
const result = await cdp.eval(`window.__qaTransfer.result`);
|
||||
assert(result && !result.error && !result.cancelled, JSON.stringify(result));
|
||||
const actualSha256 = crypto.createHash('sha256').update(fs.readFileSync(targetPath)).digest('hex');
|
||||
assert.equal(fs.statSync(targetPath).size, fixture.payload.length);
|
||||
assert.equal(actualSha256, expectedSha256);
|
||||
report.sftpPauseResume = 'pass';
|
||||
report.sftp = { invocation: 'production preload API -> packaged native transfer runtime, actual loopback SSH2 SFTP; no substituted bridge', transferId, bytes: fixture.payload.length, paused, resumed, pauseSamples: samples, finalServer: fixture.sftpStats, expectedSha256, actualSha256, events: await cdp.eval(`window.__qaTransfer.events`) };
|
||||
await capture('06-sftp-completed.png');
|
||||
}
|
||||
async function verifyHostFilters() {
|
||||
report.hostFilters = {status: 'incomplete', cases: []};
|
||||
const hosts = [
|
||||
{id: 'web', label: 'QA WEB', hostname: '127.0.0.1', username: 'deploy', group: 'prod/web', tags: ['Nginx'], os: 'linux'},
|
||||
{id: 'db', label: 'QA DB', hostname: '127.0.0.2', username: 'root', group: 'prod/db', tags: ['postgres'], os: 'linux'},
|
||||
{id: 'old', label: 'QA OLD', hostname: '127.0.0.3', username: 'root', group: 'production-old', tags: [], os: 'linux'},
|
||||
{id: 'prod-root', label: 'QA PROD ROOT', hostname: '127.0.0.4', username: 'ops', group: 'prod', tags: [], os: 'linux'},
|
||||
{id: 'ungrouped', label: 'QA UNGROUPED', hostname: '127.0.0.5', username: 'ops', tags: [], os: 'linux'},
|
||||
];
|
||||
await cdp.eval(`localStorage.setItem('netcatty_hosts_v1', ${JSON.stringify(JSON.stringify(hosts))})`);
|
||||
await cdp.send('Page.reload');
|
||||
await until('synthetic filter host vault loaded', () => cdp.eval(`document.body.innerText.includes('QA UNGROUPED')`));
|
||||
await capture('02-host-filter-vault.png');
|
||||
const all = hosts.map(h => h.id).sort();
|
||||
const cases = [
|
||||
[{}, all],
|
||||
[{query: ' ', group: ''}, all],
|
||||
[{query: 123, group: null}, all],
|
||||
[{query: 'WEB nginx'}, ['web']],
|
||||
[{query: 'root DB'}, ['db']],
|
||||
[{query: 'production'}, []],
|
||||
[{group: 'prod'}, ['db', 'prod-root', 'web']],
|
||||
[{group: 'prod/web'}, ['web']],
|
||||
[{group: ' prod/ '}, ['db', 'prod-root', 'web']],
|
||||
[{group: 'PROD'}, []],
|
||||
[{group: 'prod', query: 'postgres'}, ['db']],
|
||||
];
|
||||
for (const [params, expected] of cases) {
|
||||
const result = await mainCdp.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/mcpServerBridge.cjs').dispatchBuiltinRpc('public/vault/hosts/list', ${JSON.stringify(params)})`);
|
||||
assert.equal(result.ok, true, JSON.stringify(result));
|
||||
const ids = result.hosts.map(h => h.id).sort();
|
||||
report.hostFilters.cases.push({params, ids, expected});
|
||||
assert.deepEqual(ids, expected);
|
||||
assert(result.hosts.every(h => !('password' in h) && !('privateKey' in h)));
|
||||
}
|
||||
report.hostFilters.status = 'pass';
|
||||
report.hostFilters.path = 'real packaged public/vault/hosts/list dispatcher -> production renderer vault bridge';
|
||||
await capture('03-host-filter-cases-completed.png');
|
||||
}
|
||||
function saveEvidence(print) {
|
||||
if (fixture && scenario === 'sftp') {
|
||||
const pauseAt = report.sftpControl?.pauseAcknowledgedAt;
|
||||
const resumeAt = report.sftpControl?.resumeRequestedAt || Infinity;
|
||||
report.sftpProtocolSummary = fixture.protocol.opens.map(open => {
|
||||
const reads = fixture.protocol.reads.filter(read => read.handle === open.handle);
|
||||
return {...open, role: open.handle === report.sftpHandleClassification?.isolatedDownload?.handle ? 'isolated payload download' : open.channelId === report.sftpHandleClassification?.sharedVerificationChannel ? 'shared browse / source verification' : 'unclassified', readCount: reads.length, repliedBytes: reads.reduce((n, read) => n + (read.replyBytes || 0), 0), readsReceivedWhilePaused: reads.filter(read => read.receivedAt > pauseAt && read.receivedAt < resumeAt).length, repliesWhilePaused: reads.filter(read => read.repliedAt > pauseAt && read.repliedAt < resumeAt).length};
|
||||
});
|
||||
}
|
||||
const output = logs.join('');
|
||||
const publicText = output + JSON.stringify(report) + (fixture ? JSON.stringify(fixture.protocol) : '');
|
||||
const sensitive = publicText.includes(loginPassword) || /-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]+)|Authorization:\s*Bearer\s+\S+/i.test(publicText);
|
||||
report.stderrReview = sensitive ? 'blocked: sensitive output; logs and screenshots withheld' : 'pass: ephemeral password, private key, GitHub credential and bearer-token checks';
|
||||
if (sensitive) {
|
||||
process.exitCode = 1; delete report.failure; delete report.sshDiagnostics;
|
||||
for (const name of ['electron-output.log', 'sftp-protocol.json', 'sftp-pause-resume.mp4', ...screenshots.keys()]) fs.rmSync(path.join(evidence, name), {force: true});
|
||||
} else {
|
||||
fs.writeFileSync(path.join(evidence, 'electron-output.log'), output);
|
||||
if (fixture && scenario === 'sftp') fs.writeFileSync(path.join(evidence, 'sftp-protocol.json'), JSON.stringify(fixture.protocol, null, 2));
|
||||
if (fs.existsSync(videoPath) && fs.statSync(videoPath).size > 1000) fs.copyFileSync(videoPath, path.join(evidence, 'sftp-pause-resume.mp4'));
|
||||
for (const [name, bytes] of screenshots) fs.writeFileSync(path.join(evidence, name), bytes);
|
||||
if (print) console.log('Reviewed official Electron stdout/stderr:\n' + output);
|
||||
}
|
||||
report.coverage = 'Independent scenario: only this report and candidate SHA count; other scenario reports must be evaluated separately';
|
||||
fs.writeFileSync(path.join(evidence, 'assertions.json'), JSON.stringify(report, null, 2));
|
||||
if (print) console.log(JSON.stringify(report, null, 2));
|
||||
}
|
||||
async function verifyClipboard() {
|
||||
report.clipboard = {status: 'incomplete'};
|
||||
await terminalLine(cdp, mainCdp, 'QA_CLIPBOARD_ONLY');
|
||||
await until('clipboard scenario server receive', () => fixture.sessions.some(s => s.commands.includes('QA_CLIPBOARD_ONLY')));
|
||||
await assertEcho('ran: QA_CLIPBOARD_ONLY');
|
||||
async function menu(label) {
|
||||
await clickElement(cdp, '.xterm', 0, 'right');
|
||||
const point = await until(`terminal menu ${label}`, () => cdp.eval(`(() => { const e = [...document.querySelectorAll('[role="menuitem"]')].find(e => e.textContent.trim().startsWith(${JSON.stringify(label)})); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`));
|
||||
await clickPoint(cdp, point);
|
||||
await pause(200);
|
||||
}
|
||||
await menu('Select All'); await menu('Copy');
|
||||
await until('clipboard receives real terminal echo', async () => {
|
||||
const actual = await mainCdp.eval(`process.mainModule.require('electron').clipboard.readText()`);
|
||||
report.clipboard.observed = actual;
|
||||
return actual.includes('ran: QA_CLIPBOARD_ONLY');
|
||||
}, 5000);
|
||||
report.clipboard.status = 'pass';
|
||||
await capture('03-independent-clipboard.png');
|
||||
}
|
||||
async function run() {
|
||||
assert.notEqual(process.getuid(), 0, 'QA must run as a non-root user');
|
||||
assert(fs.existsSync(executable), `Official executable missing: ${executable}`);
|
||||
fs.mkdirSync(evidence, { recursive: true });
|
||||
assert(!fs.existsSync(profile), 'QA profile must start clean');
|
||||
watchdog = setTimeout(() => { fs.writeFileSync(path.join(evidence, 'watchdog.json'), JSON.stringify({candidate: pinned.sha, scenario, failure: 'Scenario exceeded 180 seconds', stage: report.stage || 'desktop'})); child?.kill('SIGKILL'); process.exit(1); }, 180000);
|
||||
try {
|
||||
await launch();
|
||||
await capture('01-official-launch.png');
|
||||
if (scenario === 'persistence') {
|
||||
const seed = { id: 'qa-persisted-host', label: 'QA persisted loopback host', hostname: '127.0.0.1', username: 'fixture', port: 22222, protocol: 'ssh', tags: ['qa-only'], os: 'linux' };
|
||||
// Seed synthetic pre-existing data through real Chromium storage. The
|
||||
// acceptance check is a full process restart and visible real vault data.
|
||||
await cdp.eval(`localStorage.setItem('netcatty_hosts_v1', ${JSON.stringify(JSON.stringify([seed]))})`);
|
||||
await cdp.send('Page.reload');
|
||||
await until('seeded host visible before quit', () => cdp.eval(`document.body.innerText.includes('QA persisted loopback host')`));
|
||||
await capture('02-seeded-data.png');
|
||||
await quit();
|
||||
await launch();
|
||||
await until('same profile data visible after restart', () => cdp.eval(`document.body.innerText.includes('QA persisted loopback host')`));
|
||||
assert.equal(await cdp.eval(`JSON.parse(localStorage.getItem('netcatty_hosts_v1'))[0].id`), seed.id);
|
||||
report.persistence = 'pass: synthetic saved host visible before and after graceful quit/relaunch of same isolated profile';
|
||||
await capture('03-persisted-after-restart.png');
|
||||
|
||||
return;
|
||||
}
|
||||
if (scenario === 'host-filter') { await verifyHostFilters(); return; }
|
||||
fixture = startSshFixture();
|
||||
await new Promise((resolve, reject) => { fixture.server.once('error', reject); fixture.server.listen(0, '127.0.0.1', resolve); });
|
||||
const sshPort = fixture.server.address().port;
|
||||
await clickElement(cdp, 'input[placeholder^="Find a host"]');
|
||||
await insertText(mainCdp, `ssh -p ${sshPort} fixture@127.0.0.1`);
|
||||
await clickText(cdp, 'Connect');
|
||||
await until('protocol wizard', () => cdp.eval(`document.body.innerText.includes('Choose protocol')`));
|
||||
await clickText(cdp, 'Continue');
|
||||
await until('username wizard', () => cdp.eval(`Boolean(document.querySelector('input[placeholder="root"]'))`));
|
||||
await clickText(cdp, 'Continue');
|
||||
await until('password wizard', () => cdp.eval(`Boolean(document.querySelector('input[placeholder="Enter password"]'))`));
|
||||
await clickElement(cdp, 'input[placeholder="Enter password"]');
|
||||
await insertText(mainCdp, loginPassword);
|
||||
await clickText(cdp, 'Continue');
|
||||
await until('real host-key confirmation', () => cdp.eval(`document.body.innerText.includes('Confirm this host key')`));
|
||||
await clickText(cdp, 'Add and continue');
|
||||
await until('first real SSH shell', () => fixture.sessions.filter(s => s.ready).length === 1);
|
||||
await pause(700);
|
||||
await capture('02-connected-shell.png');
|
||||
if (scenario === 'sftp') { await verifySftp(); return; }
|
||||
if (scenario === 'clipboard') { await verifyClipboard(); return; }
|
||||
report.sshReconnect = 'incomplete';
|
||||
await terminalLine(cdp, mainCdp, 'QA_BEFORE_DISCONNECT');
|
||||
await until('first server received command', () => fixture.sessions.some(s => s.commands.includes('QA_BEFORE_DISCONNECT')));
|
||||
await assertEcho('ran: QA_BEFORE_DISCONNECT');
|
||||
const originalTabs = await cdp.eval(`[...document.querySelectorAll('[data-tab-type="session"]')].map(e => e.getAttribute('data-tab-id'))`);
|
||||
assert.equal(originalTabs.length, 1);
|
||||
assert(originalTabs[0], 'Stable original tab ID required');
|
||||
disconnectFixtureClients(true);
|
||||
await capture('03-real-ssh-transport-lost.png');
|
||||
await until('transport closed and reconnect path observable', async () => fixture.sessions[0].closedAt && (fixture.sessions.filter(s => s.ready).length >= 2 || await cdp.eval(`Boolean(document.querySelector('[data-terminal-disconnected-dialog="true"]'))`)));
|
||||
if (fixture.sessions.filter(s => s.ready).length < 2) {
|
||||
report.reconnectMode = 'UI Enter';
|
||||
await capture('04-real-ssh-disconnected.png');
|
||||
await key(mainCdp, 'Enter'); await key(mainCdp, 'Enter', 'keyUp');
|
||||
} else report.reconnectMode = 'production automatic reconnect after real transport loss';
|
||||
await until('second real SSH shell', () => fixture.sessions.filter(s => s.ready).length === 2, 20000);
|
||||
await pause(700);
|
||||
await terminalLine(cdp, mainCdp, 'QA_AFTER_RECONNECT');
|
||||
await until('second server received command', () => fixture.sessions.filter(s => s.ready)[1].commands.includes('QA_AFTER_RECONNECT'));
|
||||
await assertEcho('ran: QA_AFTER_RECONNECT');
|
||||
assert.deepEqual(await cdp.eval(`[...document.querySelectorAll('[data-tab-type="session"]')].map(e => e.getAttribute('data-tab-id'))`), originalTabs);
|
||||
report.sshReconnect = 'pass';
|
||||
report.ssh = { transport: 'SSH2 over loopback TCP; server destroys its socket, production app reconnects original tab', shellConnections: fixture.sessions.filter(s => s.ready).length, originalTabs, commands: fixture.sessions.filter(s => s.ready).map(s => s.commands.filter(command => command.startsWith('QA_'))), connections: fixture.sessions.filter(s => s.ready).map(({readyAt, closedAt}) => ({readyAt, closedAt})) };
|
||||
await capture('05-real-ssh-reconnected.png');
|
||||
} catch (error) {
|
||||
report.failure = error.message;
|
||||
report.failureCategory = 'Unresolved assertion; use focus and server receive diagnostics before assigning a product regression';
|
||||
if (fixture) report.sftpServerAtFailure = {...fixture.sftpStats};
|
||||
if (scenario === 'sftp' && cdp) report.sftpNativeAtFailure = await cdp.eval(`window.__qaTransfer`).catch(() => null);
|
||||
if (fixture) report.sshDiagnostics = fixture.sessions.map(({ready, receivedHex, commands, sent}) => ({ready, receivedHex, commands, sent}));
|
||||
if (report.launcher === 'not_run') report.launcher = 'fail';
|
||||
await capture('failure-real-application.png').catch(() => {});
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
// Persist tested assertions and reviewed evidence before teardown. Cleanup
|
||||
// must not erase a functional result or mask the original failure.
|
||||
await stopPauseRecording();
|
||||
saveEvidence(false);
|
||||
try {
|
||||
await quit();
|
||||
if (fixture) {
|
||||
disconnectFixtureClients();
|
||||
await Promise.race([new Promise(resolve => fixture.server.close(resolve)), pause(5000)]);
|
||||
}
|
||||
fs.rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 });
|
||||
} catch (error) { report.cleanupWarning = error.code || error.message; }
|
||||
clearTimeout(watchdog);
|
||||
saveEvidence(true);
|
||||
}
|
||||
}
|
||||
run().catch(error => { console.error(error.message); process.exitCode = 1; });
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"name": "netcatty-official-linux-qa",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "netcatty-official-linux-qa",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"ssh2": "1.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1": {
|
||||
"version": "0.2.6",
|
||||
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
|
||||
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": "~2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bcrypt-pbkdf": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
|
||||
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tweetnacl": "^0.14.3"
|
||||
}
|
||||
},
|
||||
"node_modules/buildcheck": {
|
||||
"version": "0.0.7",
|
||||
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
|
||||
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cpu-features": {
|
||||
"version": "0.0.10",
|
||||
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
|
||||
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
|
||||
"hasInstallScript": true,
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"buildcheck": "~0.0.6",
|
||||
"nan": "^2.19.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nan": {
|
||||
"version": "2.30.0",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz",
|
||||
"integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ssh2": {
|
||||
"version": "1.17.0",
|
||||
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
|
||||
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"asn1": "^0.2.6",
|
||||
"bcrypt-pbkdf": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.16.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"cpu-features": "~0.0.10",
|
||||
"nan": "^2.23.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tweetnacl": {
|
||||
"version": "0.14.5",
|
||||
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
|
||||
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
|
||||
"license": "Unlicense"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "netcatty-official-linux-qa",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"description": "QA harness dependencies only; never bundled in Netcatty",
|
||||
"dependencies": { "ssh2": "1.17.0" }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// The GitHub token exists only in this downloader process, never in Electron.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { Readable } = require('node:stream');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const pinned = require(path.resolve(__dirname, process.env.QA_CANDIDATE || 'candidate.json'));
|
||||
async function main() {
|
||||
assert(process.env.GH_TOKEN, 'Downloader needs actions:read token');
|
||||
const root = path.resolve(process.env.QA_ROOT);
|
||||
fs.mkdirSync(path.join(root, 'evidence'), { recursive: true });
|
||||
const base = `https://api.github.com/repos/${pinned.repository}`;
|
||||
const headers = { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
async function api(route) {
|
||||
const response = await fetch(base + route, { headers });
|
||||
assert(response.ok, `GitHub metadata HTTP ${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
const run = await api(`/actions/runs/${pinned.run}`);
|
||||
assert.equal(run.head_sha, pinned.sha);
|
||||
assert.equal(run.repository.id, pinned.repositoryId);
|
||||
assert.equal(run.head_repository.id, pinned.repositoryId);
|
||||
assert.equal(run.head_branch, 'main');
|
||||
assert.equal(run.event, 'push');
|
||||
assert.equal(run.path, '.github/workflows/build.yml');
|
||||
const jobs = await api(`/actions/runs/${pinned.run}/jobs?per_page=100`);
|
||||
const job = jobs.jobs.find(item => item.name === 'build-linux-x64');
|
||||
assert.equal(job?.conclusion, 'success', 'Official Linux job must succeed');
|
||||
const artifact = await api(`/actions/artifacts/${pinned.artifact}`);
|
||||
assert.equal(artifact.name, pinned.name);
|
||||
assert.equal(artifact.expired, false);
|
||||
assert.equal(artifact.workflow_run.id, pinned.run);
|
||||
assert.equal(artifact.workflow_run.head_sha, pinned.sha);
|
||||
assert.equal(artifact.workflow_run.head_repository_id, pinned.repositoryId);
|
||||
assert.equal(artifact.digest, `sha256:${pinned.zipSha256}`);
|
||||
const response = await fetch(`${base}/actions/artifacts/${pinned.artifact}/zip`, { headers, redirect: 'manual' });
|
||||
assert.equal(response.status, 302);
|
||||
const location = new URL(response.headers.get('location'));
|
||||
assert.equal(location.protocol, 'https:');
|
||||
// Deliberately omit authorization from the redirected blob request.
|
||||
const archive = await fetch(location);
|
||||
assert(archive.ok, `Artifact download HTTP ${archive.status}`);
|
||||
const zip = path.join(root, 'official.zip');
|
||||
await pipeline(Readable.fromWeb(archive.body), fs.createWriteStream(zip));
|
||||
async function digest(file) {
|
||||
const hash = crypto.createHash('sha256');
|
||||
for await (const bytes of fs.createReadStream(file)) hash.update(bytes);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
assert.equal(await digest(zip), pinned.zipSha256);
|
||||
// Extract just the named deb, without trusting archive paths or executing postinst.
|
||||
execFileSync('python3', ['-c', 'import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); n=sys.argv[2]; assert z.namelist().count(n)==1; open(sys.argv[3],"wb").write(z.read(n))', zip, pinned.deb, path.join(root, pinned.deb)]);
|
||||
const deb = path.join(root, pinned.deb);
|
||||
assert.equal(await digest(deb), pinned.debSha256);
|
||||
assert.equal(execFileSync('dpkg-deb', ['-f', deb, 'Architecture'], { encoding: 'utf8' }).trim(), 'amd64');
|
||||
execFileSync('dpkg-deb', ['-x', deb, path.join(root, 'package')]);
|
||||
fs.writeFileSync(path.join(root, 'evidence/provenance.json'), JSON.stringify({ ...pinned, officialLinuxJob: job.id, officialRunStatus: run.status, mode: 'rootless deb extraction; installer scripts not executed', verifiedAt: new Date().toISOString() }, null, 2));
|
||||
console.log(`Verified official ${pinned.sha}, run ${pinned.run}, artifact ${pinned.artifact}, deb SHA-256 ${pinned.debSha256}`);
|
||||
}
|
||||
main().catch(error => { console.error(error.message); process.exitCode = 1; });
|
||||
@@ -0,0 +1,47 @@
|
||||
# Official macOS candidate smoke (QA-only Draft #4299)
|
||||
|
||||
Independent standard macos-26 Apple Silicon and macos-15-intel jobs pin official
|
||||
main 9d4e90b / successful push run 44903060405 / artifact 14706977005. Only the
|
||||
metadata/downloader step receives the built-in Actions read token. It verifies
|
||||
repository IDs, head, branch/event/workflow, successful macOS job, exact artifact
|
||||
ID/name/size/expiry and archive SHA-256, then extracts only the matching DMG.
|
||||
|
||||
Stock hdiutil verifies DMG integrity and mounts it read-only. ditto copies the
|
||||
original Netcatty.app into a temporary runner-owned Applications directory,
|
||||
preserving bundle metadata. The copied app must have the native Mach-O slice,
|
||||
strict valid Developer ID signature, hardened runtime, a valid stapled APP
|
||||
notarization ticket, and accepted Notarized Developer ID Gatekeeper assessment.
|
||||
Outer DMG signature/stapler results are recorded separately and are never
|
||||
presented as APP notarization. No OS/security/xattr/quarantine/privacy settings
|
||||
are modified; an assessment preventing launch stops the GUI step.
|
||||
|
||||
The unmodified installed app executable launches its real native GUI with a
|
||||
fresh synthetic profile and an allowlisted process environment retaining the
|
||||
ephemeral VM's standard HOME/TMPDIR for ordinary macOS services. Actual app
|
||||
version/path/origin/profile/architecture and stock web preferences are recorded.
|
||||
Renderer automation and screenshots use loopback CDP/native capture, without
|
||||
accessibility or screen-recording permission grants. No browser/UI fixture or
|
||||
checkout-sourced application code replaces the official package.
|
||||
|
||||
A generated-credential ssh2 server listens only on 127.0.0.1. Normal Netcatty
|
||||
Quick Connect GUI accepts that test host key in the isolated profile and opens a
|
||||
real encrypted PTY/shell. Native xterm input sends a unique harmless printf
|
||||
token. Both the server receipt/acknowledgement event and the production live
|
||||
terminal reader must observe the explicit server acknowledgement. Screenshots
|
||||
capture the actual startup, connection and terminal output. No LAN, external
|
||||
SSH account, model, business data or public listener is used.
|
||||
|
||||
Evidence retained for three days: provenance.json, verification.json (including
|
||||
exact OS command outputs and package identities), assertions.json,
|
||||
application-output.log, and arch-prefixed native PNGs: 00-native-launch,
|
||||
01-first-launch, 02-real-ssh-connected, 03-real-ssh-roundtrip, or failure-native-
|
||||
application when possible. Assertions and reviewed images are saved before
|
||||
cleanup; credentials/private keys/tokens in output withhold logs/images and fail.
|
||||
Raw profiles and generated private keys are never uploaded.
|
||||
|
||||
This covers copy installation and first native executable GUI launch after APP
|
||||
Gatekeeper assessment, not Finder quarantine ingestion, physical user devices,
|
||||
LAN/privacy approval, automatic updating or a final merged revision. The stock
|
||||
renderer sandbox:false preference is recorded honestly, never changed. Final
|
||||
official revision replay requires a separately supplied merge SHA and artifact
|
||||
IDs; the pinned candidate is not silently replaced.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"repository": "binaricat/Netcatty",
|
||||
"repositoryId": 1111357457,
|
||||
"sha": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
|
||||
"run": 44903060405,
|
||||
"buildJob": 136843406473,
|
||||
"artifact": 14706977005,
|
||||
"name": "netcatty-macos",
|
||||
"archiveBytes": 594675248,
|
||||
"zipSha256": "9c2484a19db5fc74d201bbe8dbdd11101a6a36360a99743a4fe2d90a48369ef1",
|
||||
"version": "0.0.0-sha-9d4e90b",
|
||||
"bundleId": "com.netcatty.app",
|
||||
"dmgs": {
|
||||
"arm64": "Netcatty-0.0.0-sha-9d4e90b-mac-arm64.dmg",
|
||||
"x64": "Netcatty-0.0.0-sha-9d4e90b-mac-x64.dmg"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
// Real, verified installed app GUI + real loopback SSH2; no component fixtures.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const net = require('node:net');
|
||||
const vm = require('node:vm');
|
||||
const { spawn, execFileSync } = require('node:child_process');
|
||||
const { chromium } = require('playwright-core');
|
||||
const { Server } = require('ssh2');
|
||||
const pinned = require('./candidate.json');
|
||||
const arch = process.env.QA_ARCH, root = path.resolve(process.env.QA_ROOT);
|
||||
const evidence = path.join(root, 'evidence'), profile = path.join(root, 'profile');
|
||||
const executable = path.join(root, 'Applications/Netcatty.app/Contents/MacOS/Netcatty');
|
||||
const loginPassword = crypto.randomBytes(24).toString('hex');
|
||||
const token = `QA_MAC_${arch}_${crypto.randomUUID().replaceAll('-', '')}`;
|
||||
const commandText = `printf ${token}`;
|
||||
const acknowledgement = `QA_MAC_ACK:${token}`;
|
||||
const report = { candidate: pinned.sha, arch, qaHead: process.env.QA_HEAD_SHA, runner: process.env.QA_RUNNER, firstLaunch: 'not_run', ssh: 'not_run', screenshots: [], fixtureEvents: [], scope: 'First real native GUI launch of the copied official signed/notarized APP, then actual SSH2 loopback shell roundtrip. Not Finder quarantine, LAN, updater, personal-device or final-merged-revision coverage.', security: 'Stock Electron and OS protections. No sandbox/Gatekeeper/quarantine/SIP or privacy-permission changes.' };
|
||||
const logs = [], images = new Map(), clients = new Set();
|
||||
let app, browser, page, inspector, server, watchdog, finishing;
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
function stage(name) { report.stage = name; console.log(`QA_MAC_STAGE ${name}`); }
|
||||
async function until(label, check, timeout = 20000) {
|
||||
const end = Date.now() + timeout; let last;
|
||||
while (Date.now() < end) {
|
||||
try { const value = await check(); if (value) return value; } catch (error) { if (error instanceof SyntaxError) throw error; last = error; }
|
||||
await sleep(150);
|
||||
}
|
||||
throw new Error(`Timed out: ${label}${last ? `: ${last.message}` : ''}`);
|
||||
}
|
||||
async function freePort() { const s = net.createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }
|
||||
function environment() {
|
||||
const env = {};
|
||||
for (const key of ['PATH', 'HOME', 'TMPDIR', 'USER', 'LOGNAME', 'SHELL', '__CF_USER_TEXT_ENCODING', 'XPC_FLAGS', 'XPC_SERVICE_NAME', 'COMMAND_MODE']) if (process.env[key]) env[key] = process.env[key];
|
||||
Object.assign(env, { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' });
|
||||
// Preserve the ephemeral VM's normal OS home/bootstrap and temporary paths.
|
||||
// Only app userData is isolated; never substitute/disable the OS keychain.
|
||||
report.environment = { home: env.HOME, tmpdir: env.TMPDIR, isolatedAppProfile: profile, inheritedKeys: Object.keys(env) };
|
||||
return env;
|
||||
}
|
||||
class Inspector {
|
||||
constructor(url) {
|
||||
this.ws = new WebSocket(url); this.next = 0; this.pending = new Map();
|
||||
this.ws.addEventListener('message', event => { const m = JSON.parse(event.data), item = this.pending.get(m.id); if (!item) return; this.pending.delete(m.id); m.error ? item.reject(new Error(m.error.message)) : item.resolve(m.result); });
|
||||
}
|
||||
async connect() { await new Promise((resolve, reject) => { this.ws.addEventListener('open', resolve, { once: true }); this.ws.addEventListener('error', reject, { once: true }); }); }
|
||||
async eval(expression) {
|
||||
if (typeof expression === 'function') expression = `(${expression.toString()})()`;
|
||||
new vm.Script(expression);
|
||||
const id = ++this.next;
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('Native inspector timeout')); }, 12000);
|
||||
this.pending.set(id, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
|
||||
this.ws.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, returnByValue: true, awaitPromise: true } }));
|
||||
});
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
return result.result.value;
|
||||
}
|
||||
close() { this.ws.close(); }
|
||||
}
|
||||
function keepImage(name, bytes) {
|
||||
assert(bytes.length > 10000, 'Capture must contain an actual rendered application');
|
||||
assert.equal(bytes.subarray(1, 4).toString(), 'PNG');
|
||||
images.set(name, bytes);
|
||||
report.screenshots.push({ name, bytes: bytes.length, width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), sha256: crypto.createHash('sha256').update(bytes).digest('hex'), source: 'Actual installed native renderer capture' });
|
||||
}
|
||||
async function capture(name) {
|
||||
if (inspector) {
|
||||
const encoded = await inspector.eval(async () => {
|
||||
const e = process.mainModule.require('electron');
|
||||
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html'));
|
||||
return w ? (await w.webContents.capturePage()).toPNG().toString('base64') : null;
|
||||
});
|
||||
if (encoded) keepImage(`${arch}-${name}.png`, Buffer.from(encoded, 'base64'));
|
||||
} else if (page && !page.isClosed()) keepImage(`${arch}-${name}.png`, await page.screenshot({ timeout: 10000 }));
|
||||
}
|
||||
function event(kind, detail = {}) { report.fixtureEvents.push({ at: new Date().toISOString(), kind, ...detail }); }
|
||||
async function startSsh() {
|
||||
const { privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, publicKeyEncoding: { type: 'spki', format: 'pem' } });
|
||||
server = new Server({ hostKeys: [privateKey] }, client => {
|
||||
clients.add(client); const connection = report.fixtureEvents.filter(e => e.kind === 'tcp').length + 1;
|
||||
event('tcp', { connection, remoteAddress: client._sock?.remoteAddress });
|
||||
client.on('error', error => event('transport_error', { connection, message: error.message }));
|
||||
client.on('close', () => { clients.delete(client); event('closed', { connection }); });
|
||||
client.on('authentication', ctx => { if (ctx.method === 'password' && ctx.username === 'fixture' && ctx.password === loginPassword) { event('authentication_accepted', { connection, method: ctx.method }); ctx.accept(); } else ctx.reject(['password']); });
|
||||
client.on('ready', () => {
|
||||
event('ready', { connection });
|
||||
client.on('session', accept => {
|
||||
const session = accept();
|
||||
session.on('pty', acceptPty => { event('pty', { connection }); acceptPty?.(); });
|
||||
session.on('window-change', acceptChange => acceptChange?.());
|
||||
session.on('shell', acceptShell => {
|
||||
const stream = acceptShell(); let line = '';
|
||||
event('shell', { connection }); stream.write('Synthetic Netcatty QA loopback SSH\r\nfixture$ ');
|
||||
stream.on('data', data => {
|
||||
for (const char of data.toString()) {
|
||||
if (char === '\r' || char === '\n') {
|
||||
const submitted = line; line = '';
|
||||
if (!submitted) continue;
|
||||
event('command_received', { connection, command: submitted });
|
||||
if (submitted === commandText) { stream.write(`\r\n${acknowledgement}\r\nfixture$ `); event('acknowledgement_sent', { connection, text: acknowledgement }); }
|
||||
} else if (char === '\x7f') line = line.slice(0, -1);
|
||||
else line += char;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
||||
report.service = { implementation: 'ssh2 real encrypted loopback server with a controlled synthetic shell', address: server.address(), command: commandText, acknowledgement, generatedCredential: 'ephemeral random password, never logged or uploaded' };
|
||||
assert.equal(server.address().address, '127.0.0.1');
|
||||
return server.address().port;
|
||||
}
|
||||
async function launch() {
|
||||
stage('launch verified installed app executable');
|
||||
const debugPort = await freePort(), inspectPort = await freePort();
|
||||
app = spawn(executable, [`--user-data-dir=${profile}`, '--remote-debugging-address=127.0.0.1', `--remote-debugging-port=${debugPort}`, `--inspect=127.0.0.1:${inspectPort}`], { cwd: path.dirname(executable), env: environment(), stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
app.on('error', error => logs.push(error.stack));
|
||||
for (const name of ['stdout', 'stderr']) app[name].on('data', b => logs.push(`[${name}] ${b}`));
|
||||
const target = await until('stock signed app native debugger', async () => {
|
||||
assert.equal(app.exitCode, null, 'Actual app exited; read real stderr');
|
||||
return (await (await fetch(`http://127.0.0.1:${inspectPort}/json/list`, { signal: AbortSignal.timeout(1000) })).json())[0];
|
||||
}, 45000);
|
||||
stage('await actual renderer CDP target before native identity inspection');
|
||||
await until('official app renderer target', async () => {
|
||||
const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`, { signal: AbortSignal.timeout(1000) })).json();
|
||||
report.rendererTargets = targets.map(t => ({ type: t.type, url: t.url, title: t.title }));
|
||||
return targets.some(t => t.type === 'page' && t.url.startsWith('app://netcatty/index.html'));
|
||||
}, 45000);
|
||||
browser = await chromium.connectOverCDP(`http://127.0.0.1:${debugPort}`, { timeout: 30000 }); browser.contexts()[0].setDefaultTimeout(12000);
|
||||
page = await until('actual installed app page', () => browser.contexts()[0].pages().find(p => p.url().startsWith('app://netcatty/index.html') && !p.url().includes('settings')));
|
||||
await page.getByPlaceholder(/^Find a host/).waitFor({ timeout: 45000 });
|
||||
inspector = new Inspector(target.webSocketDebuggerUrl); await inspector.connect();
|
||||
report.nativeInspectorPreflight = await inspector.eval('({pid:process.pid, platform:process.platform, arch:process.arch})');
|
||||
stage('actual renderer ready; inspect native app identity');
|
||||
report.native = await inspector.eval(() => {
|
||||
const e = process.mainModule.require('electron'), w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html'));
|
||||
w.setSize(1440, 1000); w.show(); w.focus();
|
||||
return { pid: process.pid, platform: process.platform, arch: process.arch, uid: process.getuid(), version: e.app.getVersion(), packaged: e.app.isPackaged, appPath: e.app.getAppPath(), executable: process.execPath, profile: e.app.getPath('userData'), origin: w.webContents.getURL(), electron: process.versions.electron, argv: process.argv, preferences: w.webContents.getLastWebPreferences(), noSandbox: e.app.commandLine.hasSwitch('no-sandbox'), disableSetuidSandbox: e.app.commandLine.hasSwitch('disable-setuid-sandbox') };
|
||||
});
|
||||
const n = report.native;
|
||||
assert.equal(n.arch, arch); assert.equal(n.platform, 'darwin'); assert.notEqual(n.uid, 0); assert.equal(n.version, pinned.version); assert.equal(n.packaged, true);
|
||||
assert.equal(n.executable, executable); assert.equal(n.profile, profile); assert(n.appPath.endsWith('/Netcatty.app/Contents/Resources/app.asar'));
|
||||
assert.equal(n.noSandbox, false); assert.equal(n.disableSetuidSandbox, false); assert.equal(n.preferences.contextIsolation, true); assert.equal(n.preferences.nodeIntegration, false); assert.equal(n.preferences.webSecurity, true);
|
||||
report.sandboxScope = `Unmodified stock renderer sandbox:${n.preferences.sandbox}; this is not full renderer-sandbox certification`;
|
||||
await until('native window resize applied', () => inspector.eval(() => {
|
||||
const w = process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html'));
|
||||
return w.isVisible() && w.getBounds().width === 1440;
|
||||
}));
|
||||
await sleep(300);
|
||||
await capture('00-native-launch');
|
||||
stage('native GUI identity and initial capture verified');
|
||||
for (const port of [debugPort, inspectPort]) {
|
||||
const output = execFileSync('/usr/sbin/lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], { encoding: 'utf8', timeout: 10000 });
|
||||
assert(!/\*:|0\.0\.0\.0:|\[::\]:/.test(output), 'Debugger must not listen publicly'); assert(/127\.0\.0\.1:|\[::1\]:/.test(output));
|
||||
(report.debuggerListeners ||= []).push({ port, output });
|
||||
}
|
||||
report.firstLaunch = 'passed: actual installed official native GUI, fresh synthetic profile, stock protections';
|
||||
await capture('01-first-launch');
|
||||
stage('first GUI launch passed');
|
||||
}
|
||||
async function ssh(port) {
|
||||
stage('normal GUI quick-connect to owned loopback SSH');
|
||||
report.ssh = 'incomplete';
|
||||
await page.getByPlaceholder(/^Find a host/).fill(`ssh -p ${port} fixture@127.0.0.1`);
|
||||
await page.getByRole('button', { name: 'Connect', exact: true }).click();
|
||||
await page.getByText('Choose protocol', { exact: false }).first().waitFor();
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByPlaceholder('root', { exact: true }).fill('fixture');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByPlaceholder('Enter password', { exact: true }).fill(loginPassword);
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByText('Confirm this host key', { exact: false }).first().waitFor();
|
||||
await page.getByRole('button', { name: 'Add and continue', exact: true }).click();
|
||||
await until('actual authenticated SSH shell', () => report.fixtureEvents.some(e => e.kind === 'shell'));
|
||||
stage('real authenticated SSH shell accepted by fixture');
|
||||
await until('actual xterm input mounted', () => page.evaluate(() => [...document.querySelectorAll('.xterm-helper-textarea')].some(e => e.closest('.xterm')?.getBoundingClientRect().width > 0)));
|
||||
await capture('02-real-ssh-connected');
|
||||
report.inputFocus = await page.evaluate(() => { const e = [...document.querySelectorAll('.xterm-helper-textarea')].find(e => e.closest('.xterm')?.getBoundingClientRect().width > 0); e.focus(); return { focused: document.activeElement === e, tag: document.activeElement.tagName }; });
|
||||
assert.equal(report.inputFocus.focused, true);
|
||||
await page.keyboard.insertText(commandText); await page.keyboard.press('Enter');
|
||||
await until('server received unique harmless command', () => report.fixtureEvents.some(e => e.kind === 'command_received' && e.command === commandText));
|
||||
assert(report.fixtureEvents.some(e => e.kind === 'acknowledgement_sent' && e.text === acknowledgement));
|
||||
const tabId = await page.locator('[data-tab-type="session"]').first().getAttribute('data-tab-id'); assert(tabId);
|
||||
const params = { sessionId: tabId, scopedSessionIds: [tabId], range: 'tail', maxLines: 80 };
|
||||
await until('server acknowledgement in actual production terminal reader', async () => {
|
||||
const result = await inspector.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/mcpServerBridge.cjs').dispatchBuiltinRpc('netcatty/readContext', ${JSON.stringify(params)})`);
|
||||
report.terminalRead = result;
|
||||
return result.ok === true && result.content.includes(acknowledgement);
|
||||
});
|
||||
report.ssh = 'passed: encrypted SSH authentication + PTY/shell, server unique-command receipt, explicit server acknowledgement in production live terminal buffer';
|
||||
report.tabId = tabId; await sleep(150); await capture('03-real-ssh-roundtrip');
|
||||
stage('real SSH roundtrip passed');
|
||||
}
|
||||
async function quit() {
|
||||
if (inspector) {
|
||||
try { if (app?.exitCode === null && app?.signalCode === null) await inspector.eval("setImmediate(() => process.mainModule.require('electron').app.quit()); true"); }
|
||||
finally { inspector.close(); inspector = null; }
|
||||
}
|
||||
if (!app || app.exitCode !== null || app.signalCode !== null) return;
|
||||
const exited = await new Promise(resolve => { const timer = setTimeout(() => resolve(false), 10000); app.once('exit', () => { clearTimeout(timer); resolve(true); }); });
|
||||
if (!exited && app.exitCode === null && app.signalCode === null) {
|
||||
report.cleanupWarning = 'Normal quit exceeded 10 seconds; terminate only the owned ephemeral QA app'; app.kill('SIGTERM'); await sleep(1500);
|
||||
if (app.exitCode === null && app.signalCode === null) app.kill('SIGKILL');
|
||||
}
|
||||
}
|
||||
function save() {
|
||||
const output = logs.join('');
|
||||
const publicText = output + JSON.stringify(report);
|
||||
const sensitive = publicText.includes(loginPassword) || /-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:gh[opsur]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})|Authorization:\s*Bearer\s+\S+/i.test(publicText);
|
||||
report.stderrReview = sensitive ? 'blocked: sensitive data; logs and images withheld' : 'passed: ephemeral password, private key, GitHub credential and bearer-header checks';
|
||||
if (sensitive) { process.exitCode = 1; report.error = 'Sensitive-data review failed'; }
|
||||
else { fs.writeFileSync(path.join(evidence, 'application-output.log'), output); for (const [name, bytes] of images) fs.writeFileSync(path.join(evidence, name), bytes); }
|
||||
fs.writeFileSync(path.join(evidence, 'assertions.json'), JSON.stringify(report, null, 2));
|
||||
}
|
||||
async function finish() {
|
||||
if (finishing) return finishing;
|
||||
finishing = (async () => {
|
||||
clearTimeout(watchdog);
|
||||
if (report.error) { try { await capture('failure-native-application'); } catch {} if (page) try { report.failureVisibleUI = await page.locator('body').innerText({ timeout: 3000 }); } catch {} }
|
||||
save(); // Preserve actual assertions before cleanup.
|
||||
for (const client of clients) client.end();
|
||||
if (server) { server.close(); await sleep(200); }
|
||||
try { await quit(); } catch (error) { report.cleanupWarning = error.message; app?.kill('SIGTERM'); }
|
||||
for (const client of clients) client._sock?.destroy(); // Owned fixture teardown only, after SSH assertions.
|
||||
if (browser) await Promise.race([browser.close().catch(() => {}), sleep(2000)]);
|
||||
report.applicationExit = app && { pid: app.pid, code: app.exitCode, signal: app.signalCode };
|
||||
save();
|
||||
if (report.stderrReview.startsWith('passed')) console.log('Reviewed actual application output:\n' + logs.join(''));
|
||||
await new Promise(resolve => process.stdout.write(JSON.stringify(report, null, 2) + '\n', resolve));
|
||||
})();
|
||||
return finishing;
|
||||
}
|
||||
async function main() {
|
||||
assert.equal(process.platform, 'darwin'); assert.equal(process.arch, arch); assert.notEqual(process.getuid(), 0); assert(!process.env.GH_TOKEN && !process.env.GITHUB_TOKEN);
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(evidence, 'verification.json'))).status, 'passed', 'No launch around a failed OS assessment');
|
||||
assert(!fs.existsSync(profile), 'First launch must use a fresh QA profile'); fs.mkdirSync(evidence, { recursive: true });
|
||||
watchdog = setTimeout(() => { report.error = 'Native scenario exceeded 240 seconds'; process.exitCode = 1; finish().finally(() => process.exit(1)); }, 240000);
|
||||
const port = await startSsh(); await launch(); await ssh(port);
|
||||
}
|
||||
main().catch(error => { report.error = error.stack; process.exitCode = 1; }).then(async () => {
|
||||
await finish(); process.exit(process.exitCode || 0); // Do not let stale automation transports keep a finished QA step alive.
|
||||
}).catch(error => { console.error(error.stack); process.exit(1); });
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"name": "netcatty-official-macos-qa",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "netcatty-official-macos-qa",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.56.1",
|
||||
"ssh2": "1.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/asn1": {
|
||||
"version": "0.2.6",
|
||||
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
|
||||
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": "~2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bcrypt-pbkdf": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
|
||||
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tweetnacl": "^0.14.3"
|
||||
}
|
||||
},
|
||||
"node_modules/buildcheck": {
|
||||
"version": "0.0.7",
|
||||
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
|
||||
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cpu-features": {
|
||||
"version": "0.0.10",
|
||||
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
|
||||
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
|
||||
"hasInstallScript": true,
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"buildcheck": "~0.0.6",
|
||||
"nan": "^2.19.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nan": {
|
||||
"version": "2.30.0",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz",
|
||||
"integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.56.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
|
||||
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ssh2": {
|
||||
"version": "1.17.0",
|
||||
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
|
||||
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"asn1": "^0.2.6",
|
||||
"bcrypt-pbkdf": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.16.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"cpu-features": "~0.0.10",
|
||||
"nan": "^2.23.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tweetnacl": {
|
||||
"version": "0.14.5",
|
||||
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
|
||||
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
|
||||
"license": "Unlicense"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "netcatty-official-macos-qa",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "QA-only official macOS native launch and loopback SSH",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.56.1",
|
||||
"ssh2": "1.17.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Only this metadata/download step receives the built-in Actions read token.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { Readable } = require('node:stream');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const pinned = require('./candidate.json');
|
||||
const root = path.resolve(process.env.QA_ROOT);
|
||||
const arch = process.env.QA_ARCH;
|
||||
async function digest(file) { const h = crypto.createHash('sha256'); for await (const b of fs.createReadStream(file)) h.update(b); return h.digest('hex'); }
|
||||
async function main() {
|
||||
assert.equal(process.platform, 'darwin'); assert(pinned.dmgs[arch]); assert(process.env.GH_TOKEN);
|
||||
fs.mkdirSync(path.join(root, 'evidence'), { recursive: true });
|
||||
const base = `https://api.github.com/repos/${pinned.repository}`;
|
||||
const headers = { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
async function api(route) { const r = await fetch(base + route, { headers, signal: AbortSignal.timeout(30000) }); assert(r.ok, `Metadata HTTP ${r.status}`); return r.json(); }
|
||||
const run = await api(`/actions/runs/${pinned.run}`);
|
||||
assert.equal(run.head_sha, pinned.sha); assert.equal(run.repository.id, pinned.repositoryId); assert.equal(run.head_repository.id, pinned.repositoryId);
|
||||
assert.equal(run.event, 'push'); assert.equal(run.head_branch, 'main'); assert.equal(run.path, '.github/workflows/build.yml'); assert.equal(run.conclusion, 'success');
|
||||
const jobs = await api(`/actions/runs/${pinned.run}/jobs?per_page=100`);
|
||||
const job = jobs.jobs.find(j => j.id === pinned.buildJob);
|
||||
assert.equal(job?.name, 'build-macos'); assert.equal(job.conclusion, 'success');
|
||||
const artifact = await api(`/actions/artifacts/${pinned.artifact}`);
|
||||
assert.equal(artifact.name, pinned.name); assert.equal(artifact.expired, false); assert(Date.parse(artifact.expires_at) > Date.now());
|
||||
assert.equal(artifact.size_in_bytes, pinned.archiveBytes); assert.equal(artifact.digest, `sha256:${pinned.zipSha256}`);
|
||||
assert.equal(artifact.workflow_run.id, pinned.run); assert.equal(artifact.workflow_run.head_sha, pinned.sha); assert.equal(artifact.workflow_run.head_repository_id, pinned.repositoryId);
|
||||
const redirect = await fetch(`${base}/actions/artifacts/${pinned.artifact}/zip`, { headers, redirect: 'manual', signal: AbortSignal.timeout(30000) });
|
||||
assert.equal(redirect.status, 302); const location = new URL(redirect.headers.get('location')); assert.equal(location.protocol, 'https:');
|
||||
const response = await fetch(location, { signal: AbortSignal.timeout(180000) }); // No token forwarded to blob storage.
|
||||
assert(response.ok, `Artifact HTTP ${response.status}`);
|
||||
const archive = path.join(root, 'official.zip'); await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(archive));
|
||||
assert.equal(fs.statSync(archive).size, pinned.archiveBytes); assert.equal(await digest(archive), pinned.zipSha256);
|
||||
const dmg = path.join(root, pinned.dmgs[arch]);
|
||||
const script = 'import sys,zipfile,shutil,json; z=zipfile.ZipFile(sys.argv[1]); n=sys.argv[2]; assert z.namelist().count(n)==1; print(json.dumps(z.namelist())); src=z.open(n); dst=open(sys.argv[3],"wb"); shutil.copyfileobj(src,dst); dst.close(); src.close()';
|
||||
const entries = JSON.parse(execFileSync('python3', ['-c', script, archive, pinned.dmgs[arch], dmg], { encoding: 'utf8', env: { ...process.env, GH_TOKEN: '' }, timeout: 60000, maxBuffer: 2e6 }));
|
||||
const report = { ...pinned, arch, qaHead: process.env.QA_HEAD_SHA, officialArtifactExpiresAt: artifact.expires_at, verifiedAt: new Date().toISOString(), archiveEntries: entries, selectedDmg: pinned.dmgs[arch], dmgSha256: await digest(dmg), dmgBytes: fs.statSync(dmg).size, scope: 'Exact official candidate only; not final merged revision or release updater acceptance' };
|
||||
fs.writeFileSync(path.join(root, 'evidence/provenance.json'), JSON.stringify(report, null, 2));
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
}
|
||||
main().catch(error => { console.error(error.stack); process.exitCode = 1; });
|
||||
@@ -0,0 +1,66 @@
|
||||
// Read-only OS assessments and normal copy installation. No OS settings change.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const pinned = require('./candidate.json');
|
||||
const root = path.resolve(process.env.QA_ROOT), arch = process.env.QA_ARCH;
|
||||
const evidence = path.join(root, 'evidence');
|
||||
const app = path.join(root, 'Applications/Netcatty.app');
|
||||
const mount = path.join(root, 'mount');
|
||||
const report = { candidate: pinned.sha, arch, qaHead: process.env.QA_HEAD_SHA, commands: [], dmgIntegrity: 'not_run', installedApp: 'not_run', developerId: 'not_run', appNotarizationTicket: 'not_run', gatekeeperApp: 'not_run', scope: 'Runner-owned Applications copy from read-only mounted official DMG. DMG integrity differs from app Developer ID/notarization; no Finder-quarantine or personal-device claim.' };
|
||||
let mounted = false;
|
||||
function command(label, executable, args, required = true, timeout = 60000) {
|
||||
const r = spawnSync(executable, args, { encoding: 'utf8', timeout, maxBuffer: 5e6 });
|
||||
const item = { label, executable, args, exitCode: r.status, signal: r.signal, stdout: r.stdout || '', stderr: r.stderr || '', error: r.error?.message };
|
||||
report.commands.push(item);
|
||||
if (required) assert.equal(r.status, 0, `${label}: ${item.stderr || item.stdout || item.error}`);
|
||||
return item;
|
||||
}
|
||||
function main() {
|
||||
assert.equal(process.platform, 'darwin'); assert.equal(process.arch, arch); assert.notEqual(process.getuid(), 0);
|
||||
assert(!process.env.GH_TOKEN && !process.env.GITHUB_TOKEN);
|
||||
fs.mkdirSync(evidence, { recursive: true });
|
||||
report.uname = command('runner uname', '/usr/bin/uname', ['-m']).stdout.trim();
|
||||
assert.equal(report.uname, arch === 'arm64' ? 'arm64' : 'x86_64');
|
||||
report.os = command('runner OS', '/usr/bin/sw_vers', []).stdout;
|
||||
report.uid = process.getuid(); report.runnerLabel = process.env.QA_RUNNER; report.nodeArch = process.arch;
|
||||
const dmg = path.join(root, pinned.dmgs[arch]);
|
||||
command('DMG integrity verification', '/usr/bin/hdiutil', ['verify', dmg]); report.dmgIntegrity = 'passed';
|
||||
// Informational only: unsigned outer DMG != unsigned/not-notarized inner app.
|
||||
report.outerDmgSignature = command('outer DMG signature display (not an app assessment)', '/usr/bin/codesign', ['-d', '--verbose=4', dmg], false);
|
||||
report.outerDmgStapler = command('outer DMG staple validation (reported separately)', '/usr/bin/xcrun', ['stapler', 'validate', dmg], false);
|
||||
fs.mkdirSync(mount, { recursive: true });
|
||||
command('mount official DMG read-only', '/usr/bin/hdiutil', ['attach', '-readonly', '-nobrowse', '-noautoopen', '-mountpoint', mount, dmg]); mounted = true;
|
||||
assert(fs.existsSync(path.join(mount, 'Netcatty.app')));
|
||||
fs.mkdirSync(path.dirname(app), { recursive: true }); assert(!fs.existsSync(app));
|
||||
command('copy original app preserving bundle metadata', '/usr/bin/ditto', [path.join(mount, 'Netcatty.app'), app]); report.installedApp = 'passed: normal runner-owned Applications copy; original bundle unchanged';
|
||||
command('unmount read-only image', '/usr/bin/hdiutil', ['detach', mount]); mounted = false;
|
||||
report.bundleIdentifier = command('bundle identifier', '/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleIdentifier', path.join(app, 'Contents/Info.plist')]).stdout.trim();
|
||||
assert.equal(report.bundleIdentifier, pinned.bundleId);
|
||||
report.bundleVersion = command('bundle version', '/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleShortVersionString', path.join(app, 'Contents/Info.plist')]).stdout.trim();
|
||||
const executableName = command('bundle executable', '/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleExecutable', path.join(app, 'Contents/Info.plist')]).stdout.trim();
|
||||
assert.equal(executableName, 'Netcatty');
|
||||
report.executable = path.join(app, 'Contents/MacOS', executableName);
|
||||
report.executableArchitectures = command('Mach-O architecture', '/usr/bin/lipo', ['-archs', report.executable]).stdout.trim().split(/\s+/);
|
||||
assert(report.executableArchitectures.includes(report.uname), 'Official executable must contain native runner architecture');
|
||||
command('strict deep code signature verification', '/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=4', app]);
|
||||
const signature = command('Developer ID signature identifiers', '/usr/bin/codesign', ['-d', '--verbose=4', app]);
|
||||
const description = signature.stdout + signature.stderr;
|
||||
assert(description.includes(`Identifier=${pinned.bundleId}`)); assert(/Authority=Developer ID Application:/.test(description)); assert(/TeamIdentifier=[A-Z0-9]+/.test(description)); assert(/flags=.*runtime/.test(description));
|
||||
report.teamIdentifier = description.match(/TeamIdentifier=([A-Z0-9]+)/)[1];
|
||||
report.authorities = [...description.matchAll(/^Authority=(.+)$/gm)].map(m => m[1]);
|
||||
command('designated requirements', '/usr/bin/codesign', ['-d', '-r-', app]); report.developerId = 'passed: valid strict Developer ID application signature with hardened runtime';
|
||||
command('notarization ticket on installed APP', '/usr/bin/xcrun', ['stapler', 'validate', app]); report.appNotarizationTicket = 'passed';
|
||||
const status = command('stock Gatekeeper status (read only)', '/usr/sbin/spctl', ['--status']);
|
||||
assert(/assessments enabled/i.test(status.stdout + status.stderr), 'Runner must have stock Gatekeeper assessments enabled; never enable/disable to obtain a pass');
|
||||
const gatekeeper = command('Gatekeeper assessment of installed APP', '/usr/sbin/spctl', ['--assess', '--type', 'execute', '--verbose=4', app], true, 90000);
|
||||
assert(/Notarized Developer ID/.test(gatekeeper.stdout + gatekeeper.stderr)); report.gatekeeperApp = 'passed: accepted, Notarized Developer ID';
|
||||
report.installedAppXattrs = command('observe app xattrs without modification', '/usr/bin/xattr', ['-l', app], false);
|
||||
report.installPath = app; report.status = 'passed';
|
||||
}
|
||||
try { main(); } catch (error) { report.status = 'failed'; report.blocker = error.stack; process.exitCode = 1; }
|
||||
finally {
|
||||
if (mounted) command('detach after failed assessment', '/usr/bin/hdiutil', ['detach', mount], false);
|
||||
fs.mkdirSync(evidence, { recursive: true }); fs.writeFileSync(path.join(evidence, 'verification.json'), JSON.stringify(report, null, 2)); console.log(JSON.stringify(report, null, 2));
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
# Installed Windows package acceptance (QA only)
|
||||
|
||||
This harness belongs only to same-repository Draft PR #4299 on
|
||||
`qa/official-linux-a23868e`. Its independent standard `windows-2022` workflow
|
||||
does not modify the product, release packages, main, or the earlier Linux job.
|
||||
|
||||
`candidate.json` pins the public v1.1.90 NSIS asset and the exact official
|
||||
9d4e90b Windows Actions artifact. The downloader verifies repository, main push,
|
||||
build job, artifact metadata and archive SHA-256 before extracting the one named
|
||||
NSIS installer. The Actions read token exists only in this downloader step.
|
||||
|
||||
An independent `portable` matrix job verifies the public v1.1.90 Windows ZIP
|
||||
SHA-256 `df057f03d122fb541168868d2d203c3723b8b731a663dbdaa5bc38390a742b88`
|
||||
and extracts the exact candidate Windows ZIP entry from the same verified
|
||||
official artifact. It runs the identical actual-GUI migration assertions on an
|
||||
explicit disposable profile, even if NSIS fails. ZIP extraction does not certify
|
||||
installation, overinstallation, NSIS portable launchers or automatic updates.
|
||||
The two modes use fresh independent VMs and separately named evidence artifacts.
|
||||
|
||||
The separate exact-fix jobs pin same-repository PR #4302 commit
|
||||
`4516d3aed7cb54862dabd53abb56a7f90fba3212`, based on frozen main 9d4e90b.
|
||||
If no exact standard package exists, a separate checkout on standard
|
||||
windows-2022 runs the existing Node 22/MSVC/npm ci/pack:win-x64 conventions.
|
||||
Only the normal non-release version metadata is set. Application source is not
|
||||
patched while packaging. The build child receives a Windows environment
|
||||
allowlist with no Actions credentials; signing/distribution credentials are not
|
||||
supplied and publishing is disabled. The resulting NSIS is explicitly
|
||||
CI QA-built, unsigned and unreleased. Its exact SHA-256, source SHA and QA run
|
||||
are verified in a separate fresh desktop job before normal installation.
|
||||
|
||||
The fix acceptance uses the same real released v1.1.90 GUI baseline and native
|
||||
NSIS/history harness. A positive candidate-created Beta pointer in IndexedDB is
|
||||
a mandatory precondition before normal quit. That exact pointer must survive
|
||||
complete restart before panel interaction, alongside both original chats,
|
||||
saved host and new reply. Panel display intent remains memory-only: manual
|
||||
history opening after restart is not claimed as automatic conversation reopen.
|
||||
The old official 9d4e90b control and its original retained failure are separate.
|
||||
|
||||
The installed real v1.1.90 GUI configures a deterministic loopback-only OpenAI
|
||||
provider, saves one synthetic loopback host, and creates two distinct chats with
|
||||
two complete user/assistant turns each. Beta remains active. No localStorage,
|
||||
IndexedDB or React state writes seed the fixture. The same custom profile and
|
||||
`app://netcatty` origin are reused by the installed official candidate. Read-only
|
||||
storage observations compare original session IDs, full messages and scope,
|
||||
the exact active pointer, saved host and the IndexedDB migration marker. The
|
||||
candidate sends another normal GUI message, quits normally and restarts to
|
||||
verify the appended turn and original chats persist.
|
||||
|
||||
Both candidate snapshots must have IndexedDB `meta.activeSessionMap` directly;
|
||||
legacy localStorage is not accepted as a substitute for migration evidence.
|
||||
The stock panel's draft/chat display intent is memory-only. Record and capture
|
||||
the initial candidate/restarted view before any navigation. If it opens the
|
||||
Recent/draft view, verify the original IndexedDB active pointer first, then
|
||||
select the existing chat through normal history UI. Do not call that selection
|
||||
automatic restoration of the previously visible conversation.
|
||||
|
||||
Both installers use normal silent per-user NSIS arguments. The candidate version
|
||||
`0.0.0-sha-9d4e90b` is below 1.1.90, so this is **not** released automatic updater
|
||||
acceptance. A blocked replacement is recorded separately. A normal uninstall
|
||||
and fresh candidate installation may then test migration using the preserved
|
||||
explicit QA profile, without altering packages or bypassing version checks.
|
||||
|
||||
The application receives an allowlist of Windows runtime environment variables,
|
||||
isolated synthetic home directories, and no GitHub token. There are no sandbox
|
||||
disabling flags or system security changes. The stock application's own web
|
||||
preferences are recorded rather than claiming stronger isolation than it uses.
|
||||
|
||||
Evidence is retained for three days. `provenance.json` has exact hashes;
|
||||
`assertions.json` records individual outcomes, installer exits, actual running
|
||||
executable/version/profile/origin, and loopback calls. Storage snapshots contain
|
||||
only synthetic chats/host. PNGs (`01-baseline-alpha`, `02-baseline-beta-active`,
|
||||
`03-candidate-beta-active`, `04-candidate-alpha`, `05-candidate-appended`,
|
||||
`06-candidate-restarted`, or `failure-*`) capture the actual installed native
|
||||
renderer via CDP, not the Windows OS desktop or a physical computer. Logs are
|
||||
checked for credential patterns before PNGs and app output enter the upload
|
||||
directory. Launch, installer, harness and product failures remain failures.
|
||||
@@ -0,0 +1,77 @@
|
||||
// Trusted exact-SHA source build only. No Actions credentials reach npm/build.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { spawn, execFileSync } = require('node:child_process');
|
||||
const pinned = require('./fixed-candidate.json');
|
||||
const source = path.resolve(process.env.QA_FIX_SOURCE);
|
||||
const output = path.resolve(process.env.QA_BUILD_OUTPUT);
|
||||
const report = { ...pinned, origin: 'CI QA-built from exact trusted same-repository fix; unsigned, unreleased, no automatic updater certification', run: process.env.GITHUB_RUN_ID, qaHead: process.env.QA_HEAD_SHA, node: process.version, platform: process.platform, arch: process.arch, steps: [] };
|
||||
const logs = [];
|
||||
function environment() {
|
||||
const allowed = ['PATH', 'SystemRoot', 'SystemDrive', 'WINDIR', 'ComSpec', 'PATHEXT', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432', 'CommonProgramFiles', 'CommonProgramFiles(x86)', 'CommonProgramW6432', 'ProgramData', 'ALLUSERSPROFILE', 'PUBLIC', 'OS', 'PROCESSOR_ARCHITECTURE', 'NUMBER_OF_PROCESSORS', 'USERNAME', 'USERDOMAIN', 'USERDNSDOMAIN', 'COMPUTERNAME', 'SESSIONNAME', 'PSModulePath', 'PSHOME', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'HOMEDRIVE', 'HOMEPATH', 'TEMP', 'TMP'];
|
||||
const env = {};
|
||||
for (const key of allowed) if (process.env[key]) env[key] = process.env[key];
|
||||
return { ...env, CI: 'true', BUNDLE_MOSH: 'false', BUNDLE_ET: 'false', ELECTRON_BUILDER_PUBLISH: 'never', CSC_IDENTITY_AUTO_DISCOVERY: 'false', NPM_CONFIG_FETCH_RETRIES: '4', NPM_CONFIG_FETCH_RETRY_FACTOR: '2', NPM_CONFIG_FETCH_RETRY_MINTIMEOUT: '1000', NPM_CONFIG_FETCH_RETRY_MAXTIMEOUT: '10000' };
|
||||
}
|
||||
const safe = environment();
|
||||
function git(...args) { return execFileSync('git', args, { cwd: source, env: safe, encoding: 'utf8', timeout: 30000 }).trim(); }
|
||||
async function digest(file) { const hash = crypto.createHash('sha256'); for await (const part of fs.createReadStream(file)) hash.update(part); return hash.digest('hex'); }
|
||||
async function main() {
|
||||
assert.equal(process.platform, 'win32'); assert.equal(process.arch, 'x64');
|
||||
fs.mkdirSync(output, { recursive: true });
|
||||
assert.equal(git('rev-parse', 'HEAD'), pinned.sha);
|
||||
assert.equal(git('config', '--get', 'remote.origin.url').replace(/\.git$/, ''), `https://github.com/${pinned.repository}`);
|
||||
assert.equal(git('status', '--porcelain'), '', 'Exact source checkout must begin clean');
|
||||
const originalSourceHash = await digest(path.join(source, 'application/state/useAIState.ts'));
|
||||
const vswhere = path.join(process.env['ProgramFiles(x86)'], 'Microsoft Visual Studio/Installer/vswhere.exe');
|
||||
const installation = execFileSync(vswhere, ['-latest', '-products', '*', '-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64', '-property', 'installationPath'], { env: safe, encoding: 'utf8', timeout: 30000 }).trim();
|
||||
assert(installation, 'Stock Windows hosted MSVC installation required');
|
||||
const vsScript = path.join(installation, 'Common7/Tools/Launch-VsDevShell.ps1');
|
||||
assert(fs.existsSync(vsScript));
|
||||
const script = `$ErrorActionPreference = 'Stop'
|
||||
& $env:QA_VS_SCRIPT -Arch amd64 -HostArch amd64 -SkipAutomaticLocation
|
||||
if (-not $?) { throw 'MSVC developer shell failed' }
|
||||
Set-Location -LiteralPath $env:QA_FIX_SOURCE
|
||||
Write-Output 'QA_BUILD_STEP npm ci'
|
||||
& npm.cmd ci
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
Write-Output 'QA_BUILD_STEP repository non-release version metadata'
|
||||
& npm.cmd pkg set "version=$env:QA_FIX_VERSION"
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
Write-Output 'QA_BUILD_STEP npm run pack:win-x64 -- publish never'
|
||||
& npm.cmd run pack:win-x64
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
Write-Output 'QA_BUILD_STEP packaged SSH cipher verification'
|
||||
& node scripts/test-packaged-ssh-ciphers.cjs
|
||||
exit $LASTEXITCODE`;
|
||||
const child = spawn('pwsh.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { cwd: source, env: { ...safe, QA_FIX_SOURCE: source, QA_FIX_VERSION: pinned.version, QA_VS_SCRIPT: vsScript }, windowsHide: false, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
child.on('error', error => logs.push(error.stack));
|
||||
for (const stream of [child.stdout, child.stderr]) stream.on('data', part => { const text = String(part); logs.push(text); process.stdout.write(text); });
|
||||
const code = await new Promise(resolve => child.once('close', resolve));
|
||||
report.buildExit = code;
|
||||
assert.equal(code, 0, 'Repository Windows packaging failed');
|
||||
assert.equal(await digest(path.join(source, 'application/state/useAIState.ts')), originalSourceHash, 'Do not modify application source to package it');
|
||||
assert.equal(git('rev-parse', 'HEAD'), pinned.sha);
|
||||
const installer = path.join(source, 'release', pinned.installer);
|
||||
assert(fs.existsSync(installer), 'Exact NSIS installer must be produced');
|
||||
report.installerSha256 = await digest(installer);
|
||||
report.installerBytes = fs.statSync(installer).size;
|
||||
report.sourceFileSha256 = originalSourceHash;
|
||||
report.versionMetadata = JSON.parse(fs.readFileSync(path.join(source, 'package.json'))).version;
|
||||
assert.equal(report.versionMetadata, pinned.version);
|
||||
fs.copyFileSync(installer, path.join(output, pinned.installer));
|
||||
fs.appendFileSync(process.env.GITHUB_OUTPUT, `installer_sha=${report.installerSha256}\n`);
|
||||
report.status = 'passed';
|
||||
}
|
||||
main().catch(error => { report.status = 'failed'; report.error = error.stack; process.exitCode = 1; }).finally(() => {
|
||||
fs.mkdirSync(output, { recursive: true });
|
||||
const log = logs.join('');
|
||||
const sensitive = /(?:gh[opsu]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|-----BEGIN (?:RSA |OPENSSH )?PRIVATE KEY-----|Authorization:\s*Bearer\s+\S+)/i.test(log);
|
||||
report.logReview = sensitive ? 'blocked' : 'passed: no credentials supplied to build process; output pattern scan passed';
|
||||
if (!sensitive) fs.writeFileSync(path.join(output, 'build.log'), log);
|
||||
else { process.exitCode = 1; fs.rmSync(path.join(output, pinned.installer), { force: true }); }
|
||||
fs.writeFileSync(path.join(output, 'build-provenance.json'), JSON.stringify(report, null, 2));
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"repository": "binaricat/Netcatty",
|
||||
"repositoryId": 1111357457,
|
||||
"sha": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
|
||||
"run": 44903060405,
|
||||
"artifact": 14707595613,
|
||||
"name": "netcatty-windows",
|
||||
"zipSha256": "3a197f7b2510e34547168b066a470e70c454610500639670e356a8a24da1e502",
|
||||
"installer": "Netcatty-0.0.0-sha-9d4e90b-win-x64.exe",
|
||||
"version": "0.0.0-sha-9d4e90b",
|
||||
"portableZip": "Netcatty-0.0.0-sha-9d4e90b-win-x64.zip",
|
||||
"portableBaseline": {
|
||||
"tag": "v1.1.90",
|
||||
"asset": 677167676,
|
||||
"installer": "Netcatty-1.1.90-win-x64.zip",
|
||||
"sha256": "df057f03d122fb541168868d2d203c3723b8b731a663dbdaa5bc38390a742b88",
|
||||
"url": "https://github.com/binaricat/Netcatty/releases/download/v1.1.90/Netcatty-1.1.90-win-x64.zip"
|
||||
},
|
||||
"baseline": {
|
||||
"tag": "v1.1.90",
|
||||
"asset": 677167660,
|
||||
"installer": "Netcatty-1.1.90-win-x64.exe",
|
||||
"sha256": "cf6a028a0286264fd1e315025b1f78e8c96c468d6a22d5058b64319410debdc9",
|
||||
"url": "https://github.com/binaricat/Netcatty/releases/download/v1.1.90/Netcatty-1.1.90-win-x64.exe"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
// Operates the installed, unmodified Electron application through its real GUI.
|
||||
// Storage and native debugger calls below observe state; all test data is seeded
|
||||
// through normal controls and a deterministic model bound only to loopback.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
const net = require('node:net');
|
||||
const vm = require('node:vm');
|
||||
const crypto = require('node:crypto');
|
||||
const { spawn, execFileSync } = require('node:child_process');
|
||||
const { chromium } = require('playwright-core');
|
||||
const pinned = require(path.resolve(__dirname, process.env.QA_CANDIDATE || 'candidate.json'));
|
||||
const portable = process.env.QA_MODE === 'portable';
|
||||
const root = path.resolve(process.env.QA_ROOT);
|
||||
const evidence = path.join(root, 'evidence');
|
||||
const staging = path.join(root, 'unreviewed');
|
||||
const home = path.join(root, 'user');
|
||||
const profile = path.join(root, 'profile');
|
||||
const installDir = path.join(root, 'app');
|
||||
let executable = path.join(installDir, 'Netcatty.exe');
|
||||
const hostLabel = 'QA Windows Loopback';
|
||||
const report = {
|
||||
candidate: pinned.sha, qaHead: process.env.QA_HEAD_SHA, mode: portable ? 'portable ZIP' : 'NSIS installed',
|
||||
testPackageOrigin: pinned.qaBuilt ? 'Exact trusted fix SHA, CI QA-built NSIS; unsigned/unreleased, not released automatic updater acceptance' : 'Pinned official package',
|
||||
baselineInstall: 'not_run', baselineGuiSeed: 'not_run', installerReplacement: 'not_run',
|
||||
candidateInstall: 'not_run', aiHistoryMigration: 'not_run', restartPersistence: 'not_run',
|
||||
scope: portable ? 'Independent official Windows ZIP extraction and real native Electron GUI migration; no installation, replacement or updater coverage. CDP PNGs are actual renderer captures. Synthetic data only.' : 'Real per-user NSIS and installed native Electron renderer on ephemeral windows-2022; CDP PNGs are actual renderer captures, not OS desktop captures. Synthetic data only.',
|
||||
updater: 'not_covered: CI candidate 0.0.0-sha version is not a released automatic updater test',
|
||||
security: 'Stock application sandbox settings; no disabling flags, privilege or system security changes',
|
||||
events: [], installers: [], launches: [],
|
||||
};
|
||||
const logs = [];
|
||||
const replies = new Map([
|
||||
['QA_ALPHA_USER_ONE', 'QA_ALPHA_REPLY_ONE'], ['QA_ALPHA_USER_TWO', 'QA_ALPHA_REPLY_TWO'],
|
||||
['QA_BETA_USER_ONE', 'QA_BETA_REPLY_ONE'], ['QA_BETA_USER_TWO', 'QA_BETA_REPLY_TWO'],
|
||||
['QA_BETA_AFTER_UPGRADE', 'QA_BETA_REPLY_AFTER_UPGRADE'],
|
||||
]);
|
||||
let app, browser, page, inspector, fixture, watchdog;
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
function event(label, detail) { report.events.push({ at: new Date().toISOString(), label, detail }); console.log(label); }
|
||||
async function until(label, check, timeout = 20000) {
|
||||
const deadline = Date.now() + timeout;
|
||||
let last;
|
||||
while (Date.now() < deadline) {
|
||||
try { const result = await check(); if (result) return result; } catch (error) { if (error instanceof SyntaxError) throw error; last = error; }
|
||||
await sleep(200);
|
||||
}
|
||||
throw new Error(`Timed out: ${label}${last ? `: ${last.message}` : ''}`);
|
||||
}
|
||||
function childExit(child, timeout) {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
|
||||
return new Promise(resolve => {
|
||||
const finish = () => { clearTimeout(timer); resolve(true); };
|
||||
const timer = setTimeout(() => { child.off('exit', finish); resolve(false); }, timeout);
|
||||
child.once('exit', finish);
|
||||
});
|
||||
}
|
||||
async function freePort() {
|
||||
const server = net.createServer();
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
return port;
|
||||
}
|
||||
function isolatedEnvironment(installer = false) {
|
||||
const allowed = ['PATH', 'SystemRoot', 'SystemDrive', 'WINDIR', 'ComSpec', 'PATHEXT', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramData', 'ALLUSERSPROFILE', 'PUBLIC', 'OS', 'PROCESSOR_ARCHITECTURE', 'NUMBER_OF_PROCESSORS', 'USERNAME', 'USERDOMAIN', 'USERDNSDOMAIN', 'COMPUTERNAME', 'SESSIONNAME', 'PSModulePath', 'PSHOME'];
|
||||
const env = {};
|
||||
for (const key of allowed) if (process.env[key]) env[key] = process.env[key];
|
||||
Object.assign(env, { USERPROFILE: home, HOME: home, APPDATA: path.join(home, 'AppData', 'Roaming'), LOCALAPPDATA: path.join(home, 'AppData', 'Local'), TEMP: path.join(root, 'temp'), TMP: path.join(root, 'temp') });
|
||||
for (const dir of [home, env.APPDATA, env.LOCALAPPDATA, env.TEMP]) fs.mkdirSync(dir, { recursive: true });
|
||||
// NSIS uses the real ephemeral Windows user's shell folders. Its explicit
|
||||
// installation directory remains QA-owned; only the application gets the
|
||||
// synthetic home/profile. Do not change Windows account or registry paths.
|
||||
if (installer) for (const key of ['USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'HOMEDRIVE', 'HOMEPATH']) if (process.env[key]) env[key] = process.env[key];
|
||||
return env;
|
||||
}
|
||||
function osCommand(script, timeout = 20000, extra = {}) {
|
||||
return execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { env: { ...isolatedEnvironment(true), ...extra }, encoding: 'utf8', timeout });
|
||||
}
|
||||
function installerDiagnostic(label, pid) {
|
||||
const result = { executableExists: fs.existsSync(executable), installFiles: fs.existsSync(installDir) ? fs.readdirSync(installDir) : [] };
|
||||
try {
|
||||
result.process = osCommand(`Get-CimInstance Win32_Process -Filter "ProcessId=$env:QA_NSIS_PID" | Select-Object Name,ProcessId,ParentProcessId,ExecutablePath,CommandLine | ConvertTo-Json; Get-Process | Where-Object {$_.ProcessName -like '*Netcatty*'} | Select-Object ProcessName,Id,MainWindowTitle,Responding,SessionId | ConvertTo-Json`, 10000, { QA_NSIS_PID: String(pid) });
|
||||
} catch (error) { result.processError = error.message; }
|
||||
try {
|
||||
result.desktop = osCommand(`Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing
|
||||
$b = [Windows.Forms.Screen]::PrimaryScreen.Bounds
|
||||
$bitmap = [Drawing.Bitmap]::new($b.Width,$b.Height); $g = [Drawing.Graphics]::FromImage($bitmap)
|
||||
$g.CopyFromScreen($b.Location,[Drawing.Point]::Empty,$b.Size)
|
||||
$bitmap.Save($env:QA_NATIVE_PNG,[Drawing.Imaging.ImageFormat]::Png); $g.Dispose(); $bitmap.Dispose(); 'Actual OS desktop captured'`, 10000, { QA_NATIVE_PNG: path.join(staging, `installer-${label.replace(/[^a-z0-9]/gi, '-')}.png`) });
|
||||
} catch (error) { result.desktopError = error.message; }
|
||||
try {
|
||||
const source = `using System; using System.Text; using System.Runtime.InteropServices;
|
||||
public class QaWindows { public delegate bool Callback(IntPtr h, IntPtr p);
|
||||
[DllImport("user32.dll")] public static extern bool EnumWindows(Callback cb, IntPtr p);
|
||||
[DllImport("user32.dll")] public static extern bool EnumChildWindows(IntPtr h, Callback cb, IntPtr p);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder b, int n);
|
||||
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); }`;
|
||||
const script = `Add-Type -TypeDefinition $env:QA_NATIVE_SOURCE
|
||||
$items = [Collections.Generic.List[object]]::new()
|
||||
[QaWindows]::EnumWindows({param($h,$p)
|
||||
[uint32]$owner = 0; [void][QaWindows]::GetWindowThreadProcessId($h,[ref]$owner)
|
||||
$proc = Get-Process -Id $owner -ErrorAction SilentlyContinue
|
||||
if ($proc.ProcessName -like '*Netcatty*') {
|
||||
$text = [Text.StringBuilder]::new(4096); [void][QaWindows]::GetWindowText($h,$text,4096)
|
||||
$items.Add(@{process=$proc.ProcessName;pid=$owner;text=$text.ToString()})
|
||||
[QaWindows]::EnumChildWindows($h,{param($child,$unused)
|
||||
$body = [Text.StringBuilder]::new(4096); [void][QaWindows]::GetWindowText($child,$body,4096)
|
||||
if ($body.Length) {$items.Add(@{childText=$body.ToString()})}; return $true
|
||||
},[IntPtr]::Zero) | Out-Null
|
||||
}; return $true
|
||||
},[IntPtr]::Zero) | Out-Null
|
||||
$items | ConvertTo-Json -Depth 5`;
|
||||
result.windows = osCommand(script, 10000, { QA_NATIVE_SOURCE: source });
|
||||
} catch (error) { result.windowError = error.message; }
|
||||
return result;
|
||||
}
|
||||
class Inspector {
|
||||
constructor(url) {
|
||||
this.ws = new WebSocket(url); this.id = 0; this.pending = new Map();
|
||||
this.ws.addEventListener('message', event => {
|
||||
const message = JSON.parse(event.data);
|
||||
const item = this.pending.get(message.id);
|
||||
if (!item) return;
|
||||
this.pending.delete(message.id);
|
||||
if (message.error) item.reject(new Error(message.error.message)); else item.resolve(message.result);
|
||||
});
|
||||
}
|
||||
async connect() {
|
||||
await new Promise((resolve, reject) => { this.ws.addEventListener('open', resolve, { once: true }); this.ws.addEventListener('error', reject, { once: true }); });
|
||||
}
|
||||
async eval(expression) {
|
||||
if (typeof expression === 'function') expression = `(${expression.toString()})()`;
|
||||
new vm.Script(expression); // Validate generated debugger code before sending.
|
||||
const id = ++this.id;
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('Native inspector timeout')); }, 12000);
|
||||
this.pending.set(id, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
|
||||
this.ws.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, returnByValue: true, awaitPromise: true } }));
|
||||
});
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
return result.result.value;
|
||||
}
|
||||
close() { this.ws.close(); }
|
||||
}
|
||||
async function install(installer, label, uninstall = false) {
|
||||
assert(!app || app.exitCode !== null, 'Close app before official installer');
|
||||
const args = uninstall ? ['/S', '/currentuser'] : ['/S', '/currentuser', `/D=${installDir}`];
|
||||
const started = Date.now();
|
||||
const child = spawn(installer, args, { env: isolatedEnvironment(true), windowsHide: false, stdio: 'ignore' });
|
||||
let output = '';
|
||||
let spawnError;
|
||||
child.on('error', error => { spawnError = error; });
|
||||
const completed = await childExit(child, 90000);
|
||||
const diagnostic = !completed ? installerDiagnostic(label, child.pid) : undefined;
|
||||
if (!completed) child.kill();
|
||||
const result = { label, installer: path.basename(installer), arguments: args, exitCode: child.exitCode, completed, durationMs: Date.now() - started, output, error: spawnError?.message, diagnostic };
|
||||
report.installers.push(result); event(`installer ${label}`, result);
|
||||
return completed && child.exitCode === 0 && !spawnError;
|
||||
}
|
||||
async function startModel() {
|
||||
const calls = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Access-Control-Allow-Headers', 'content-type,authorization,x-api-key');
|
||||
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
|
||||
if (req.url === '/v1/models') { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ object: 'list', data: [{ id: 'qa-history-fixture', object: 'model', owned_by: 'synthetic-loopback' }] })); return; }
|
||||
if (req.url !== '/v1/chat/completions' || req.method !== 'POST') { res.writeHead(404); res.end(); return; }
|
||||
let raw = '';
|
||||
for await (const part of req) { raw += part; if (raw.length > 4e6) { res.writeHead(413); res.end(); return; } }
|
||||
const body = JSON.parse(raw);
|
||||
const last = body.messages?.filter(m => m.role === 'user').at(-1)?.content;
|
||||
const content = typeof last === 'string' ? last : (last || []).filter(p => p.type === 'text').map(p => p.text).join('\n');
|
||||
const matched = [...replies.keys()].find(text => content?.includes(text));
|
||||
calls.push({ at: new Date().toISOString(), prompt: matched || 'UNEXPECTED_SYNTHETIC_REQUEST', model: body.model, stream: body.stream });
|
||||
const reply = replies.get(matched) || 'QA_UNEXPECTED_PROMPT';
|
||||
if (!body.stream) {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.end(JSON.stringify({ id: 'qa', object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content: reply }, finish_reason: 'stop' }] })); return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
|
||||
const chunk = (delta, finish_reason = null) => `data: ${JSON.stringify({ id: 'qa', object: 'chat.completion.chunk', created: 1700000000, model: 'qa-history-fixture', choices: [{ index: 0, delta, finish_reason }] })}\n\n`;
|
||||
res.write(chunk({ role: 'assistant', content: reply }));
|
||||
await sleep(100);
|
||||
res.write(chunk({}, 'stop')); res.end('data: [DONE]\n\n');
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
return { server, calls, port: server.address().port };
|
||||
}
|
||||
async function screenshot(name, target = page) {
|
||||
if (target && !target.isClosed()) {
|
||||
const png = await target.screenshot({ path: path.join(staging, `${name}.png`), timeout: 10000 });
|
||||
(report.screenshots ||= []).push({ name: `${name}.png`, bytes: png.length, width: png.readUInt32BE(16), height: png.readUInt32BE(20), sha256: crypto.createHash('sha256').update(png).digest('hex'), scope: 'Actual native application renderer' });
|
||||
}
|
||||
}
|
||||
async function launch(label, expectedVersion) {
|
||||
assert(fs.existsSync(executable), 'Official installer must create Netcatty.exe');
|
||||
const port = await freePort(), inspectPort = await freePort();
|
||||
app = spawn(executable, [`--user-data-dir=${profile}`, '--remote-debugging-address=127.0.0.1', `--remote-debugging-port=${port}`, `--inspect=127.0.0.1:${inspectPort}`], {
|
||||
cwd: path.dirname(executable), env: isolatedEnvironment(), windowsHide: false, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
app.on('error', error => logs.push(`${label}: ${error.message}`));
|
||||
for (const name of ['stdout', 'stderr']) app[name].on('data', part => logs.push(`[${label} ${name}] ${part}`));
|
||||
const info = await until(`${label} native debugger`, async () => {
|
||||
assert.equal(app.exitCode, null, 'Installed app exited before debugger');
|
||||
const response = await fetch(`http://127.0.0.1:${inspectPort}/json/list`, { signal: AbortSignal.timeout(1000) });
|
||||
return (await response.json())[0];
|
||||
}, 45000);
|
||||
inspector = new Inspector(info.webSocketDebuggerUrl); await inspector.connect();
|
||||
await until(`${label} Chromium debugger ready`, async () => {
|
||||
assert.equal(app.exitCode, null, 'Real app exited before Chromium debugger');
|
||||
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
|
||||
return (await response.json()).webSocketDebuggerUrl;
|
||||
}, 45000);
|
||||
await until(`${label} actual native renderer ready`, () => inspector.eval(async () => {
|
||||
const e = process.mainModule.require('electron');
|
||||
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html') && !w.webContents.getURL().includes('settings'));
|
||||
return !!w && !w.webContents.isLoadingMainFrame() && await w.webContents.executeJavaScript("!!document.querySelector('[data-section=\"top-tabs-toolbar-actions\"]')");
|
||||
}), 45000);
|
||||
const native = await inspector.eval(`(() => {
|
||||
const e = process.mainModule.require('electron');
|
||||
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html') && !w.webContents.getURL().includes('settings'));
|
||||
w.setSize(1440, 1000); w.show(); w.focus();
|
||||
return { version:e.app.getVersion(), packaged:e.app.isPackaged, appPath:e.app.getAppPath(), profile:e.app.getPath('userData'), executable:process.execPath,
|
||||
origin:w.webContents.getURL(), argv:process.argv, preferences:w.webContents.getLastWebPreferences(),
|
||||
noSandbox:e.app.commandLine.hasSwitch('no-sandbox'), disableSetuidSandbox:e.app.commandLine.hasSwitch('disable-setuid-sandbox') };
|
||||
})()`);
|
||||
report.launches.push({ label, ...native });
|
||||
assert.equal(native.version, expectedVersion);
|
||||
assert.equal(native.packaged, true);
|
||||
assert.equal(path.resolve(native.profile).toLowerCase(), profile.toLowerCase());
|
||||
assert.equal(path.resolve(native.executable).toLowerCase(), executable.toLowerCase());
|
||||
assert(native.appPath.toLowerCase().startsWith(path.dirname(executable).toLowerCase()));
|
||||
assert.equal(native.noSandbox, false); assert.equal(native.disableSetuidSandbox, false);
|
||||
event(`launched ${label}`, { version: native.version, origin: native.origin });
|
||||
const nativePng = await inspector.eval(`(async () => {
|
||||
const e = process.mainModule.require('electron');
|
||||
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html') && !w.webContents.getURL().includes('settings'));
|
||||
return (await w.webContents.capturePage()).toPNG().toString('base64');
|
||||
})()`);
|
||||
fs.writeFileSync(path.join(staging, `native-launch-${label}.png`), Buffer.from(nativePng, 'base64'));
|
||||
browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 30000 });
|
||||
browser.contexts()[0].setDefaultTimeout(12000);
|
||||
page = await until(`${label} actual app page`, () => browser.contexts()[0].pages().find(p => p.url().startsWith('app://netcatty/index.html') && !p.url().includes('settings')));
|
||||
await page.locator('[data-section="top-tabs-toolbar-actions"]').waitFor({ timeout: 15000 });
|
||||
await screenshot(`launch-${label}`);
|
||||
return native.version;
|
||||
}
|
||||
async function quit() {
|
||||
if (!app) return;
|
||||
if (inspector) {
|
||||
try { await inspector.eval("setImmediate(() => process.mainModule.require('electron').app.quit()); true"); } catch {}
|
||||
inspector.close(); inspector = null;
|
||||
}
|
||||
// Node inspector must disconnect before Electron can exit normally.
|
||||
assert(await childExit(app, 20000), 'App did not complete normal quit; do not call persistence passed');
|
||||
browser = null; page = null;
|
||||
}
|
||||
async function snapshot() {
|
||||
return page.evaluate(async () => {
|
||||
const read = key => { const value = localStorage.getItem(key); return value ? JSON.parse(value) : null; };
|
||||
const result = { origin: location.origin, legacy: read('netcatty_ai_sessions_v1'), activeMap: read('netcatty_ai_active_session_map_v1'), hosts: read('netcatty_hosts_v1'), databases: await indexedDB.databases(), liveTabs: [...document.querySelectorAll('[data-tab-type="session"]')].map(e => ({ id: e.getAttribute('data-tab-id'), text: e.textContent })) };
|
||||
if (result.databases.some(db => db.name === 'netcatty_ai_sessions')) {
|
||||
result.idb = await new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open('netcatty_ai_sessions');
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => {
|
||||
const db = request.result, tx = db.transaction(['sessions', 'meta'], 'readonly');
|
||||
const sessions = tx.objectStore('sessions').getAll(), meta = tx.objectStore('meta').getAll();
|
||||
tx.oncomplete = () => { db.close(); resolve({ sessions: sessions.result, meta: meta.result }); };
|
||||
tx.onerror = () => { db.close(); reject(tx.error); };
|
||||
};
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
function sessionWith(snapshot, marker) {
|
||||
return (snapshot.idb?.sessions || snapshot.legacy || []).find(s => s.messages.some(m => m.role === 'user' && m.content.includes(marker)));
|
||||
}
|
||||
function messages(session) { return session.messages.filter(m => m.role === 'user' || m.role === 'assistant').map(m => ({ id: m.id, role: m.role, content: m.content, timestamp: m.timestamp })); }
|
||||
async function configureProvider() {
|
||||
await page.locator('[data-section="top-tabs-toolbar-actions"] button:has(svg.lucide-settings)').click();
|
||||
const settings = await until('native settings window', () => browser.contexts()[0].pages().find(p => p.url().includes('settings')));
|
||||
await settings.getByRole('tab', { name: 'AI', exact: true }).click();
|
||||
await settings.getByRole('tab', { name: 'Providers', exact: true }).click();
|
||||
await settings.getByRole('button', { name: 'Add Provider', exact: true }).click();
|
||||
await settings.getByRole('button', { name: 'Custom', exact: true }).click();
|
||||
await settings.getByPlaceholder('e.g. My Provider').fill('QA Loopback');
|
||||
await settings.getByPlaceholder('Enter API key').fill('qa-local-only');
|
||||
await settings.getByPlaceholder('https://', { exact: true }).fill(`http://127.0.0.1:${fixture.port}/v1`);
|
||||
await settings.getByPlaceholder(/Search or type model ID|e\.g\. gpt-4o/).fill('qa-history-fixture');
|
||||
const chat = settings.getByRole('button', { name: 'Chat Completions', exact: true });
|
||||
if (await chat.count()) await chat.click();
|
||||
await settings.getByRole('button', { name: 'Save', exact: true }).click();
|
||||
const enable = settings.getByRole('switch', { checked: false }).first();
|
||||
await enable.click();
|
||||
await until('provider enabled', () => settings.getByRole('switch', { checked: true }).count());
|
||||
// Close via normal native-window control; settings is a real separate window.
|
||||
await settings.getByRole('button', { name: 'Close', exact: true }).click();
|
||||
await page.bringToFront(); event('Configured normal loopback OpenAI provider');
|
||||
}
|
||||
async function saveHost() {
|
||||
await page.getByRole('button', { name: 'New Host', exact: true }).click();
|
||||
await page.getByPlaceholder('Label (e.g., Production Server)', { exact: true }).fill(hostLabel);
|
||||
await page.getByPlaceholder('IP or Hostname', { exact: true }).fill('127.0.0.1');
|
||||
await page.getByPlaceholder('Username', { exact: true }).fill('synthetic-qa');
|
||||
await page.locator('button[aria-label="Save"]').click();
|
||||
await until('GUI saved loopback host', async () => (await snapshot()).hosts?.some(h => h.label === hostLabel && (h.hostname === '127.0.0.1' || h.address === '127.0.0.1')));
|
||||
await page.getByText(hostLabel, { exact: true }).filter({ visible: true }).first().waitFor();
|
||||
event('Synthetic host saved through actual GUI');
|
||||
}
|
||||
async function aiPanel(restore = false) {
|
||||
if (!restore) {
|
||||
await page.keyboard.press('Control+t');
|
||||
await page.locator('.xterm-helper-textarea').first().waitFor({ state: 'attached' });
|
||||
}
|
||||
let panel = page.locator('[data-section="ai-chat-panel"]:visible');
|
||||
if (!(await panel.count())) await page.locator('[data-section="top-tabs-toolbar-actions"] button:has(svg.lucide-sparkles)').click();
|
||||
await panel.waitFor({ state: 'visible' });
|
||||
return panel;
|
||||
}
|
||||
async function send(panel, prompt) {
|
||||
const input = panel.locator('textarea:visible').first();
|
||||
await input.fill(prompt); await input.press('Enter');
|
||||
await panel.getByText(replies.get(prompt), { exact: true }).waitFor({ timeout: 45000 });
|
||||
await until(`stored full reply ${prompt}`, async () => sessionWith(await snapshot(), prompt)?.messages.some(m => m.role === 'assistant' && m.content === replies.get(prompt)), 20000);
|
||||
event('Normal AI turn completed', { prompt, reply: replies.get(prompt) });
|
||||
}
|
||||
async function chooseChat(panel, marker) {
|
||||
await panel.locator('button:has(svg.lucide-history)').click();
|
||||
await panel.getByText(marker, { exact: true }).first().click();
|
||||
await panel.getByText(replies.get(marker), { exact: true }).waitFor();
|
||||
}
|
||||
async function assertChats(baseline, current, afterAppend = false, pointerSource = baseline) {
|
||||
const a = sessionWith(current, 'QA_ALPHA_USER_ONE'), b = sessionWith(current, 'QA_BETA_USER_ONE');
|
||||
assert(a && b, 'Both distinct chats must exist'); assert.notEqual(a.id, b.id);
|
||||
const oldA = sessionWith(baseline, 'QA_ALPHA_USER_ONE'), oldB = sessionWith(baseline, 'QA_BETA_USER_ONE');
|
||||
assert.equal(a.id, oldA.id); assert.equal(b.id, oldB.id);
|
||||
assert.deepEqual(messages(a), messages(oldA), 'Alpha complete turns and identities preserved');
|
||||
assert.deepEqual(messages(b).slice(0, 4), messages(oldB), 'Beta original full turns and identities preserved');
|
||||
assert.equal(messages(b).length, afterAppend ? 6 : 4);
|
||||
if (afterAppend) assert.deepEqual(messages(b).slice(-2).map(m => [m.role, m.content]), [['user', 'QA_BETA_AFTER_UPGRADE'], ['assistant', 'QA_BETA_REPLY_AFTER_UPGRADE']]);
|
||||
assert(current.hosts.some(h => h.id === baseline.hosts.find(h => h.label === hostLabel).id && h.label === hostLabel));
|
||||
assert(current.idb, 'Candidate must use the real AI IndexedDB');
|
||||
assert(current.idb.meta.some(m => m.key === 'migrationCompleted' && m.value?.migrationCompleted === true));
|
||||
const active = current.idb.meta.find(m => m.key === 'activeSessionMap')?.value;
|
||||
assert(active && typeof active === 'object', 'IndexedDB meta.activeSessionMap must exist directly; no legacy fallback');
|
||||
const originalPointerMap = pointerSource.idb ? pointerSource.idb.meta.find(m => m.key === 'activeSessionMap')?.value : pointerSource.activeMap;
|
||||
const activeKey = Object.keys(originalPointerMap || {}).find(key => originalPointerMap[key] === oldB.id);
|
||||
assert.equal(current.origin, baseline.origin, 'Actual app origin must stay identical');
|
||||
assert.deepEqual(a.scope, oldA.scope); assert.deepEqual(b.scope, oldB.scope);
|
||||
const pointer = { phase: afterAppend ? 'restarted' : 'migrated', expectedKey: activeKey, expectedBeta: oldB.id, originalScope: oldB.scope, baselineMap: originalPointerMap, actualIdbMap: active, actualLegacyMap: current.activeMap, baselineLiveTabs: baseline.liveTabs, liveTabs: current.liveTabs };
|
||||
(report.activePointerChecks ||= []).push(pointer);
|
||||
if (!activeKey) {
|
||||
pointer.status = 'untested: no positive pointer persisted by the source GUI';
|
||||
(report.coverageGaps ||= []).push({ phase: pointer.phase, assertion: 'active pointer preservation', reason: pointer.status });
|
||||
} else try {
|
||||
assert.equal(active[activeKey], oldB.id, 'Exact original scope-to-session active pointer preserved');
|
||||
pointer.status = 'passed';
|
||||
} catch (error) {
|
||||
pointer.status = 'failed'; pointer.failure = error.message;
|
||||
(report.validationFailures ||= []).push({ phase: pointer.phase, assertion: 'original active Beta pointer in IndexedDB', message: error.message });
|
||||
process.exitCode = 1;
|
||||
}
|
||||
return { alpha: a.id, beta: b.id, activeMap: active, activePointer: pointer.status, originalRecordsAndScope: 'passed', savedHost: 'passed', alphaMessages: messages(a).length, betaMessages: messages(b).length };
|
||||
}
|
||||
async function main() {
|
||||
assert.equal(process.platform, 'win32');
|
||||
assert(!process.env.GH_TOKEN && !process.env.GITHUB_TOKEN, 'Application/test step must not receive GitHub token');
|
||||
fs.mkdirSync(evidence, { recursive: true }); fs.mkdirSync(staging, { recursive: true });
|
||||
assert(!fs.existsSync(profile), 'Only a fresh QA profile may be seeded');
|
||||
report.processPreflight = osCommand("'QA_WINDOWS_PROCESS_PREFLIGHT'; [Environment]::UserName; [Environment]::OSVersion.VersionString", 10000);
|
||||
event('Windows process preflight passed');
|
||||
watchdog = setTimeout(() => { report.error = 'Harness global timeout'; finish().finally(() => process.exit(1)); }, 11 * 60 * 1000);
|
||||
fixture = await startModel();
|
||||
if (portable) {
|
||||
executable = path.join(root, 'baseline-portable', 'Netcatty.exe');
|
||||
report.baselineInstall = 'not_covered: official ZIP extraction';
|
||||
report.installerReplacement = 'not_covered: separate portable migration job';
|
||||
report.candidateInstall = 'not_covered: official ZIP extraction';
|
||||
} else {
|
||||
assert(await install(path.join(root, pinned.baseline.installer), 'baseline v1.1.90'), 'Baseline NSIS failed'); report.baselineInstall = 'passed';
|
||||
}
|
||||
await launch('baseline', '1.1.90');
|
||||
await configureProvider(); await saveHost();
|
||||
let panel = await aiPanel();
|
||||
await send(panel, 'QA_ALPHA_USER_ONE'); await send(panel, 'QA_ALPHA_USER_TWO');
|
||||
await screenshot('01-baseline-alpha');
|
||||
await panel.locator('button:has(svg.lucide-plus)').first().click();
|
||||
await send(panel, 'QA_BETA_USER_ONE'); await send(panel, 'QA_BETA_USER_TWO');
|
||||
await screenshot('02-baseline-beta-active');
|
||||
// Explicit normal history selection gives the released GUI a bounded chance
|
||||
// to persist Beta before asking the candidate to migrate a positive pointer.
|
||||
await chooseChat(panel, 'QA_ALPHA_USER_ONE');
|
||||
await chooseChat(panel, 'QA_BETA_USER_ONE');
|
||||
let baseline;
|
||||
try {
|
||||
baseline = await until('released GUI positive active Beta pointer', async () => {
|
||||
const value = await snapshot(), beta = sessionWith(value, 'QA_BETA_USER_ONE');
|
||||
return beta && value.activeMap?.[`terminal:${beta.scope.targetId}`] === beta.id && value;
|
||||
}, 4000);
|
||||
report.baselinePointerSeed = { status: 'passed', map: baseline.activeMap };
|
||||
} catch {
|
||||
baseline = await snapshot();
|
||||
report.baselinePointerSeed = { status: 'untested: released GUI did not persist a positive Beta pointer after History Alpha then Beta', map: baseline.activeMap, beta: sessionWith(baseline, 'QA_BETA_USER_ONE')?.id, scope: sessionWith(baseline, 'QA_BETA_USER_ONE')?.scope, liveTabs: baseline.liveTabs };
|
||||
}
|
||||
assert(!baseline.idb, 'Released baseline must exercise legacy-to-IDB migration');
|
||||
assert.equal(messages(sessionWith(baseline, 'QA_ALPHA_USER_ONE')).length, 4);
|
||||
assert.equal(messages(sessionWith(baseline, 'QA_BETA_USER_ONE')).length, 4);
|
||||
fs.writeFileSync(path.join(evidence, 'baseline-storage.json'), JSON.stringify(baseline, null, 2));
|
||||
report.baselineGuiSeed = 'passed'; await quit();
|
||||
if (portable) executable = path.join(root, 'candidate-portable', 'Netcatty.exe');
|
||||
else {
|
||||
const replaced = await install(path.join(root, pinned.installer), 'candidate replacement');
|
||||
if (!replaced) {
|
||||
report.installerReplacement = 'blocked_or_failed: see installer exit/output; CI version is older than 1.1.90';
|
||||
// Normal uninstall/reinstall is separately labelled. Never patch the package
|
||||
// or bypass an official installer version check; keep the custom profile.
|
||||
const uninstall = path.join(installDir, 'Uninstall Netcatty.exe');
|
||||
assert(fs.existsSync(uninstall), 'Normal uninstaller unavailable');
|
||||
assert(await install(uninstall, 'baseline normal uninstall (preserve explicit QA profile)', true));
|
||||
assert(await install(path.join(root, pinned.installer), 'candidate fresh install preserving QA profile'), 'Candidate fresh NSIS failed');
|
||||
report.candidateInstall = 'passed: fresh install after normal baseline uninstall; migration uses original profile';
|
||||
} else { report.installerReplacement = 'passed: normal per-user NSIS replacement'; report.candidateInstall = 'passed'; }
|
||||
}
|
||||
await launch('candidate-after-install', pinned.version);
|
||||
const beforePanel = await until('candidate migration marker before panel navigation', async () => {
|
||||
const value = await snapshot();
|
||||
return value.idb?.meta.some(m => m.key === 'migrationCompleted' && m.value?.migrationCompleted === true) && value;
|
||||
});
|
||||
fs.writeFileSync(path.join(evidence, 'candidate-before-panel-storage.json'), JSON.stringify(beforePanel, null, 2));
|
||||
report.candidateBeforePanel = { activeMap: beforePanel.activeMap, idbMeta: beforePanel.idb?.meta, liveTabs: beforePanel.liveTabs };
|
||||
panel = await aiPanel(true);
|
||||
const migrated = await until('IDB migration completed', async () => {
|
||||
const value = await snapshot();
|
||||
return value.idb?.meta.some(m => m.key === 'migrationCompleted' && m.value?.migrationCompleted === true) && value;
|
||||
});
|
||||
fs.writeFileSync(path.join(evidence, 'candidate-migrated-storage.json'), JSON.stringify(migrated, null, 2));
|
||||
report.migratedChats = await assertChats(baseline, beforePanel);
|
||||
report.afterOpeningPanelActiveMap = migrated.idb?.meta.find(m => m.key === 'activeSessionMap')?.value;
|
||||
report.candidateInitialView = { automaticallyOpenedBeta: await panel.getByText('QA_BETA_REPLY_TWO', { exact: true }).isVisible(), visibleText: await panel.innerText(), policy: 'Stock panelViewByScope is memory-only; exact persisted active pointer checked before any chat selection' };
|
||||
await screenshot('candidate-initial-view-before-history-selection');
|
||||
if (!report.candidateInitialView.automaticallyOpenedBeta) await chooseChat(panel, 'QA_BETA_USER_ONE');
|
||||
await panel.getByText('QA_BETA_REPLY_TWO', { exact: true }).waitFor();
|
||||
await screenshot('03-candidate-beta-active');
|
||||
await chooseChat(panel, 'QA_ALPHA_USER_ONE'); await screenshot('04-candidate-alpha');
|
||||
await chooseChat(panel, 'QA_BETA_USER_ONE');
|
||||
report.aiHistoryMigration = `original records/full turns/scope/host PASSED; active pointer ${report.migratedChats.activePointer}`;
|
||||
await send(panel, 'QA_BETA_AFTER_UPGRADE'); await screenshot('05-candidate-appended');
|
||||
const beforeRestart = pinned.requirePositiveCandidatePointer ? await until('patched candidate persists a positive Beta pointer before quit', async () => {
|
||||
const value = await snapshot(), beta = sessionWith(value, 'QA_BETA_USER_ONE');
|
||||
const map = value.idb?.meta.find(m => m.key === 'activeSessionMap')?.value;
|
||||
return beta && map?.[`${beta.scope.type}:${beta.scope.targetId ?? ''}`] === beta.id && value;
|
||||
}, 5000) : await snapshot();
|
||||
fs.writeFileSync(path.join(evidence, 'candidate-before-quit-storage.json'), JSON.stringify(beforeRestart, null, 2));
|
||||
report.beforeRestartPointer = { idbMap: beforeRestart.idb?.meta.find(m => m.key === 'activeSessionMap')?.value, legacyMap: beforeRestart.activeMap };
|
||||
await quit(); await launch('candidate-restarted', pinned.version);
|
||||
const restartBeforePanel = await snapshot();
|
||||
fs.writeFileSync(path.join(evidence, 'restarted-before-panel-storage.json'), JSON.stringify(restartBeforePanel, null, 2));
|
||||
report.restartBeforePanel = { activeMap: restartBeforePanel.activeMap, idbMeta: restartBeforePanel.idb?.meta, liveTabs: restartBeforePanel.liveTabs };
|
||||
panel = await aiPanel(true);
|
||||
const restarted = await snapshot();
|
||||
fs.writeFileSync(path.join(evidence, 'candidate-restarted-storage.json'), JSON.stringify(restarted, null, 2));
|
||||
report.restartedChats = await assertChats(baseline, restartBeforePanel, true, beforeRestart);
|
||||
report.afterRestartOpeningPanelActiveMap = restarted.idb?.meta.find(m => m.key === 'activeSessionMap')?.value;
|
||||
report.restartInitialView = { automaticallyOpenedBeta: await panel.getByText('QA_BETA_REPLY_AFTER_UPGRADE', { exact: true }).isVisible(), visibleText: await panel.innerText(), policy: 'Report automatic view restoration separately from unchanged IndexedDB active pointer and complete persisted turns' };
|
||||
await screenshot('restarted-initial-view-before-history-selection');
|
||||
if (!report.restartInitialView.automaticallyOpenedBeta) await chooseChat(panel, 'QA_BETA_USER_ONE');
|
||||
await panel.getByText('QA_BETA_REPLY_AFTER_UPGRADE', { exact: true }).waitFor();
|
||||
await screenshot('06-candidate-restarted');
|
||||
report.restartPersistence = `original and appended turns/scope/host PASSED; active pointer ${report.restartedChats.activePointer}`;
|
||||
report.targetedCandidateRestartRegression = report.restartedChats.activePointer === 'passed' ? 'passed: positive candidate-created IDB Beta pointer and full new/original contents survived complete restart' : 'failed or untested: read activePointerChecks';
|
||||
report.overall = report.validationFailures?.length ? 'failed: read individual validation failures' : report.coverageGaps?.length ? 'partial: independent data assertions passed; positive legacy pointer not available' : 'passed';
|
||||
await quit(); event('Windows installed real GUI acceptance completed');
|
||||
}
|
||||
let finishing;
|
||||
async function finish() {
|
||||
if (finishing) return finishing;
|
||||
finishing = (async () => {
|
||||
clearTimeout(watchdog);
|
||||
if ((report.error || report.validationFailures?.length) && browser) {
|
||||
for (const [index, target] of browser.contexts()[0].pages().entries()) {
|
||||
try { await screenshot(`failure-${index}`, target); } catch {}
|
||||
try {
|
||||
const text = await target.locator('body').innerText({ timeout: 3000 });
|
||||
fs.writeFileSync(path.join(evidence, `failure-${index}-visible-ui.txt`), text);
|
||||
(report.failureVisibleUI ||= []).push({ page: index, text: text.slice(-14000) });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
if (report.error && app && !browser) report.nativeFailureDiagnostic = installerDiagnostic('application-launch-failure', app.pid);
|
||||
try { await quit(); } catch (error) { report.cleanupError = error.message; app?.kill(); }
|
||||
if (fixture) { fixture.server.closeAllConnections(); fixture.server.close(); report.modelCalls = fixture.calls; }
|
||||
const stderr = logs.join('\n');
|
||||
// Only synthetic app data and no tokens/credentials may leave this runner.
|
||||
const secretPattern = /(?:gh[opsu]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|-----BEGIN (?:RSA |OPENSSH )?PRIVATE KEY-----|Bearer\s+(?!qa-local-only)[A-Za-z0-9_.-]{20,})/i;
|
||||
report.evidenceReview = secretPattern.test(stderr) ? 'failed: raw app logs and PNGs withheld' : 'passed: app logs checked for credential patterns; only known synthetic GUI data';
|
||||
if (!secretPattern.test(stderr)) {
|
||||
fs.writeFileSync(path.join(evidence, 'app-output.log'), stderr);
|
||||
console.log('Reviewed actual application output:\n' + stderr);
|
||||
for (const file of fs.readdirSync(staging)) fs.copyFileSync(path.join(staging, file), path.join(evidence, file));
|
||||
} else { report.error ||= 'Evidence sensitive-data review failed'; process.exitCode = 1; }
|
||||
fs.writeFileSync(path.join(evidence, 'assertions.json'), JSON.stringify(report, null, 2));
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
})();
|
||||
return finishing;
|
||||
}
|
||||
main().catch(error => { report.error = error.stack; process.exitCode = 1; }).finally(finish);
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"repository": "binaricat/Netcatty",
|
||||
"repositoryId": 1111357457,
|
||||
"sha": "4516d3aed7cb54862dabd53abb56a7f90fba3212",
|
||||
"base": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
|
||||
"sourcePr": 4302,
|
||||
"qaBuilt": true,
|
||||
"requirePositiveCandidatePointer": true,
|
||||
"version": "0.0.0-sha-4516d3a",
|
||||
"installer": "Netcatty-0.0.0-sha-4516d3a-win-x64.exe",
|
||||
"baseline": {
|
||||
"tag": "v1.1.90",
|
||||
"asset": 677167660,
|
||||
"installer": "Netcatty-1.1.90-win-x64.exe",
|
||||
"sha256": "cf6a028a0286264fd1e315025b1f78e8c96c468d6a22d5058b64319410debdc9",
|
||||
"url": "https://github.com/binaricat/Netcatty/releases/download/v1.1.90/Netcatty-1.1.90-win-x64.exe"
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "netcatty-official-windows-qa",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "netcatty-official-windows-qa",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.56.1"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.56.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
|
||||
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "netcatty-official-windows-qa",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"description": "QA-only native installed Windows application acceptance",
|
||||
"dependencies": { "playwright-core": "1.56.1" }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Token is scoped to public release metadata/download in this step only.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { Readable } = require('node:stream');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const pinned = require('./fixed-candidate.json');
|
||||
const root = path.resolve(process.env.QA_ROOT);
|
||||
const artifact = path.resolve(process.env.QA_FIXED_ARTIFACT);
|
||||
async function digest(file) { const hash = crypto.createHash('sha256'); for await (const part of fs.createReadStream(file)) hash.update(part); return hash.digest('hex'); }
|
||||
async function main() {
|
||||
fs.mkdirSync(path.join(root, 'evidence'), { recursive: true });
|
||||
const build = JSON.parse(fs.readFileSync(path.join(artifact, 'build-provenance.json')));
|
||||
assert.equal(build.repository, pinned.repository); assert.equal(build.sha, pinned.sha);
|
||||
assert.equal(build.status, 'passed'); assert.equal(build.logReview.startsWith('passed'), true);
|
||||
assert.equal(build.run, process.env.GITHUB_RUN_ID); assert.equal(build.qaHead, process.env.QA_HEAD_SHA);
|
||||
assert.equal(build.versionMetadata, pinned.version);
|
||||
assert.equal(build.installerSha256, process.env.QA_EXPECTED_INSTALLER_SHA);
|
||||
assert.equal(await digest(path.join(artifact, pinned.installer)), process.env.QA_EXPECTED_INSTALLER_SHA);
|
||||
fs.copyFileSync(path.join(artifact, pinned.installer), path.join(root, pinned.installer));
|
||||
const response = await fetch(`https://api.github.com/repos/${pinned.repository}/releases/tags/${pinned.baseline.tag}`, { headers: { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json' }, signal: AbortSignal.timeout(30000) });
|
||||
assert(response.ok);
|
||||
const release = await response.json(), asset = release.assets.find(a => a.id === pinned.baseline.asset);
|
||||
assert.equal(asset?.name, pinned.baseline.installer); assert.equal(asset.digest, `sha256:${pinned.baseline.sha256}`); assert.equal(asset.browser_download_url, pinned.baseline.url);
|
||||
const baseline = await fetch(pinned.baseline.url, { signal: AbortSignal.timeout(120000) });
|
||||
assert(baseline.ok);
|
||||
await pipeline(Readable.fromWeb(baseline.body), fs.createWriteStream(path.join(root, pinned.baseline.installer)));
|
||||
assert.equal(await digest(path.join(root, pinned.baseline.installer)), pinned.baseline.sha256);
|
||||
fs.writeFileSync(path.join(root, 'evidence/provenance.json'), JSON.stringify({ ...pinned, build, buildArtifactId: process.env.QA_BUILD_ARTIFACT_ID, buildArtifactDigest: process.env.QA_BUILD_ARTIFACT_DIGEST, baselineVerifiedSha256: pinned.baseline.sha256, testPackageOrigin: 'Exact trusted patch SHA, CI QA-built NSIS; unsigned/unreleased, not official release/updater acceptance' }, null, 2));
|
||||
console.log(JSON.stringify({ fixedSha: pinned.sha, installerSha256: build.installerSha256, baselineSha256: pinned.baseline.sha256, buildArtifact: process.env.QA_BUILD_ARTIFACT_ID }, null, 2));
|
||||
}
|
||||
main().catch(error => { console.error(error.stack); process.exitCode = 1; });
|
||||
@@ -0,0 +1,104 @@
|
||||
// Only this downloader receives the standard Actions read token.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { Readable } = require('node:stream');
|
||||
const { pipeline } = require('node:stream/promises');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const pinned = require('./candidate.json');
|
||||
const portable = process.env.QA_MODE === 'portable';
|
||||
const baseline = portable ? pinned.portableBaseline : pinned.baseline;
|
||||
const entry = portable ? pinned.portableZip : pinned.installer;
|
||||
const root = path.resolve(process.env.QA_ROOT);
|
||||
const evidence = path.join(root, 'evidence');
|
||||
const digest = async file => {
|
||||
const hash = crypto.createHash('sha256');
|
||||
for await (const part of fs.createReadStream(file)) hash.update(part);
|
||||
return hash.digest('hex');
|
||||
};
|
||||
async function download(response, file) {
|
||||
assert(response.ok, `Download HTTP ${response.status}`);
|
||||
await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(file));
|
||||
}
|
||||
async function main() {
|
||||
assert.equal(process.platform, 'win32');
|
||||
assert(process.env.GH_TOKEN);
|
||||
fs.mkdirSync(evidence, { recursive: true });
|
||||
const base = `https://api.github.com/repos/${pinned.repository}`;
|
||||
const headers = { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
|
||||
async function api(route) {
|
||||
const response = await fetch(base + route, { headers, signal: AbortSignal.timeout(30000) });
|
||||
assert(response.ok, `GitHub metadata HTTP ${response.status}`);
|
||||
return response.json();
|
||||
}
|
||||
const run = await api(`/actions/runs/${pinned.run}`);
|
||||
assert.equal(run.head_sha, pinned.sha);
|
||||
assert.equal(run.repository.id, pinned.repositoryId);
|
||||
assert.equal(run.head_repository.id, pinned.repositoryId);
|
||||
assert.equal(run.head_branch, 'main');
|
||||
assert.equal(run.event, 'push');
|
||||
assert.equal(run.path, '.github/workflows/build.yml');
|
||||
const jobs = await api(`/actions/runs/${pinned.run}/jobs?per_page=100`);
|
||||
const job = jobs.jobs.find(item => item.name === 'build-windows');
|
||||
assert.equal(job?.conclusion, 'success');
|
||||
const artifact = await api(`/actions/artifacts/${pinned.artifact}`);
|
||||
assert.equal(artifact.name, pinned.name);
|
||||
assert.equal(artifact.expired, false);
|
||||
assert.equal(artifact.workflow_run.id, pinned.run);
|
||||
assert.equal(artifact.workflow_run.head_sha, pinned.sha);
|
||||
assert.equal(artifact.workflow_run.head_repository_id, pinned.repositoryId);
|
||||
assert.equal(artifact.digest, `sha256:${pinned.zipSha256}`);
|
||||
const release = await api(`/releases/tags/${baseline.tag}`);
|
||||
const asset = release.assets.find(item => item.id === baseline.asset);
|
||||
assert.equal(asset?.name, baseline.installer);
|
||||
assert.equal(asset.digest, `sha256:${baseline.sha256}`);
|
||||
assert.equal(asset.browser_download_url, baseline.url);
|
||||
await download(await fetch(baseline.url, { signal: AbortSignal.timeout(120000) }), path.join(root, baseline.installer));
|
||||
assert.equal(await digest(path.join(root, baseline.installer)), baseline.sha256);
|
||||
const response = await fetch(`${base}/actions/artifacts/${pinned.artifact}/zip`, { headers, redirect: 'manual', signal: AbortSignal.timeout(30000) });
|
||||
assert.equal(response.status, 302);
|
||||
const location = new URL(response.headers.get('location'));
|
||||
assert.equal(location.protocol, 'https:');
|
||||
// Never forward the token to the signed artifact blob or to installers/apps.
|
||||
const zip = path.join(root, 'official.zip');
|
||||
await download(await fetch(location, { signal: AbortSignal.timeout(180000) }), zip);
|
||||
assert.equal(await digest(zip), pinned.zipSha256);
|
||||
const extract = `Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$z = [IO.Compression.ZipFile]::OpenRead($env:QA_ZIP)
|
||||
try {
|
||||
$entries = @($z.Entries | Where-Object { $_.FullName -eq $env:QA_INSTALLER })
|
||||
if ($entries.Count -ne 1) { throw 'Expected exactly one pinned NSIS entry' }
|
||||
[IO.Compression.ZipFileExtensions]::ExtractToFile($entries[0], $env:QA_OUTPUT, $false)
|
||||
} finally { $z.Dispose() }`;
|
||||
execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', extract], {
|
||||
env: { ...process.env, GH_TOKEN: '', QA_ZIP: zip, QA_INSTALLER: entry, QA_OUTPUT: path.join(root, entry) }, timeout: 30000,
|
||||
});
|
||||
if (portable) {
|
||||
const unpack = `Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$destination = [IO.Path]::GetFullPath($env:QA_DEST) + [IO.Path]::DirectorySeparatorChar
|
||||
$z = [IO.Compression.ZipFile]::OpenRead($env:QA_ARCHIVE)
|
||||
try { foreach ($e in $z.Entries) {
|
||||
$target = [IO.Path]::GetFullPath([IO.Path]::Combine($destination,$e.FullName))
|
||||
if (-not $target.StartsWith($destination,[StringComparison]::OrdinalIgnoreCase)) { throw 'ZIP path outside isolated root' }
|
||||
if ($e.Name -eq '') { [void][IO.Directory]::CreateDirectory($target) }
|
||||
else { [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($target)); [IO.Compression.ZipFileExtensions]::ExtractToFile($e,$target,$false) }
|
||||
}} finally { $z.Dispose() }`;
|
||||
for (const [archive, dest] of [[baseline.installer, 'baseline-portable'], [entry, 'candidate-portable']]) {
|
||||
execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', unpack], { env: { ...process.env, GH_TOKEN: '', QA_ARCHIVE: path.join(root, archive), QA_DEST: path.join(root, dest) }, timeout: 60000 });
|
||||
assert(fs.existsSync(path.join(root, dest, 'Netcatty.exe')));
|
||||
}
|
||||
}
|
||||
const provenance = {
|
||||
...pinned, mode: process.env.QA_MODE || 'nsis', testedBaseline: baseline,
|
||||
officialWindowsJob: job.id, verifiedAt: new Date().toISOString(),
|
||||
candidateEntry: entry, candidateEntrySha256: await digest(path.join(root, entry)),
|
||||
candidateEntryDigestSource: 'Computed from exact entry in verified official artifact ZIP',
|
||||
baselineMode: portable ? 'Public released Windows ZIP, extraction only' : 'Public released NSIS installer',
|
||||
candidateMode: portable ? 'Official CI Windows ZIP, extraction only; no installer/updater coverage' : 'Official CI NSIS installer; prerelease version, not released updater acceptance',
|
||||
};
|
||||
fs.writeFileSync(path.join(evidence, 'provenance.json'), JSON.stringify(provenance, null, 2));
|
||||
console.log(JSON.stringify(provenance, null, 2));
|
||||
console.log(`Verified ${pinned.baseline.tag} and official ${pinned.sha}, artifact ${pinned.artifact}`);
|
||||
}
|
||||
main().catch(error => { console.error(error.message); process.exitCode = 1; });
|
||||
@@ -0,0 +1,85 @@
|
||||
"use strict";
|
||||
/* global process, __dirname, console */
|
||||
if (!process.versions.electron) {
|
||||
require("node:test")("RTL DOM cell geometry", { skip: "run with Electron" }, () => {});
|
||||
} else {
|
||||
const { app, BrowserWindow } = require("electron");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { buildSync } = require("esbuild");
|
||||
const profile = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-rtl-width-"));
|
||||
app.setPath("userData", profile);
|
||||
app.on("window-all-closed", () => {});
|
||||
const bundle = buildSync({
|
||||
stdin: {
|
||||
contents: 'export { Terminal } from "@xterm/xterm"; export { findRightToLeftRuns } from "./components/terminal/runtime/terminalBidiJoiner";',
|
||||
resolveDir: path.resolve(__dirname, ".."),
|
||||
},
|
||||
bundle: true, format: "iife", globalName: "rtlTest", platform: "browser", write: false,
|
||||
}).outputFiles[0].text;
|
||||
let win;
|
||||
function finish(code) {
|
||||
win?.destroy();
|
||||
app.exit(code);
|
||||
}
|
||||
void app.whenReady().then(async () => {
|
||||
win = new BrowserWindow({ show: true, width: 600, height: 320 });
|
||||
await win.loadURL("data:text/html,<div id='terminal' style='width:500px;height:260px'></div>");
|
||||
await win.webContents.insertCSS(fs.readFileSync(require.resolve("@xterm/xterm/css/xterm.css"), "utf8"));
|
||||
const measurement = await win.webContents.executeJavaScript(`(async () => {
|
||||
${bundle}
|
||||
const fontFamily = '"Noto Sans Mono", "DejaVu Sans", monospace';
|
||||
const term = new rtlTest.Terminal({cols: 30, rows: 8, fontSize: 24, fontFamily, allowProposedApi: true});
|
||||
term.open(document.querySelector("#terminal"));
|
||||
term.registerCharacterJoiner(text => text.startsWith("ffi") ? [[0, 3]] : rtlTest.findRightToLeftRuns(text));
|
||||
const a = "יייייייי", b = "שששששששש";
|
||||
const ctx = document.createElement("canvas").getContext("2d");
|
||||
ctx.font = "24px " + fontFamily;
|
||||
await new Promise(resolve => term.write(a + " Z\\r\\n" + b + " Z\\r\\n01234567 Z\\r\\nffi Z\\r\\n", resolve));
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
const rows = [...document.querySelectorAll(".xterm-rows > div")].slice(0, 4);
|
||||
const geometry = rows.map(row => {
|
||||
const spans = [...row.children];
|
||||
const suffix = spans.find(span => span.textContent.includes("Z"));
|
||||
const content = spans[0].firstElementChild ?? spans[0];
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(content);
|
||||
const glyphs = range.getBoundingClientRect();
|
||||
const cellBox = spans[0].getBoundingClientRect();
|
||||
return {
|
||||
glyphWidth: glyphs.width,
|
||||
glyphRight: glyphs.right - cellBox.left,
|
||||
transform: content.style.transform,
|
||||
marker: suffix.getBoundingClientRect().right - row.getBoundingClientRect().left,
|
||||
joinedWidth: spans[0].getBoundingClientRect().width,
|
||||
text: row.textContent,
|
||||
first: spans[0].textContent,
|
||||
widthStyle: spans[0].style.width,
|
||||
overflow: spans[0].style.overflow,
|
||||
};
|
||||
});
|
||||
return { geometry, cell: term._core._renderService.dimensions.css.cell.width, natural: [ctx.measureText(a).width, ctx.measureText(b).width] };
|
||||
})()`);
|
||||
console.log(JSON.stringify(measurement));
|
||||
const [thin, wide, ascii, ligature] = measurement.geometry;
|
||||
assert.equal(ligature.first, "ffi");
|
||||
assert.equal(ligature.widthStyle, "", "ASCII ligatures must keep their existing layout");
|
||||
assert.equal(ligature.overflow, "", "ASCII ligature overhang must not be clipped");
|
||||
// Ensure the fixture actually exercises unequal font metrics rather than
|
||||
// passing accidentally on a monospace/fallback-only test environment.
|
||||
assert.ok(Math.abs(measurement.natural[0] - measurement.natural[1]) > 8);
|
||||
assert.ok(measurement.natural[1] > measurement.cell * 8 + 8, "wide fallback must exceed its cell allocation");
|
||||
assert.notEqual(wide.transform, "", "nominally oversized RTL glyphs must actually fit, not just clip");
|
||||
assert.equal(wide.overflow, "", "RTL text must not be hidden by overflow clipping");
|
||||
assert.ok(wide.glyphRight <= wide.joinedWidth + 1, JSON.stringify(measurement));
|
||||
assert.equal(thin.transform, "", "narrow RTL text must not be unnecessarily rescaled");
|
||||
for (const row of [thin, wide]) {
|
||||
assert.match(row.text, / Z/);
|
||||
assert.ok(Math.abs(row.joinedWidth - measurement.cell * 8) <= 1, JSON.stringify(measurement));
|
||||
assert.ok(Math.abs(row.marker - ascii.marker) <= 1, JSON.stringify(measurement));
|
||||
}
|
||||
finish(0);
|
||||
}).catch(error => { console.error(error); finish(1); });
|
||||
}
|
||||
@@ -11,7 +11,8 @@ Use the Netcatty MCP tools whenever the task targets Netcatty or a remote sessio
|
||||
|
||||
- For terminal work, call `get_environment` first. Select the current target by its label or hostname and pass its `sessionId` to terminal tools.
|
||||
- Never use the local shell for commands intended for a Netcatty session.
|
||||
- If a required specialized tool is not visible, call `load_netcatty_tools` with `attachments`, `sftp_advanced`, `vault_hosts`, `vault_notes`, `snippets`, `scripts`, or `portforward`. Use `all` only when several categories are needed.
|
||||
- If a required specialized tool is not visible, call `load_netcatty_tools` with `sessions`, `attachments`, `sftp_advanced`, `vault_hosts`, `vault_notes`, `snippets`, `scripts`, or `portforward`. Use `all` only when several categories are needed.
|
||||
- For disconnected sessions already in scope, load `sessions` and use `session_reconnect` / `session_recover` instead of `host_open`, which creates a new tab.
|
||||
- If no live session matches, use `vault_hosts_list` and `host_open`. A newly opened tab lands in your own bound workspace by default (workspace chat → that workspace; terminal chat → that terminal's workspace); only pass `workspaceId` when the user asks for a different target. Close only sessions opened for the current task when they are no longer needed.
|
||||
- Use `terminal_execute` for short commands. Use `terminal_start`, `terminal_poll`, and `terminal_stop` for long-running or streaming commands.
|
||||
- Treat Netcatty permission denials and tool errors as authoritative. Do not bypass them with local commands or alternate connection tools.
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
declare module "bidi-js" {
|
||||
interface BidiParagraph {
|
||||
start: number;
|
||||
end: number;
|
||||
level: number;
|
||||
}
|
||||
|
||||
interface BidiEmbeddingLevels {
|
||||
levels: Uint8Array;
|
||||
paragraphs: BidiParagraph[];
|
||||
}
|
||||
|
||||
interface Bidi {
|
||||
getBidiCharTypeName(char: string): string;
|
||||
getEmbeddingLevels(text: string, baseDirection?: "ltr" | "rtl"): BidiEmbeddingLevels;
|
||||
}
|
||||
|
||||
export default function bidiFactory(): Bidi;
|
||||
}
|
||||
Reference in new issue
Block a user