diff --git a/.github/actions/cloud-sql-rollout-lease/action-contract.test.mjs b/.github/actions/cloud-sql-rollout-lease/action-contract.test.mjs deleted file mode 100644 index 4acfc3552da..00000000000 --- a/.github/actions/cloud-sql-rollout-lease/action-contract.test.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { test } from 'node:test' - -const here = new URL('./', import.meta.url) -const action = readFileSync(new URL('action.yml', here), 'utf8') - -test('is a node24 JavaScript action with an always-run post step', () => { - // A composite action has no `post:`, so the lease could never be released on cancel or failure. - assert.match(action, /^ {2}using: node24$/m) - assert.doesNotMatch(action, /using: composite/) - assert.match(action, /^ {2}main: main\.mjs$/m) - assert.match(action, /^ {2}post: post\.mjs$/m) - assert.match(action, /^ {2}post-if: always\(\)$/m) -}) - -test('declares the inputs the wave-chain callers depend on', () => { - for (const input of ['bucket:', 'object:', 'holder-key:', 'release:']) { - assert.match(action, new RegExp(`^ {2}${input}$`, 'm'), input) - } - assert.match(action, /default: \$\{\{ github\.repository \}\}\/\$\{\{ github\.run_id \}\}/) - assert.match(action, /default: 'true'/) -}) diff --git a/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs b/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs index 73d1a1e6e78..469f64291d4 100644 --- a/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs +++ b/.github/actions/cloud-sql-rollout-lease/storage-lease.test.mjs @@ -234,18 +234,6 @@ test('fails closed when the bucket answers 5xx', async () => { assert.equal(storage.state.requests.filter((request) => request.method !== 'GET').length, 0) }) -test('fails closed when permission is denied', async () => { - const storage = fakeStorage({ - faults: [{ when: (request) => request.method === 'GET', status: 403 }] - }) - - const error = await leaseFor(storage) - .acquire(HOLDER) - .catch((thrown) => thrown) - - assert.match(error.message, /lease inspection failed: 403/) -}) - test('treats an unreadable record as held, not free', async () => { const storage = fakeStorage({ object: { generation: '1500', body: { holder_key: 'stablyai/orca/9001' } } diff --git a/.github/workflows/orca-server-artifact.yml b/.github/workflows/orca-server-artifact.yml new file mode 100644 index 00000000000..2840ad7caa7 --- /dev/null +++ b/.github/workflows/orca-server-artifact.yml @@ -0,0 +1,133 @@ +name: Server-only Linux artifact + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - 'config/scripts/orcad-distribution/server-artifact/**' + - '.github/workflows/orca-server-artifact.yml' + # The launcher relies on how the CLI picks and starts its serve runtime. + - 'src/cli/runtime/launch.ts' + - 'src/cli/runtime/orca-app-executable.ts' + - 'src/cli/runtime/serve-orcad-launch.ts' + - 'src/shared/orcad-local-serve-selection.ts' + - 'src/shared/orcad-artifacts.ts' + # Catch serve regressions on main between releases. + schedule: + - cron: '45 11 * * *' + workflow_dispatch: + # Releases pass the qualified template this run already built, so the tarball ships its exact bytes. + workflow_call: + inputs: + ref: + description: Git ref to check out, e.g. the release tag + type: string + required: true + template_artifact: + description: Name of this run's qualified orcad-template artifact; blank builds the host slot + type: string + default: '' + outputs: + packed: + description: "'true' when both tarballs were packed and passed the smoke" + value: ${{ jobs.package.outputs.packed }} + +permissions: + contents: read + +concurrency: + group: orca-server-artifact-${{ inputs.ref && format('run-{0}', github.run_id) || github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ !inputs.ref }} + +jobs: + package: + if: github.event_name != 'pull_request' || github.event.pull_request.draft != true + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + runner: ubuntu-24.04 + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + permissions: + contents: read + actions: read + env: + ORCA_BACKGROUND_LAUNCH: '1' + TARGET: linux-${{ matrix.arch }}-glibc + outputs: + packed: ${{ steps.smoke.outcome == 'success' }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + # A release cut from a ref older than this workflow has nothing to pack; skip instead of failing. + - name: Check the ref can pack the tarball + id: supported + run: | + if [ -f config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs ]; then + echo 'supported=true' >> "$GITHUB_OUTPUT" + else + echo '::notice::This ref predates the server-only tarball; skipping it.' + fi + - uses: ./.github/actions/install-node-dependencies + if: steps.supported.outputs.supported == 'true' + with: + cache-pnpm-store: ${{ !inputs.ref }} + - name: Use the qualified release template + if: steps.supported.outputs.supported == 'true' && inputs.template_artifact != '' + uses: actions/download-artifact@v8 + with: + name: ${{ inputs.template_artifact }} + path: out/orcad-template + # Without a release template, build this runner's slot the way the desktop template does. + - uses: ./.github/actions/build-mobile-web-bundle + if: steps.supported.outputs.supported == 'true' && inputs.template_artifact == '' + - name: Build this runner's template slot + if: steps.supported.outputs.supported == 'true' && inputs.template_artifact == '' + run: pnpm build:orcad-template --targets "$TARGET" + - name: Pack the tarball + if: steps.supported.outputs.supported == 'true' + run: | + pnpm build:packages + SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)" node config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs --template out/orcad-template --target "$TARGET" --out-dir out/orca-server + { + echo "### orca-server-linux-${{ matrix.arch }}" + echo '```' + ls -l out/orca-server + cat out/orca-server/*.sha256 + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + - name: Start and pair on the runner + if: steps.supported.outputs.supported == 'true' + run: node config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs --archive "out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz" + # Bare images with no Node, display, GTK or X11: the tarball's own Node runs the smoke. + - name: Start and pair on minimal images + id: smoke + if: steps.supported.outputs.supported == 'true' + run: | + for image in ubuntu:24.04 debian:12-slim; do + echo "::group::$image" + docker run --rm --init \ + -v "$PWD/out/orca-server:/artifacts:ro" \ + -v "$PWD/config/scripts/orcad-distribution/server-artifact:/smoke:ro" \ + "$image" sh -ec ' + mkdir -p /tmp/runtime + tar -xzf /artifacts/orca-server-linux-${{ matrix.arch }}.tar.gz -C /tmp/runtime --strip-components=1 + /tmp/runtime/runtimes/node-*/bin/node /smoke/smoke-orcad-server-artifact.mjs --archive /artifacts/orca-server-linux-${{ matrix.arch }}.tar.gz + ' + echo '::endgroup::' + done + - uses: actions/upload-artifact@v7 + if: steps.supported.outputs.supported == 'true' + with: + name: orca-server-linux-${{ matrix.arch }} + path: | + out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz + out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz.sha256 + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index ffc61def51f..01ed0b8ffe1 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -1039,6 +1039,21 @@ jobs: ref: refs/tags/${{ needs.cut.outputs.tag }} fast_runners: false + # Server-only Linux tarballs from the same qualified template. Nothing depends on this job, so a + # failure here never holds the desktop release. + orca-server-artifact: + needs: + - cut + - orcad-template + if: ${{ !cancelled() && needs.cut.outputs.should_release == 'true' && needs.orcad-template.result == 'success' }} + permissions: + contents: read + actions: read + uses: ./.github/workflows/orca-server-artifact.yml + with: + ref: refs/tags/${{ needs.cut.outputs.tag }} + template_artifact: orcad-template + # Gate SignPath artifact requests behind blocking tests to avoid approvals for unpublishable builds. release-preflight: needs: @@ -2241,6 +2256,39 @@ jobs: --prerelease="$prerelease" \ --repo "$GITHUB_REPOSITORY" + # After publish: the draft's asset checks and undraft never see these, and a failure here only + # leaves the server tarballs missing from an already published release. + publish-orca-server-artifact: + needs: + - cut + - publish-release + - orca-server-artifact + if: ${{ !cancelled() && needs.publish-release.result == 'success' && needs.orca-server-artifact.result == 'success' && needs.orca-server-artifact.outputs.packed == 'true' && needs.cut.outputs.tag != '' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/download-artifact@v8 + with: + pattern: orca-server-linux-* + path: orca-server + merge-multiple: true + - name: Write the checksum manifest and upload + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ needs.cut.outputs.tag }} + working-directory: orca-server + run: | + set -euo pipefail + cat orca-server-linux-x64.tar.gz.sha256 orca-server-linux-arm64.tar.gz.sha256 > orca-server-sha256sums.txt + sha256sum -c orca-server-sha256sums.txt + gh release upload "$TAG" \ + orca-server-linux-x64.tar.gz \ + orca-server-linux-arm64.tar.gz \ + orca-server-sha256sums.txt \ + --clobber --repo "$GITHUB_REPOSITORY" + post-release-e2e: needs: - cut diff --git a/cloud/dev/scripts/run-relay-tests.test.mjs b/cloud/dev/scripts/run-relay-tests.test.mjs index 1f806f183dc..70a332ea205 100644 --- a/cloud/dev/scripts/run-relay-tests.test.mjs +++ b/cloud/dev/scripts/run-relay-tests.test.mjs @@ -110,8 +110,7 @@ for (const [name, options] of [ { env: { ORCA_IDLE_REHOME_POSTGRES_URL: 'postgres://localhost:55440/relay' } } ], ['application database', { env: { DATABASE_URL: databaseUrl } }], - ['one CPU', { parallelism: 1 }], - ['two CPUs', { parallelism: 2 }] + ['one CPU', { parallelism: 1 }] ]) { test(`retains the original single run for ${name}`, async (t) => { const h = start(t, options) diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 6c0afd8ee14..67ce4cfb757 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -560,7 +560,7 @@ 1 test-no-wall-clock:src/main/pty/history/terminal-history-gc-fs-call-count.test.ts 2 test-no-wall-clock:src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts 4 test-no-wall-clock:src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts -17 test-no-wall-clock:src/main/rate-limits/service/service-account-target-selection.test.ts +5 test-no-wall-clock:src/main/rate-limits/service/service-account-target-selection.test.ts 1 test-no-wall-clock:src/main/rate-limits/service/service-cursor-usage.test.ts 3 test-no-wall-clock:src/main/rate-limits/service/service-minimax-usage.test.ts 3 test-no-wall-clock:src/main/rate-limits/service/service-refresh-orchestration.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 406884c510d..00b3edcbd75 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2175,13 +2175,13 @@ "providers": ["local", "daemon", "wsl", "ssh", "remote-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": [], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/pty-connection/main-pane-start-wait.test.ts: Loses joined waiter invocation/failure notification and raw terminal error/paired-host readable sentence alarms; survivors preserve hold detection and card clearing. deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/pty-connection-pi-synchronized-input.test.ts: Loses typed-input forced synchronized-frame presentation alarm; setup implements the parser behavior it claims to exercise. deletes src/renderer/src/components/terminal-pane/pty-connection-unserved-ssh-pane.test.ts: Loses automatic SSH dial deduplication, passphrase gating, stale pane exclusion, and disposal cancellation alarms. deletes src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts: Loses source grid before frame and destination grid restoration ordering alarm. deletes src/renderer/src/components/terminal-pane/pty-connection-restart-replacement.spec.ts: Loses wrapper-level hidden/visible restart resume, dispose/rebind suppression and finished-turn replay alarms; manual pipeline and mock-implemented binding invalidate the whole callbacks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1391 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): macOS daemon-backed Electron journey verifies same PID and terminal identity plus rendered output. Focused renderer contracts pass on Linux, Windows and WSL. Neighboring SSH model and replay contracts pass locally; no new live SSH or paired-runtime journey. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-unanswered-command-finish.spec.ts removed. Unanswered SSH shell finish keeps/drops mocked agent row matrix disappears. src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. src/renderer/src/components/terminal-pane/pty-connection-command-input-agent-identity.spec.ts removed. Typed Droid versus process/launch identity and SSH/runtime process-evidence matrices disappear. src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts removed. Success/no-ID/expired/superseded attach-settlement bag alarms disappear. src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts reduced. Every-write kind forwarding and synchronous driving-attempt observer/rejection/ACK call counts disappear. src/renderer/src/components/terminal-pane/pty-connection-codex-restart-input-lookup.spec.ts removed. No global tab enumeration on ordinary/stale input and known restart notice input-block mock-call alarms. src/renderer/src/components/terminal-pane/pty-connection-layout-owner-wake.test.ts removed. Hidden-to-visible single-pane start request, attach-only argument and negative local wake-record alarms are intentionally dropped; no real server wake/ack occurs. src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts reduced. Internal searched-character budget and ordinary/malformed no-op controls. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1369: src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.ts removed. Rootless/removed/moved tabs, missing leaves, queued deletion and host-qualified/legacy deletion eligibility fixtures. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/renderer/src/components/terminal-pane/pty-connection/terminal-input-echo-delay.test.ts reduced. Removes two fabricated-binding pipeline registrations; retains timestamp-policy outcomes without wall-clock speed assertions. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. src/renderer/src/components/terminal-pane/pty-connection/main-pane-resume-banner.test.ts reduced. Loses subscription-budget and attach-start generation predicate alarms; actual restored-banner renderer is not exercised. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", + "coverageNotes": "Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/pty-connection/main-pane-start-wait.test.ts: Loses joined waiter invocation/failure notification and raw terminal error/paired-host readable sentence alarms; survivors preserve hold detection and card clearing. deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/pty-connection-pi-synchronized-input.test.ts: Loses typed-input forced synchronized-frame presentation alarm; setup implements the parser behavior it claims to exercise. deletes src/renderer/src/components/terminal-pane/pty-connection-unserved-ssh-pane.test.ts: Loses automatic SSH dial deduplication, passphrase gating, stale pane exclusion, and disposal cancellation alarms. deletes src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts: Loses source grid before frame and destination grid restoration ordering alarm. deletes src/renderer/src/components/terminal-pane/pty-connection-restart-replacement.spec.ts: Loses wrapper-level hidden/visible restart resume, dispose/rebind suppression and finished-turn replay alarms; manual pipeline and mock-implemented binding invalidate the whole callbacks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1391 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): macOS daemon-backed Electron journey verifies same PID and terminal identity plus rendered output. Focused renderer contracts pass on Linux, Windows and WSL. Neighboring SSH model and replay contracts pass locally; no new live SSH or paired-runtime journey. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-unanswered-command-finish.spec.ts removed. Unanswered SSH shell finish keeps/drops mocked agent row matrix disappears. src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. src/renderer/src/components/terminal-pane/pty-connection-command-input-agent-identity.spec.ts removed. Typed Droid versus process/launch identity and SSH/runtime process-evidence matrices disappear. src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts removed. Success/no-ID/expired/superseded attach-settlement bag alarms disappear. src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts reduced. Every-write kind forwarding and synchronous driving-attempt observer/rejection/ACK call counts disappear. src/renderer/src/components/terminal-pane/pty-connection-codex-restart-input-lookup.spec.ts removed. No global tab enumeration on ordinary/stale input and known restart notice input-block mock-call alarms. src/renderer/src/components/terminal-pane/pty-connection-layout-owner-wake.test.ts removed. Hidden-to-visible single-pane start request, attach-only argument and negative local wake-record alarms are intentionally dropped; no real server wake/ack occurs. src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts reduced. Internal searched-character budget and ordinary/malformed no-op controls. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1369: src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.ts removed. Rootless/removed/moved tabs, missing leaves, queued deletion and host-qualified/legacy deletion eligibility fixtures. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/renderer/src/components/terminal-pane/pty-connection/terminal-input-echo-delay.test.ts reduced. Removes two fabricated-binding pipeline registrations; retains timestamp-policy outcomes without wall-clock speed assertions. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. src/renderer/src/components/terminal-pane/pty-connection/main-pane-resume-banner.test.ts reduced. Loses subscription-budget and attach-start generation predicate alarms; actual restored-banner renderer is not exercised. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", "motivatingLinks": [ "https://github.com/user-attachments/assets/e8c6d1dc-6150-4c3d-b55a-3d12efefdd04", "https://github.com/user-attachments/assets/b0328f88-34ac-4d51-8119-9efe17072435" ], "invariant": "Adopting a prestarted terminal preserves its existing process and paints snapshot-covered startup output once while retaining subsequent live output. Missing sequence proof or blank snapshots must not authorize dropping output.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Pass snapshot sequence and proven zero keyboard flags through real IPC transport projection. Deliver snapshot-covered and newer output before reattach resolves; drain replay parse callbacks and require one startup marker and the newer output. Repeat with no sequence and blank snapshot to retain unproven bytes. In Electron select a prestarted workspace, type a generated marker and compare PID and stable terminal identities before and after.", + "oracle": "Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Pass snapshot sequence and proven zero keyboard flags through real IPC transport projection. Deliver snapshot-covered and newer output before reattach resolves; drain replay parse callbacks and require one startup marker and the newer output. Repeat with no sequence and blank snapshot to retain unproven bytes. In Electron select a prestarted workspace, type a generated marker and compare PID and stable terminal identities before and after.", "commands": [ "pnpm test src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", "pnpm test src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts", @@ -2242,6 +2242,7 @@ "Exercise live SSH and paired-runtime snapshot adoption before claiming full provider coverage." ], "knownGaps": [ + "Audit2694 intentional coverage losses (source-only, no replacement): src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-command-finished-interrupt-arbitration.spec.ts: 'drops the command-finished status when pending interrupt inference is rejected': Loses the standalone rejected-inference-to-drop alarm; the delayed-write rows remain but are not equivalent to this immediate rejection example. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts: 'forwards raw onData after a bell as a query reply': Loses raw onData forwarding after the manually raised bell, including its hibernation-counter expectations. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts: 'blocks onData on a stale codex pane': The real isCodexPaneStale guard executes, and removing it would allow the typed a to reach transport. Intentionally loses this genuine stale-account typing refusal alarm. No retained query-reply test is claimed equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'omits byte-parser callbacks from the local transport options': Loses local main-authority callback omission and lifecycle callback presence checks. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'keeps byte-parser callbacks on remote-runtime transports': Loses remote-runtime parser callback preservation and factory-argument alarm, including this compatibility boundary; no mixed-version execution is covered. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'consumes pty:sideEffect facts with the live-path policy after spawn': Loses title/bell fact routing and exact 250ms delayed fake notification example. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'schedules the completion notification for genuine working→idle facts': Loses positive main-fact working-to-idle scheduling alarm. Retained stale/race cases do not replace this positive example. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'drops the agent status from a command-finished fact like the byte path did': Loses command-finished fact-to-drop routing and removeAgentStatus noncall alarm. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'routes pr-link facts to the worktree PR observer': Loses PR-link fact forwarding, worktree/tab/PTY arguments alarm; retained raw-byte nonconsumption is not equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'seeds and settles Command Code status from command-code facts': Real Command Code seed/settle policy runs. Loses positive seed, prompt payload, and 1499+1ms completion boundary alarm; retained newer-working cancellation is not equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'does not byte-scan Command Code output — facts are the only consumer': Loses Command Code-specific no-byte-parser alarm. Retained PR/OSC raw-byte exclusion does not cover this parser. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts: 'shares one raw store subscriber for agent-complete notification settings across panes': Actual shared subscribe/unsubscribe runs. Loses shared single-subscription and final-pane unsubscribe lifetime alarm, with no replacement claimed. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts: 'dispatches agent-task-complete for generic Codex spinner titles after process identity is confirmed': Real coordinator evidence path runs over fake process answers. Loses positive generic-title/confirmed-Codex completion and inspectProcess-argument alarm. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts: 'normalizes Pi-compatible remote titles to authoritative OMP launch identity': Real owner-compatible normalization runs. Loses Pi-to-OMP title/status normalization, active tab label, OSC observation, and retained launch-identity example; no real remote transport or equivalent replacement. Wrapper cleanup removes only the deleted bell factory import and its registration-only describe block; no additional authored removal credit. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts: structural support changed only; no new authored removal credit. src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts: requests a tab remount for an unbound spawn; leaves recovery to a remote transport that armed its own retry; requests a remount when the transport reports no recovery of its own; settles the spawn as failed before requesting a remount; prefers the restored leaf id when reporting the anomaly; falls back to the pane leaf id when no restored leaf exists. src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts: repaints from the main-owned snapshot when main drops pending output at the cap. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts: routes terminal input through deferPtyInput so the host can withhold it; forwards terminal input directly when the host supplies no deferPtyInput. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts: records a mode 2031 subscribe from the raw chunk boundary without answering. src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts: retries a fresh-spawn native follow reset when renderer dimensions return. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts: forwards onBell to pane attention and notification policy; hands the bell to the attention module with its pane even when pane attention is off. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionDeferredInputForwardingTests } from '../input/pty-connection-deferred-input-forwarding.spec', registerPtyConnectionDeferredInputForwardingTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionFreshNativeFollowResetTests } from '../output/pty-connection-fresh-native-follow-reset.spec', registerPtyConnectionFreshNativeFollowResetTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec', registerPtyConnectionTerminalBellAttentionTests(); no additional authored credit. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-deferred-input-forwarding.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts. Unresolved local/computed edges remain explicit debt.", "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Composer draft creation and cancellation are not implemented by this gate.", @@ -2378,13 +2379,13 @@ "providers": ["local", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit2729 reduces browser-page-palette-activation.test.ts: separate SSH/paired-runtime alias forwarding, distinct multigroup views accepted, and remote-folder activation forwarding alarms are removed. Collision refusal, preactivation address-bar focus capture, owning-group activation state and missing-tab refusal remain byte-identical. No equivalent replacement, fresh gate execution or actual host/browser delivery evidence is claimed. Prior coverage account: Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4965", "https://github.com/stablyai/orca/pull/15371" ], "invariant": "Candidate identity is the tuple of execution-host identity and worktree identity: same-id sibling hosts retain separate correct browser, simulator, and workspace tabs, each tab appears exactly once, and selection activates its owning host.", - "oracle": "Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", + "oracle": "Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx", @@ -2570,6 +2571,8 @@ "Add a live paired-runtime-over-SSH journey when the E2E harness can provision that combined topology." ], "knownGaps": [ + "Audit2729 retires browser palette standalone paired-runtime SSH alias forwarding, multigroup-view acceptance and remote-folder forwarding alarms without equivalent replacement. The retained partial suite has no fresh execution result; existing exact receipts and budgets stay scoped to their unchanged selectors.", + "Audit2697/2702 intentional palette coverage losses: 'omits a browser row whose backing tab id is duplicated': Remove malformed duplicate unified-tab-ID fixture and its empty result. Real duplicate-ID suppression alarm is lost; this narrow private inventory has no palette selection or activation flow. 'omits a workspace claimed by more than one unified browser tab': Remove two unified browser claims of one workspace. Real first-indexed-foreign-versus-later-owned collision rejection alarm is lost; same-host and ambiguous legacy cases do not replace it. 'omits a workspace whose single unified browser tab is not owned by this worktree': Remove one unique workspace backed by foreign-worktree unified tab fixture. Real foreign-tab/worktree rejection alarm is lost; stamped host tests are not equivalent to foreign worktree mismatch. 'indexes workspace tabs when building a large browser palette': Remove internal getter read budget over1000workspaces: current main policy explicitly rejects getter/Proxy/read counts and says performance changes get correctness tests only. Loses direct quadratic-indexing cost alarm and positive1000workspace output check; no equivalent replacement claimed. The same source review also deletes browser-link-profile-isolation.test.ts (two authored/five expanded) and removes two HTTP-routing declarations (three expanded). Exact tracked-tree filename/case search finds no active gate selector/assertionRef for those navigation sources; their local profile isolation/reuse, deferred minted-profile privacy/lifetime, foreground view/group projection and contextless must-create-page alarms still disappear without replacement. This palette gate is not credited with coverage of those unrelated navigation cases. Historical shard timings are retained unchanged. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added.", "Live Linux, Windows, and paired-runtime-over-SSH journeys are not collected; the SSH/runtime dual-owner topology is deterministic renderer coverage.", "The paired Electron simulator path seeds renderer state because remote web clients cannot launch a native emulator.", "The paired Electron journey proves a real host mirror stamp before injecting the same-id sibling state; it does not create the collision through the wire.", @@ -7371,7 +7374,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coverageNotes": "Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8878", "https://github.com/stablyai/orca/issues/9151", @@ -7381,7 +7384,7 @@ "https://github.com/stablyai/orca/pull/10193" ], "invariant": "For every claim-capable execution route, one provider-session identity has at most one live PTY owner and one canonical host surface across concurrent clients, retries, reconnects, and stale publications. For paired structured fresh and resume requests, the authenticated owning runtime creates in background without a renderer window; activate=true focuses the exact requested leaf only on the requesting viewer, while activate=false changes no viewer focus. A live orphan may be adopted only when the controller proves its exact handle and incarnation, its worktree and host owner match, no competing visual owner exists, and a host topology CAS wins. A viewer may classify completion only from successful host/provider inspection or explicit lifecycle evidence; transport, handle, or provider unavailability remains unknown and breaks any consecutive-idle proof. A physical exit retires that exact incarnation durably so stale client state and host restart cannot recreate it. Mixed-version routes select the unchanged legacy request before any authority side effect or execution-owner-local filesystem access.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup.", + "oracle": "Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session.test.ts", @@ -7592,6 +7595,7 @@ "Add live SSH/WSL provider evidence before claiming full provider coverage; Docker SSH proves only the SSH provider/relay path." ], "knownGaps": [ + "Audit2694 intentional coverage losses (source-only, no replacement): src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-command-finished-interrupt-arbitration.spec.ts: 'drops the command-finished status when pending interrupt inference is rejected': Loses the standalone rejected-inference-to-drop alarm; the delayed-write rows remain but are not equivalent to this immediate rejection example. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts: 'forwards raw onData after a bell as a query reply': Loses raw onData forwarding after the manually raised bell, including its hibernation-counter expectations. src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts: 'blocks onData on a stale codex pane': The real isCodexPaneStale guard executes, and removing it would allow the typed a to reach transport. Intentionally loses this genuine stale-account typing refusal alarm. No retained query-reply test is claimed equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'omits byte-parser callbacks from the local transport options': Loses local main-authority callback omission and lifecycle callback presence checks. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'keeps byte-parser callbacks on remote-runtime transports': Loses remote-runtime parser callback preservation and factory-argument alarm, including this compatibility boundary; no mixed-version execution is covered. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'consumes pty:sideEffect facts with the live-path policy after spawn': Loses title/bell fact routing and exact 250ms delayed fake notification example. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'schedules the completion notification for genuine working→idle facts': Loses positive main-fact working-to-idle scheduling alarm. Retained stale/race cases do not replace this positive example. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'drops the agent status from a command-finished fact like the byte path did': Loses command-finished fact-to-drop routing and removeAgentStatus noncall alarm. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'routes pr-link facts to the worktree PR observer': Loses PR-link fact forwarding, worktree/tab/PTY arguments alarm; retained raw-byte nonconsumption is not equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'seeds and settles Command Code status from command-code facts': Real Command Code seed/settle policy runs. Loses positive seed, prompt payload, and 1499+1ms completion boundary alarm; retained newer-working cancellation is not equivalent. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts: 'does not byte-scan Command Code output — facts are the only consumer': Loses Command Code-specific no-byte-parser alarm. Retained PR/OSC raw-byte exclusion does not cover this parser. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts: 'shares one raw store subscriber for agent-complete notification settings across panes': Actual shared subscribe/unsubscribe runs. Loses shared single-subscription and final-pane unsubscribe lifetime alarm, with no replacement claimed. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts: 'dispatches agent-task-complete for generic Codex spinner titles after process identity is confirmed': Real coordinator evidence path runs over fake process answers. Loses positive generic-title/confirmed-Codex completion and inspectProcess-argument alarm. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts: 'normalizes Pi-compatible remote titles to authoritative OMP launch identity': Real owner-compatible normalization runs. Loses Pi-to-OMP title/status normalization, active tab label, OSC observation, and retained launch-identity example; no real remote transport or equivalent replacement. Wrapper cleanup removes only the deleted bell factory import and its registration-only describe block; no additional authored removal credit. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts. Unresolved local/computed edges remain explicit debt.", diff --git a/config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs b/config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs new file mode 100644 index 00000000000..7dd14db6070 --- /dev/null +++ b/config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs @@ -0,0 +1,273 @@ +#!/usr/bin/env node +// Packs one target's qualified template slot, its pinned Node and a launcher into the server-only +// tarball `orca serve` runs from on hosts without the desktop app. +// node pack-orcad-server-artifact.mjs --template out/orcad-template --target linux-x64-glibc [--out-dir out/orca-server] +import { createHash } from 'node:crypto' +import { + chmodSync, + copyFileSync, + mkdirSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync +} from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' +import { c as createTar } from 'tar' +import { + ORCAD_NODE_RUNTIME_DIR_PREFIX, + ORCAD_RUNTIMES_DIRNAME, + ORCAD_SERVER_ENTRY_FILENAME, + ORCAD_TEMPLATE_MANIFEST_FILENAME, + ORCAD_TEMPLATE_TARGETS_DIR, + ORCAD_VERSION_FILENAME, + ORCAD_CLI_ENTRY_FILENAME, + orcadNodeRuntimeExecutable, + orcadTemplateCommonFilenames, + orcadTemplateTargetFilenames +} from '../../../../src/shared/orcad-artifacts.ts' +import { ORCAD_LOCAL_SERVE_SELECTION_ENTRY } from '../../../../src/shared/orcad-local-serve-selection.ts' +import { + NODE_RUNTIME_PIN, + nodeRuntimeExecutablePath, + nodeRuntimeReleaseUrl, + pinnedNodeRuntimeAsset +} from '../../../../src/shared/node-runtime-pin.ts' +import { + ensurePinnedNodeExecutable, + fetchPinnedFile, + pinnedNodeCacheDir +} from '../prebuilds/pinned-node-downloads.mjs' +import { extract } from '../../node-runtime/archive-identity/update-node-runtime-pin.mjs' +import { computeOrcadFullVersion } from '../server-bundle/orcad-artifact-version.mjs' +import { assertNotDarkBuild } from '../../../dark-build-switches.cjs' +import { isDirectInvocation } from '../../tool-invocation/script-entry-detection.mjs' + +const root = resolve(import.meta.dirname, '../../../..') +const SLOT_DIR = 'orcad' +const LAUNCHER = 'bin/orca-ide' + +/** Published name without the libc suffix: only glibc slots are published. */ +export function orcaServerArtifactName(target) { + const match = /^(linux|darwin)-(x64|arm64)(?:-glibc)?$/.exec(target) + if (!match) { + throw new Error( + `No server-only artifact for ${target}; use linux-x64-glibc or linux-arm64-glibc` + ) + } + return `orca-server-${match[1]}-${match[2]}` +} + +function sha256(path) { + return createHash('sha256').update(readFileSync(path)).digest('hex') +} + +function isExecutable(filename) { + return /(?:^|\/)(?:rg|spawn-helper)$/.test(filename) +} + +function copyVerified(source, destination, expectedSha256, executable) { + mkdirSync(dirname(destination), { recursive: true }) + copyFileSync(source, destination) + const actual = sha256(destination) + if (actual !== expectedSha256) { + throw new Error(`${source} hashed ${actual}; the template manifest expects ${expectedSha256}`) + } + if (executable) { + chmodSync(destination, 0o755) + } +} + +/** Copies exactly the slot files the desktop deploys over SSH, each checked against the manifest. */ +function stageSlot(templateDir, target, slotDir) { + const manifest = JSON.parse( + readFileSync(join(templateDir, ORCAD_TEMPLATE_MANIFEST_FILENAME), 'utf8') + ) + const targetManifest = manifest.targets?.[target] + if (!targetManifest) { + throw new Error(`${templateDir} has no ${target} slot`) + } + const mobileWebAssets = Object.keys(manifest.commonSha256).filter((name) => + name.startsWith('out/mobile-web/') + ) + const common = orcadTemplateCommonFilenames([]) + const commonFiles = [...new Set([...common, ...mobileWebAssets])] + for (const filename of commonFiles) { + const expected = manifest.commonSha256[filename] + if (!expected) { + throw new Error(`Template manifest omits ${filename}`) + } + copyVerified( + join(templateDir, ...filename.split('/')), + join(slotDir, ...filename.split('/')), + expected, + isExecutable(filename) + ) + } + for (const filename of orcadTemplateTargetFilenames(target)) { + const expected = targetManifest.files?.[filename] + if (!expected) { + throw new Error(`Template manifest omits ${target} ${filename}`) + } + copyVerified( + join(templateDir, ORCAD_TEMPLATE_TARGETS_DIR, target, ...filename.split('/')), + join(slotDir, ...filename.split('/')), + expected, + isExecutable(filename) + ) + } + // Hashed like a desktop slot without the optional browser, which this tarball omits. + const version = computeOrcadFullVersion(slotDir, { target, agentBrowserFilename: null }) + writeFileSync(join(slotDir, ORCAD_VERSION_FILENAME), `${version}\n`) + return version +} + +// Why sh: it must run before any Node exists on the host. ELECTRON_RUN_AS_NODE=1 is how the packaged +// app's CLI runs, and the CLI strips it from the server's environment; the other two would point +// `serve` at a desktop app this install does not have. +function launcherScript(nodeRelativePath) { + return `#!/bin/sh +# Orca server-only launcher: runs the bundled Orca CLI under the bundled Node. +set -e +self=$0 +if command -v readlink >/dev/null 2>&1 && resolved=$(readlink -f -- "$self" 2>/dev/null); then + self=$resolved +fi +root=$(CDPATH= cd -- "$(dirname -- "$self")/.." && pwd -P) +node="$root/${nodeRelativePath}" +unset ORCA_APP_EXECUTABLE ORCA_SERVE_RUNTIME +ELECTRON_RUN_AS_NODE=1 +export ELECTRON_RUN_AS_NODE +exec "$node" "$root/${SLOT_DIR}/${ORCAD_CLI_ENTRY_FILENAME}" "$@" +` +} + +// The CLI asks `/out/main/.js` which server to run; here the answer is fixed. +function selectionEntryScript() { + return `'use strict' +// Answers \`orca serve\`'s runtime question for the server-only artifact (src/shared/orcad-local-serve-selection.ts). +const { readFileSync } = require('node:fs') +const { join } = require('node:path') +const flag = process.argv.indexOf('--app-root') +const root = flag === -1 ? join(__dirname, '..', '..', '..') : process.argv[flag + 1] +const slot = join(root, ${JSON.stringify(SLOT_DIR)}) +let selection +try { + const version = readFileSync(join(slot, ${JSON.stringify(ORCAD_VERSION_FILENAME)}), 'utf8').trim() + selection = { kind: 'orcad', runtime: process.execPath, entry: join(slot, ${JSON.stringify(ORCAD_SERVER_ENTRY_FILENAME)}), version } +} catch (error) { + process.stderr.write('This Orca server install is incomplete; extract the release archive again.\\n') + process.exit(1) +} +process.stdout.write('ORCA_SERVE_RUNTIME ' + JSON.stringify(selection) + '\\n') +` +} + +/** Node's notice ships with its binary; it comes from the same hash-checked archive. */ +async function copyNodeLicense(target, destination) { + const asset = pinnedNodeRuntimeAsset(target) + const cacheDir = pinnedNodeCacheDir() + const archive = await fetchPinnedFile({ + url: nodeRuntimeReleaseUrl(asset.source, asset.archive), + destination: join(cacheDir, asset.archive), + sha256: asset.archiveSha256 + }) + const topLevel = nodeRuntimeExecutablePath(target, asset.archive).replace(/\/bin\/node$/, '') + const extractDir = join(cacheDir, `license-${asset.archiveSha256.slice(0, 12)}`) + extract(archive, extractDir, `${topLevel}/LICENSE`) + copyFileSync(join(extractDir, topLevel, 'LICENSE'), destination) +} + +function listEntries(dir, base = dir) { + const entries = [] + for (const name of readdirSync(dir, { withFileTypes: true }).sort((a, b) => + a.name < b.name ? -1 : a.name > b.name ? 1 : 0 + )) { + const path = join(dir, name.name) + entries.push(relative(base, path)) + if (name.isDirectory()) { + entries.push(...listEntries(path, base)) + } + } + return entries +} + +export async function packOrcaServerArtifact({ templateDir, target, outDir }) { + // A dark build's template must never ship as a server either. + assertNotDarkBuild([templateDir]) + const name = orcaServerArtifactName(target) + const { version: appVersion } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) + const topDir = `orca-server-${appVersion}-${name.slice('orca-server-'.length)}` + const stagingRoot = join(outDir, '.staging') + const staging = join(stagingRoot, topDir) + rmSync(stagingRoot, { recursive: true, force: true }) + mkdirSync(staging, { recursive: true }) + + const orcadVersion = stageSlot(templateDir, target, join(staging, SLOT_DIR)) + const runtimeAsset = pinnedNodeRuntimeAsset(target) + const nodeRelativePath = [ + ORCAD_RUNTIMES_DIRNAME, + `${ORCAD_NODE_RUNTIME_DIR_PREFIX}${runtimeAsset.executableSha256}`, + orcadNodeRuntimeExecutable(target) + ].join('/') + copyVerified( + await ensurePinnedNodeExecutable({ target }), + join(staging, ...nodeRelativePath.split('/')), + runtimeAsset.executableSha256, + true + ) + const launcher = join(staging, ...LAUNCHER.split('/')) + mkdirSync(dirname(launcher), { recursive: true }) + writeFileSync(launcher, launcherScript(nodeRelativePath), { mode: 0o755 }) + chmodSync(launcher, 0o755) + const selectionEntry = join(staging, 'out', 'main', `${ORCAD_LOCAL_SERVE_SELECTION_ENTRY}.js`) + mkdirSync(dirname(selectionEntry), { recursive: true }) + writeFileSync(selectionEntry, selectionEntryScript()) + writeFileSync( + join(staging, 'VERSION'), + `orca ${appVersion}\norcad ${orcadVersion}\nnode ${NODE_RUNTIME_PIN.version}\ntarget ${target}\n` + ) + copyFileSync(join(root, 'LICENSE'), join(staging, 'LICENSE')) + await copyNodeLicense(target, join(staging, ORCAD_RUNTIMES_DIRNAME, 'NODE-LICENSE')) + + const archive = join(outDir, `${name}.tar.gz`) + rmSync(archive, { force: true }) + createTar( + { + file: archive, + sync: true, + cwd: stagingRoot, + gzip: { level: 9 }, + portable: true, + noDirRecurse: true, + // Fixed mtime: rebuilding the same tag yields the same bytes. + mtime: new Date(Number(process.env.SOURCE_DATE_EPOCH ?? 0) * 1000) + }, + [topDir, ...listEntries(staging).map((entry) => `${topDir}/${entry}`)] + ) + rmSync(stagingRoot, { recursive: true, force: true }) + const digest = sha256(archive) + writeFileSync(`${archive}.sha256`, `${digest} ${name}.tar.gz\n`) + return { archive, sha256: digest, topDir, orcadVersion } +} + +function argument(argv, name) { + const index = argv.indexOf(name) + return index === -1 ? null : (argv[index + 1] ?? null) +} + +if (isDirectInvocation(import.meta.url, process.argv[1])) { + const templateDir = argument(process.argv, '--template') + const target = argument(process.argv, '--target') + if (!templateDir || !target) { + throw new Error( + 'Usage: pack-orcad-server-artifact.mjs --template --target [--out-dir ]' + ) + } + const result = await packOrcaServerArtifact({ + templateDir: resolve(templateDir), + target, + outDir: resolve(argument(process.argv, '--out-dir') ?? join(root, 'out', 'orca-server')) + }) + process.stdout.write(`${JSON.stringify(result)}\n`) +} diff --git a/config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs b/config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs new file mode 100644 index 00000000000..c4c96330aac --- /dev/null +++ b/config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +// Installs a server-only tarball the documented way, starts `orca serve --recipe-json`, then pairs a +// second CLI profile with the printed code. Uses only node: builtins so the archive's own Node can run it +// on an image that has nothing else. +// node smoke-orcad-server-artifact.mjs --archive out/orca-server/orca-server-linux-x64.tar.gz +import { execFileSync, spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { + closeSync, + existsSync, + mkdirSync, + mkdtempSync, + openSync, + readFileSync, + rmSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { basename, join, resolve } from 'node:path' + +const argv = process.argv.slice(2) +const archiveArg = argv[argv.indexOf('--archive') + 1] +if (!argv.includes('--archive') || !archiveArg) { + fail('Usage: smoke-orcad-server-artifact.mjs --archive ') +} +const archive = resolve(archiveArg) +const work = mkdtempSync(join(tmpdir(), 'orca-server-smoke-')) +const install = join(work, 'install') +const projectRoot = join(work, 'project') +const serverProfile = join(work, 'server-profile') +const clientProfile = join(work, 'client-profile') +// Linux names the CLI orca-ide, like the desktop package. +const orca = join(install, 'bin', 'orca-ide') + +try { + verifyChecksum() + for (const dir of [install, projectRoot, serverProfile, clientProfile]) { + mkdirSync(dir, { recursive: true }) + } + execFileSync('tar', ['-xzf', archive, '-C', install, '--strip-components=1'], { + stdio: 'inherit' + }) + const version = run([orca, '--version'], serverProfile) + assert(version.status === 0, `orca --version failed:\n${version.stderr}`) + console.log(`installed ${version.stdout.trim()}`) + + const started = Date.now() + const serve = run( + [orca, 'serve', '--recipe-json', '--project-root', projectRoot, '--port', '0'], + serverProfile, + { timeout: 120_000 } + ) + assert(serve.status === 0, `serve --recipe-json exited ${serve.status}:\n${serve.stderr}`) + const recipe = JSON.parse(serve.stdout.trim().split('\n').at(-1)) + const pairingCode = recipe.pairingCode ?? recipe.connection?.pairingCode + assert( + typeof pairingCode === 'string' && pairingCode.length > 0, + `no pairing code: ${serve.stdout}` + ) + assert( + (recipe.projectRoot ?? recipe.connection?.projectRoot) === projectRoot, + `recipe JSON names another project root: ${serve.stdout}` + ) + console.log(`PASS serve --recipe-json printed a pairing code in ${Date.now() - started} ms`) + + const status = run([orca, '--pairing-code', pairingCode, 'status', '--json'], clientProfile, { + timeout: 60_000 + }) + assert(status.status === 0, `paired status failed:\n${status.stderr}\n${status.stdout}`) + const result = JSON.parse(status.stdout).result ?? {} + assert( + result.runtime?.state === 'ready' && result.runtime?.reachable !== false, + `paired client did not reach a ready server: ${status.stdout}` + ) + console.log( + `PASS a second profile paired and saw runtime ${result.runtime.runtimeId ?? ''} ready` + ) +} finally { + stopServersFrom(install) + rmSync(work, { recursive: true, force: true }) +} + +function verifyChecksum() { + const sums = `${archive}.sha256` + if (!existsSync(sums)) { + return + } + const [expected, name] = readFileSync(sums, 'utf8').trim().split(/\s+/) + const actual = createHash('sha256').update(readFileSync(archive)).digest('hex') + assert(name === basename(archive) && actual === expected, `${archive} does not match ${sums}`) + console.log('PASS checksum') +} + +// stderr goes to a file: the detached server keeps it open, and a pipe would hold spawnSync until timeout. +function run(command, profile, { timeout = 30_000 } = {}) { + const [program, ...args] = command + const log = join(work, `${basename(profile)}.stderr.log`) + const fd = openSync(log, 'a') + try { + const result = spawnSync(program, args, { + cwd: projectRoot, + encoding: 'utf8', + timeout, + stdio: ['ignore', 'pipe', fd], + env: { ...process.env, ORCA_USER_DATA_PATH: profile, ORCA_BACKGROUND_LAUNCH: '1' } + }) + return { ...result, stderr: readFileSync(log, 'utf8').slice(-4000) } + } finally { + closeSync(fd) + } +} + +// --recipe-json leaves the server running on purpose; this smoke must not. +function stopServersFrom(dir) { + const listing = spawnSync('ps', ['-eo', 'pid=,args='], { encoding: 'utf8' }) + for (const line of (listing.stdout ?? '').split('\n')) { + const match = /^\s*(\d+)\s+(.*)$/.exec(line) + if (match && match[2].includes(dir) && Number(match[1]) !== process.pid) { + try { + process.kill(Number(match[1]), 'SIGKILL') + } catch {} + } + } +} + +function assert(condition, message) { + if (!condition) { + fail(message) + } +} + +function fail(message) { + console.error(`FAIL ${message}`) + process.exitCode = 1 + throw new Error(message) +} diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-child-artifacts.test.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-child-artifacts.test.mjs deleted file mode 100644 index 0ab57b04a53..00000000000 --- a/config/scripts/orcad-distribution/server-bundle/orcad-child-artifacts.test.mjs +++ /dev/null @@ -1,12 +0,0 @@ -import { expect, it } from 'vitest' -import { ORCAD_ARTIFACTS } from '../../../../src/shared/orcad-artifacts.ts' -import { ORCAD_CHILD_ENTRY_POINTS, orcadChildOutputFilename } from './orcad-entry-build.mjs' - -// A child built but not listed never reaches remote hosts, so its client fails there. -it.each(Object.entries(ORCAD_CHILD_ENTRY_POINTS))( - 'ships the %s child bundle as an orcad artifact', - (_name, entryPoint) => { - const filenames = ORCAD_ARTIFACTS.map((artifact) => artifact.filename) - expect(filenames).toContain(orcadChildOutputFilename(entryPoint)) - } -) diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index cf041be983c..d7542c5e628 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -4,7 +4,6 @@ "../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", "../tests/e2e/terminal-agent-pane-launch.unit.test.ts", - "../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts", "../src/shared/**/*.test.ts", "../src/shared/**/*.test.tsx", diff --git a/config/tsconfig.test.pane-launch.json b/config/tsconfig.test.pane-launch.json index f476bd1de39..63896e6d839 100644 --- a/config/tsconfig.test.pane-launch.json +++ b/config/tsconfig.test.pane-launch.json @@ -8,7 +8,6 @@ "../tests/e2e/terminal-agent-pane-launch.unit.test.ts", "../src/renderer/src/runtime/observed-provider-accounts.test.tsx", "../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx", - "../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts", "../src/renderer/src/env.d.ts", "../src/types/build-constants.d.ts", diff --git a/config/tsconfig.web.json b/config/tsconfig.web.json index ddb38d005ec..02a420684d3 100644 --- a/config/tsconfig.web.json +++ b/config/tsconfig.web.json @@ -14,7 +14,6 @@ "../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", "../tests/e2e/terminal-agent-pane-launch.unit.test.ts", - "../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts" ], "compilerOptions": { diff --git a/docs/site/content/docs/remote-servers.mdx b/docs/site/content/docs/remote-servers.mdx index 866722a7fc5..0b85c58e10a 100644 --- a/docs/site/content/docs/remote-servers.mdx +++ b/docs/site/content/docs/remote-servers.mdx @@ -189,6 +189,24 @@ Use only one host mode at a time. If the Orca desktop app is already sharing tha `orca serve` runs on Orca's own Node server (orcad) by default. If orcad can't serve on this computer, it uses the desktop app's server instead and prints one line saying why. On a packaged macOS app it uses the desktop app's server, so paired clients can still update it, unless you set `ORCA_SERVE_RUNTIME=orcad` (see [A Mac reached only over SSH](#a-mac-reached-only-over-ssh)). To always use the desktop app's server, set `ORCA_SERVE_RUNTIME=electron`. +### Install only the server on Linux + +Each release also publishes the server alone for Linux x64 and arm64: orcad, the Node runtime it runs on, and the `orca-ide` CLI. It needs no desktop packages (GTK, X11, Xvfb), so it suits your own headless Linux servers, VMs and containers. It is about 60 MB to download, against 190 MB for the `.deb`. Download it, check it, and unpack it: + +```bash +arch=$(uname -m | sed 's/x86_64/x64/; s/aarch64/arm64/') +base=https://github.com/stablyai/orca/releases/latest/download +curl -fsSLO "$base/orca-server-linux-$arch.tar.gz" -O "$base/orca-server-sha256sums.txt" +sha256sum --check --ignore-missing orca-server-sha256sums.txt +sudo mkdir -p /opt/orca-server +sudo tar -xzf "orca-server-linux-$arch.tar.gz" -C /opt/orca-server --strip-components=1 +/opt/orca-server/bin/orca-ide serve --pairing-address +``` + +To pin a release, replace `latest/download` with `download/v`, and keep that release's checksum in your script rather than downloading it next to the archive. The server needs glibc 2.28 or newer (Ubuntu 20.04, Debian 10, RHEL 8 and later). + +`orca-ide serve` takes the same flags as above, including `--supervise` under a service manager and `--recipe-json`. To update, stop the server, replace `/opt/orca-server` with a newer release, and start it again; paired clients cannot update it for you. For `orca-ide serve service install`, pass `--command /opt/orca-server/bin/orca-ide` or put `/opt/orca-server/bin` on `PATH`. A server-only install has no browser panes, dictation or paired web client, because those come with the desktop app. + ### Limit terminal memory on a Linux server By default, nothing caps how much memory a terminal's processes use, so one runaway job can push the whole server into the kernel's out-of-memory killer. On Linux you can cap each terminal by setting these variables in the environment that starts `orca serve` (or in its service unit): diff --git a/docs/site/tests/docs-package.test.mjs b/docs/site/tests/docs-package.test.mjs index 06b35a04207..4b353a717c6 100644 --- a/docs/site/tests/docs-package.test.mjs +++ b/docs/site/tests/docs-package.test.mjs @@ -3,16 +3,11 @@ import { readFile, readdir } from 'node:fs/promises' import { existsSync } from 'node:fs' import path from 'node:path' import test from 'node:test' -import { pathToFileURL } from 'node:url' const siteRoot = path.resolve(import.meta.dirname, '..') const contentRoot = path.join(siteRoot, 'content', 'docs') const publicRoot = path.join(siteRoot, 'public') -async function read(relativePath) { - return readFile(path.join(siteRoot, relativePath), 'utf8') -} - async function walkFiles(directory, extension) { const entries = await readDirectory(directory) const files = [] @@ -40,19 +35,6 @@ function isMediaPath(urlPath) { return /\.(?:gif|jpe?g|png|webp|mp4|svg|ico)$/i.test(urlPath.split(/[?#]/, 1)[0]) } -test('docs content and navigation metadata are discoverable', async () => { - const pages = await walkFiles(contentRoot, '.mdx') - assert.ok(pages.length > 0, 'expected docs content pages') - - const navigationFiles = await walkFiles(contentRoot, 'meta.json') - assert.ok(navigationFiles.length > 0, 'expected navigation metadata') - for (const file of navigationFiles) { - const metadata = JSON.parse(await readFile(file, 'utf8')) - assert.ok(metadata.title, `navigation title missing in ${file}`) - assert.ok(Array.isArray(metadata.pages), `navigation pages missing in ${file}`) - } -}) - test('every local media URL referenced by docs resolves in public assets', async () => { const files = await walkFiles(contentRoot, '.mdx') const localUrls = new Set() @@ -84,29 +66,3 @@ test('docs content does not link to routes that only exist on the marketing site } } }) - -test('GIF media helpers use the shared poster and video variants', async () => { - const media = await import(pathToFileURL(path.join(siteRoot, 'src', 'lib', 'demoMedia.mjs')).href) - assert.equal(media.posterFor('/docs/orca-design-mode.gif'), '/docs/posters/orca-design-mode.jpg') - assert.equal(media.videoFor('/docs/orca-design-mode.gif'), '/docs/videos/orca-design-mode.mp4') - assert.equal(media.posterFor('/docs/tab-split.gif'), '/docs/posters/tab-split.jpg') - assert.equal(media.videoFor('/docs/tab-split.gif'), '/docs/videos/tab-split.mp4') - - for (const name of ['orca-design-mode', 'tab-split']) { - assert.ok(existsSync(path.join(publicRoot, 'docs', 'posters', `${name}.jpg`))) - assert.ok(existsSync(path.join(publicRoot, 'docs', 'videos', `${name}.mp4`))) - } -}) - -test('OG image fonts ship with their required third-party notice', async () => { - for (const filename of ['Geist-Regular.ttf', 'Geist-Bold.ttf', 'Geist-Variable.woff2']) { - assert.ok( - existsSync(path.join(siteRoot, 'src', 'assets', 'fonts', filename)), - `missing font: ${filename}` - ) - } - - const notice = await read('THIRD_PARTY_NOTICES.md') - assert.match(notice, /SIL OPEN FONT LICENSE Version 1\.1/) - assert.match(notice, /Copyright \(c\) 2023 Vercel/) -}) diff --git a/docs/site/tests/search-excerpt.test.mjs b/docs/site/tests/search-excerpt.test.mjs index 9ce21d1c874..68b2c87869d 100644 --- a/docs/site/tests/search-excerpt.test.mjs +++ b/docs/site/tests/search-excerpt.test.mjs @@ -1,22 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { runInNewContext } from 'node:vm' import { stripSearchExcerptMarkdown } from '../src/components/docs/search-excerpt.mjs' -test('unterminated escaped link destinations do not backtrack exponentially', () => { - for (const prefix of ['![](', '[label](']) { - const input = prefix + '\\('.repeat(32_768) - const result = runInNewContext( - 'strip(input)', - { strip: stripSearchExcerptMarkdown, input }, - { - timeout: 250 - } - ) - assert.equal(result, input.replace(/\\\(/g, '(')) - } -}) - test('link destinations retain escaped closing parentheses and literal escapes', () => { for (const prefix of ['![label](', '[label](']) { assert.equal(stripSearchExcerptMarkdown(prefix + 'https://example.com/a\\)b)'), 'label') @@ -60,16 +45,6 @@ test('search excerpts preserve highlighted matches inside Markdown', () => { ) }) -test('unclosed angles finish within the excerpt budget without changing text', () => { - const input = '<'.repeat(131_072) - const result = runInNewContext( - 'strip(input)', - { strip: stripSearchExcerptMarkdown, input }, - { timeout: 250 } - ) - assert.equal(result, input) -}) - test('tag guards preserve malformed markup, protected code and highlighted matches', () => { const cases = [ ['**bold**', 'bold'], @@ -99,13 +74,3 @@ test('tag guards preserve malformed markup, protected code and highlighted match assert.equal(stripSearchExcerptMarkdown(input), expected, input) } }) - -test('unclosed brackets finish within the excerpt budget without changing text', () => { - const input = '['.repeat(131_072) - const result = runInNewContext( - 'strip(input)', - { strip: stripSearchExcerptMarkdown, input }, - { timeout: 250 } - ) - assert.equal(result, input) -}) diff --git a/docs/site/tests/zod-security.test.mjs b/docs/site/tests/zod-security.test.mjs deleted file mode 100644 index 8308ff558a4..00000000000 --- a/docs/site/tests/zod-security.test.mjs +++ /dev/null @@ -1,52 +0,0 @@ -import assert from 'node:assert/strict' -import { createRequire } from 'node:module' -import { dirname, join } from 'node:path' -import test from 'node:test' -import { pathToFileURL } from 'node:url' - -const require = createRequire(import.meta.url) -const vercelRequire = createRequire(require.resolve('vercel/package.json')) -const backendsRequire = createRequire(vercelRequire.resolve('@vercel/backends/package.json')) -const zodRoot = dirname(backendsRequire.resolve('zod/package.json')) - -for (const extension of ['cjs', 'js']) { - for (const entry of ['index', 'v3/index', 'v4/index']) { - test(`Vercel Zod rejects oversized collections before parsing elements (${entry}.${extension})`, async () => { - const path = join(zodRoot, `${entry}.${extension}`) - const z = extension === 'cjs' ? require(path) : await import(pathToFileURL(path).href) - let parsed = 0 - const element = z.preprocess((value) => { - parsed += 1 - return value - }, z.string()) - for (const [schema, value, valid] of [ - [z.array(element).max(2), Array(1_000).fill(0), ['a']], - [z.array(element).length(2), Array(1_000).fill(0), ['a', 'b']], - [z.set(element).max(2), new Set([1, 2, 3]), new Set(['a'])], - [z.set(element).size(2), new Set([1, 2, 3]), new Set(['a', 'b'])] - ]) { - parsed = 0 - for (const result of [schema.safeParse(value), await schema.safeParseAsync(value)]) { - assert.equal(result.success, false) - assert.deepEqual( - result.error.issues.map((issue) => issue.code), - ['too_big'] - ) - } - assert.equal(parsed, 0) - assert.deepEqual(schema.parse(valid), valid) - assert.deepEqual(await schema.parseAsync(valid), valid) - } - }) - } -} - -test('docs Zod 4 keeps valid schemas working after the security upgrade', async () => { - const { z } = await import('zod') - const schema = z.array(z.string()).max(2) - assert.deepEqual(schema.parse(['a']), ['a']) - assert.deepEqual( - schema.safeParse([1, 2, 3]).error.issues.map((issue) => issue.code), - ['too_big'] - ) -}) diff --git a/mobile/src/hooks/mobile-dictation-audio-chunk.ts b/mobile/src/hooks/mobile-dictation-audio-chunk.ts index 18f382de908..c9a18b0d721 100644 --- a/mobile/src/hooks/mobile-dictation-audio-chunk.ts +++ b/mobile/src/hooks/mobile-dictation-audio-chunk.ts @@ -260,7 +260,7 @@ async function sendAudioChunk( dictationId, audioBase64: bytesToBase64(bytes), sampleRate: MOBILE_DICTATION_PCM_SAMPLE_RATE, - seq: queue.pendingAudioBudget.nextSeq() + seq: queue.pendingAudioBudget.nextSeq(bytes.byteLength) } const hostDedupesResends = queue.pendingAudioBudget.hostDedupesResends try { diff --git a/mobile/src/hooks/mobile-dictation-desktop-start.ts b/mobile/src/hooks/mobile-dictation-desktop-start.ts index 29eef603b45..2b6b28cdf0c 100644 --- a/mobile/src/hooks/mobile-dictation-desktop-start.ts +++ b/mobile/src/hooks/mobile-dictation-desktop-start.ts @@ -1,7 +1,4 @@ -import { - DICTATION_FINISH_TIMEOUT_MS, - isCurrentMobileDictationStart -} from './mobile-dictation-session-state' +import { isCurrentMobileDictationStart } from './mobile-dictation-session-state' import { sendAcrossConnectionMove } from './mobile-dictation-audio-chunk' import { dictationSessionLostMessage } from '../dictation/mobile-dictation-setup' import { @@ -10,6 +7,7 @@ import { dictationSessionStart } from '../dictation/mobile-dictation-operations' import { MOBILE_DICTATION_RECONNECT_GRACE_MS } from '../../../src/shared/rpc-contract/speech-params' +import { pairedDictationFinishTimeoutMs } from '../../../src/shared/dictation-finish-deadlines' import { rpcPayloadMember } from '../transport/rpc/rpc-reader-payload' import { probeLivenessWhileWaiting } from '../transport/rpc/rpc-liveness-probe-while-waiting' import type { RpcClient } from '../transport/rpc/rpc-client-contract' @@ -57,15 +55,13 @@ export function cancelDesktopDictation(client: RpcClient, dictationId: string): // Returns the interpreted reply: the caller reads its text only after its staleness guard. export async function finishDesktopDictation( client: RpcClient, - dictationId: string + dictationId: string, + sentAudioSeconds: number ): Promise { + const timeoutMs = pairedDictationFinishTimeoutMs(sentAudioSeconds) return dictationSessionFinish.interpret( await sendAcrossConnectionMove(client, () => - dictationSessionFinish.request( - client, - { dictationId }, - { timeoutMs: DICTATION_FINISH_TIMEOUT_MS } - ) + dictationSessionFinish.request(client, { dictationId }, { timeoutMs }) ) ) } diff --git a/mobile/src/hooks/mobile-dictation-pending-audio-budget.ts b/mobile/src/hooks/mobile-dictation-pending-audio-budget.ts index 6f59df36b63..d2b83fe9b99 100644 --- a/mobile/src/hooks/mobile-dictation-pending-audio-budget.ts +++ b/mobile/src/hooks/mobile-dictation-pending-audio-budget.ts @@ -1,6 +1,7 @@ import { DICTATION_SAMPLE_RATE, - MOBILE_DICTATION_MAX_PENDING_AUDIO_BYTES + MOBILE_DICTATION_MAX_PENDING_AUDIO_BYTES, + PCM_BYTES_PER_SAMPLE } from '../../../src/shared/rpc-contract/speech-params' export const MOBILE_DICTATION_PCM_SAMPLE_RATE = DICTATION_SAMPLE_RATE @@ -15,6 +16,7 @@ export class MobileDictationPendingAudioBudget { // Backlog not yet taken into a request; it sits at the front of the held audio. private untakenBacklogBytes = 0 private sentChunks = 0 + private sentBytes = 0 // Set at each start: a host that feeds each chunk seq once can take audio a drop left unanswered again. hostDedupesResends = false @@ -24,10 +26,16 @@ export class MobileDictationPendingAudioBudget { return this.pendingBytes } - nextSeq(): number { + // Numbers a request and counts its audio, which sets how long finish waits. + nextSeq(byteLength: number): number { + this.sentBytes += normalizeByteLength(byteLength) return this.sentChunks++ } + get sentAudioSeconds(): number { + return this.sentBytes / (PCM_BYTES_PER_SAMPLE * MOBILE_DICTATION_PCM_SAMPLE_RATE) + } + reserveBacklog(byteLength: number): void { const normalizedByteLength = normalizeByteLength(byteLength) this.pendingBytes += normalizedByteLength @@ -62,6 +70,7 @@ export class MobileDictationPendingAudioBudget { this.backlogBytes = 0 this.untakenBacklogBytes = 0 this.sentChunks = 0 + this.sentBytes = 0 this.hostDedupesResends = hostDedupesResends } } diff --git a/mobile/src/hooks/mobile-dictation-session-state.ts b/mobile/src/hooks/mobile-dictation-session-state.ts index 2664ae7b540..a2ab4abb53e 100644 --- a/mobile/src/hooks/mobile-dictation-session-state.ts +++ b/mobile/src/hooks/mobile-dictation-session-state.ts @@ -36,8 +36,6 @@ export type UseMobileDictationResult = { meter: MobileDictationMeter } -export const DICTATION_FINISH_TIMEOUT_MS = 75_000 - // An interrupted user tap needs a renderable error; only explicit user cancellation may end silently. export const MOBILE_DICTATION_INPUT_CLOSED_ERROR_MESSAGE = 'Voice dictation stopped because this session is no longer accepting input. Try again.' diff --git a/mobile/src/hooks/use-mobile-dictation.ts b/mobile/src/hooks/use-mobile-dictation.ts index 46c96310138..bfc0e9cd3c9 100644 --- a/mobile/src/hooks/use-mobile-dictation.ts +++ b/mobile/src/hooks/use-mobile-dictation.ts @@ -212,7 +212,8 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil if (!isCurrent() || !client) { return } - const finished = await finishDesktopDictation(client, dictationId) + const sentSeconds = pendingAudioBudgetRef.current.sentAudioSeconds + const finished = await finishDesktopDictation(client, dictationId, sentSeconds) if (!isCurrent()) { return } diff --git a/mobile/src/terminal/session/mobile-terminal-records.test.ts b/mobile/src/terminal/session/mobile-terminal-records.test.ts deleted file mode 100644 index d5d663d307e..00000000000 --- a/mobile/src/terminal/session/mobile-terminal-records.test.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - getTerminalRecordsFromSessionTabs, - mergeTerminalListWithKnownRecords, - mergeTerminalRecordsByCurrentOrder, - type MobileTerminalSessionTab, - type TerminalRecord -} from './mobile-terminal-records' - -const lightTheme = { - mode: 'light' as const, - theme: { - background: '#ffffff', - foreground: '#111111' - } -} - -const darkTheme = { - mode: 'dark' as const, - theme: { - background: '#111111', - foreground: '#eeeeee' - } -} - -describe('mobile terminal records', () => { - it('keeps the known theme when a session-tab snapshot omits it', () => { - const known: TerminalRecord[] = [ - { handle: 'pty-1', title: 'Old title', terminalTheme: darkTheme, isActive: false } - ] - const snapshot: TerminalRecord[] = [{ handle: 'pty-1', title: 'Current title', isActive: true }] - - expect(mergeTerminalRecordsByCurrentOrder(snapshot, known)).toEqual([ - { handle: 'pty-1', title: 'Current title', terminalTheme: darkTheme, isActive: true } - ]) - }) - - it('keeps the host pane identity when a session-tab snapshot omits it', () => { - const known: TerminalRecord[] = [ - { handle: 'pty-1', title: 'Old title', isActive: false, agentIdentity: 'cursor' } - ] - const snapshot: TerminalRecord[] = [{ handle: 'pty-1', title: 'Current title', isActive: true }] - - expect(mergeTerminalRecordsByCurrentOrder(snapshot, known)).toEqual([ - { handle: 'pty-1', title: 'Current title', isActive: true, agentIdentity: 'cursor' } - ]) - }) - - it('lets an authoritative inventory replace or clear an earlier host identity', () => { - const known: TerminalRecord[] = [ - { handle: 'pty-1', title: 'Terminal', isActive: true, agentIdentity: 'cursor' } - ] - for (const agentIdentity of ['claude', undefined]) { - const listed: TerminalRecord[] = [ - { handle: 'pty-1', title: 'Terminal', isActive: true, agentIdentity } - ] - expect(mergeTerminalListWithKnownRecords(listed, known, [])[0]?.agentIdentity).toBe( - agentIdentity - ) - } - }) - - it('keeps session-tab terminal themes when terminal.list omits them', () => { - const terminalList: TerminalRecord[] = [ - { handle: 'pty-1', title: 'Terminal', isActive: true }, - { handle: 'pty-2', title: 'Logs', isActive: false } - ] - const currentTerminals: TerminalRecord[] = [ - { handle: 'pty-1', title: 'Terminal', terminalTheme: darkTheme, isActive: true } - ] - const sessionTabs: MobileTerminalSessionTab[] = [ - { - type: 'terminal', - id: 'term-1::leaf-1', - title: 'Terminal', - terminal: 'pty-1', - terminalTheme: lightTheme, - isActive: true - } - ] - - expect(mergeTerminalListWithKnownRecords(terminalList, currentTerminals, sessionTabs)).toEqual([ - { handle: 'pty-1', title: 'Terminal', terminalTheme: lightTheme, isActive: true }, - { handle: 'pty-2', title: 'Logs', isActive: false } - ]) - }) - - it('falls back to the current terminal theme while waiting for session tabs', () => { - const terminalList: TerminalRecord[] = [{ handle: 'pty-1', title: 'Terminal', isActive: true }] - const currentTerminals: TerminalRecord[] = [ - { handle: 'pty-1', title: 'Terminal', terminalTheme: darkTheme, isActive: true } - ] - - expect(mergeTerminalListWithKnownRecords(terminalList, currentTerminals, [])).toEqual([ - { handle: 'pty-1', title: 'Terminal', terminalTheme: darkTheme, isActive: true } - ]) - }) - - const record = (over: Partial & { handle: string }): TerminalRecord => ({ - title: 'Terminal', - terminalTheme: undefined, - isActive: false, - ...over - }) - const terminalTab = (handle: string): MobileTerminalSessionTab => ({ - id: `tab-${handle}`, - type: 'terminal', - terminal: handle, - title: 'Terminal', - isActive: false - }) - - it('keeps the merge additive so absence only schedules the sweep', () => { - const held = [ - record({ handle: 'pty-1', connected: true }), - record({ handle: 'pty-2', connected: true }) - ] - const tabs = [terminalTab('pty-1')] - - expect( - mergeTerminalRecordsByCurrentOrder(getTerminalRecordsFromSessionTabs(tabs), held).map( - (terminal) => terminal.handle - ) - ).toEqual(['pty-1', 'pty-2']) - }) -}) diff --git a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts b/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts deleted file mode 100644 index 82b0e0590ab..00000000000 --- a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { terminalInputSend } from './mobile-terminal-operations' -import { describe, expect, it, vi } from 'vitest' -import { sendTerminalLiveAccessoryRawBytes } from './terminal-live-accessory-raw-send' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' - -function captureClient( - result: Promise = Promise.resolve({ - id: 'send', - ok: true, - result: { send: { handle: 'terminal-a', accepted: true, bytesWritten: 1 } }, - _meta: { runtimeId: 'test-runtime' } - }) -) { - const sendRequest = vi.fn(() => result) - return { client: { sendRequest } as unknown as Pick, sendRequest } -} - -const BASE_ARGS = { - sendTerminalUserInput: terminalInputSend.request, - targetHandle: 'terminal-a', - activeHandle: 'terminal-a', - activeSessionTabType: 'terminal', - connState: 'connected', - bytes: '', - deviceToken: 'tok' -} as const - -describe('terminal live accessory raw send', () => { - it('drops the bytes when the terminal selection went stale mid-flush', async () => { - const { client, sendRequest } = captureClient() - - await expect( - sendTerminalLiveAccessoryRawBytes({ ...BASE_ARGS, client, activeHandle: 'terminal-b' }) - ).resolves.toBe(false) - - expect(sendRequest).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/terminal/terminal-viewport-refit.test.ts b/mobile/src/terminal/terminal-viewport-refit.test.ts deleted file mode 100644 index 6c3083d72e5..00000000000 --- a/mobile/src/terminal/terminal-viewport-refit.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { reduceTerminalFrameHeightRefit } from './terminal-viewport-refit-state' - -describe('terminal viewport refit', () => { - it('re-defers a height refit if the keyboard reopens before the debounce fires', () => { - let r = reduceTerminalFrameHeightRefit( - { frameHeight: 600, keyboardVisible: true, pending: false }, - { type: 'frame-height', height: 520 } - ) - expect(r.shouldRefit).toBe(false) - expect(r.state.pending).toBe(true) - - r = reduceTerminalFrameHeightRefit(r.state, { type: 'keyboard-visibility', visible: false }) - expect(r.shouldRefit).toBe(true) - - // Reopen inside debounce; the timer must preserve the pending refit instead of reflowing while typing. - r = reduceTerminalFrameHeightRefit(r.state, { type: 'keyboard-visibility', visible: true }) - const committed = reduceTerminalFrameHeightRefit(r.state, { type: 'refit-committed' }) - expect(committed.shouldRefit).toBe(false) - expect(committed.state.pending).toBe(true) - - const rescheduled = reduceTerminalFrameHeightRefit(committed.state, { - type: 'keyboard-visibility', - visible: false - }) - expect(rescheduled.shouldRefit).toBe(true) - const ran = reduceTerminalFrameHeightRefit(rescheduled.state, { type: 'refit-committed' }) - expect(ran.shouldRefit).toBe(true) - expect(ran.state.pending).toBe(false) - }) -}) diff --git a/mobile/src/test-support/rpc-recording/README.md b/mobile/src/test-support/rpc-recording/README.md index cbd6d8becff..cb81daaa812 100644 --- a/mobile/src/test-support/rpc-recording/README.md +++ b/mobile/src/test-support/rpc-recording/README.md @@ -118,7 +118,7 @@ so the projection has a temporal dimension instead of relying on where a checkpo Any transition the product schedules for itself is recorded at the time it actually fires: change a request deadline or the search debounce by any amount, in either direction, and a recorded number moves. Granularity is exact milliseconds, because the fake timers fire at their scheduled time and -never coalesce; `recording-runner.test.ts` pins a 5 ms deadline settling at exactly `settledAt: 5`. +never coalesce. A checkpoint's own clock is not recorded. It is always the sum of the scripted `advance` steps, so it is a function of the scenario rather than of the code under test; `run-recording.ts` asserts that diff --git a/mobile/src/test-support/rpc-recording/mounted-screen-tree.test.ts b/mobile/src/test-support/rpc-recording/mounted-screen-tree.test.ts deleted file mode 100644 index 015f8ffb68a..00000000000 --- a/mobile/src/test-support/rpc-recording/mounted-screen-tree.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { resolve } from 'node:path' -import { describe, expect, it } from 'vitest' -import { pilotMountAdapters } from './pilot-mount-adapters' -import { runRecording } from './run-recording' -import { readScenarios } from './scenario-input' -import { vitestRecordingScheduler } from './vitest-recording-scheduler' - -const root = resolve(import.meta.dirname, '../../../..') -const manifest = readScenarios( - process.env.RPC_FOUNDATION_SCENARIOS ?? - resolve(root, 'mobile/rpc-foundation/pilot-scenarios.json') -).scenarios - -describe('a mounted screen', () => { - // Drive the real panel/context/socket so declared props reach wire params and refusal triggers fallback. - it('sends what the screen sends, with no substitute shaping a param', async () => { - const scenario = manifest.find( - (candidate) => candidate.id === 'files-explorer-legacy-fallback' - )! - const { adapters } = pilotMountAdapters(root, { device: scenario }) - const recording = await runRecording( - scenario, - adapters[scenario.operation]!, - vitestRecordingScheduler() - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a recorded sender entry has a name and three positional argument slots. - const sender = recording.checkpoints.at(-1)!.observation.sender as { - name: string - args: { name: string; value: unknown }[] - }[] - expect( - sender.map((entry) => ({ - name: entry.name, - params: entry.args[1]?.value, - options: entry.args[2]?.value - })) - ).toEqual([ - { - name: 'files.readDir#1', - params: { relativePath: '', worktree: 'id:wt-files', limit: 500 }, - options: { failWhenDisconnected: true } - }, - { - name: 'files.list#1', - params: { worktree: 'id:wt-files' }, - options: { failWhenDisconnected: true } - } - ]) - }) -}) diff --git a/mobile/src/test-support/rpc-recording/recording-runner.test.ts b/mobile/src/test-support/rpc-recording/recording-runner.test.ts deleted file mode 100644 index df1d8b2342b..00000000000 --- a/mobile/src/test-support/rpc-recording/recording-runner.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { ScriptedRpcTransport } from './scripted-rpc-transport' -import { vitestRecordingScheduler } from './vitest-recording-scheduler' - -describe('recording boundaries', () => { - it('requires logical bindings plus matching params for concurrent same-method calls', async () => { - const clock = vitestRecordingScheduler() - await clock.start() - const transport = new ScriptedRpcTransport(clock.elapsed) - try { - const left = transport.client.sendRequest('files.list', { worktree: 'A' }) - const right = transport.client.sendRequest('files.list', { worktree: 'B' }) - await clock.flush() - expect(() => transport.complete('files.list#1', { worktree: 'A' }, {})).toThrow( - 'logical binding' - ) - expect(() => transport.bind('left', 'files.list#1', { worktree: 'B' })).toThrow( - 'params mismatch' - ) - transport.bind('left', 'files.list#1', { worktree: 'A' }) - transport.bind('right', 'files.list#2', { worktree: 'B' }) - transport.complete('right', { worktree: 'B' }, { ok: true, result: [] }) - transport.complete('left', { worktree: 'A' }, { ok: true, result: [] }) - await Promise.all([left, right]) - } finally { - await transport.dispose() - await clock.flush() - transport.causality.assertTransparentCalls() - transport.causality.close() - clock.stop() - } - }) -}) diff --git a/mobile/src/transport/connection/client-context.test.ts b/mobile/src/transport/connection/client-context.test.ts index d0faf1fb4b1..8688ab11863 100644 --- a/mobile/src/transport/connection/client-context.test.ts +++ b/mobile/src/transport/connection/client-context.test.ts @@ -47,7 +47,7 @@ vi.mock('../../diagnostics/connection/connection-log-background-flush', () => ({ })) import { RpcClientProvider } from './client-context' -import { useDisconnectHostClient, useForceReconnect, useHostClient } from './host-client-hooks' +import { useDisconnectHostClient, useHostClient } from './host-client-hooks' import { useAllHostClients } from './use-all-host-clients' import { useRelayRecoveryStatus } from './client-context-connection-metrics' @@ -168,45 +168,6 @@ beforeEach(() => { }) describe('useHostClient', () => { - it('shows connecting while a reused screen resolves an uncached host', async () => { - const client = makeFakeClient('connected') - connectMock.mockReturnValue(client) - loadHostsMock.mockResolvedValueOnce([HOST]).mockReturnValueOnce(new Promise(() => {})) - - let selectedHostId = HOST.id - let renderTick = 0 - const stateByRenderTick = new Map() - let renderer: ReactTestRenderer | null = null - function Probe(): null { - stateByRenderTick.set(renderTick, useHostClient(selectedHostId).state) - return null - } - - try { - await act(async () => { - renderer = create(createElement(RpcClientProvider, null, createElement(Probe))) - await Promise.resolve() - }) - expect(stateByRenderTick.get(0)).toBe('connected') - - // Keep host swaps amber during asynchronous profile/keychain loading. - selectedHostId = 'missing-host' - renderTick = 1 - await act(async () => { - renderer?.update(createElement(RpcClientProvider, null, createElement(Probe))) - }) - expect(stateByRenderTick.get(1)).toBe('connecting') - - renderTick = 2 - await act(async () => { - renderer?.update(createElement(RpcClientProvider, null, createElement(Probe))) - }) - expect(stateByRenderTick.get(2)).toBe('connecting') - } finally { - act(() => renderer?.unmount()) - } - }) - it('drops the closed client when the host entry is removed', async () => { const fake = makeFakeClient('connected') connectMock.mockReturnValue(fake) @@ -226,38 +187,6 @@ describe('useHostClient', () => { harness.unmount() }) - - it('keeps Retry amber through forceReconnect instead of grey-then-amber', async () => { - const first = makeFakeClient('connected') - const second = makeFakeClient('connecting') - connectMock.mockReturnValueOnce(first).mockReturnValueOnce(second) - loadHostsMock.mockResolvedValue([HOST]) - - const states: ConnectionState[] = [] - let forceReconnect: ((hostId: string) => Promise) | null = null - let renderer: ReactTestRenderer | null = null - function Probe(): null { - forceReconnect = useForceReconnect() - states.push(useHostClient(HOST.id).state) - return null - } - try { - await act(async () => { - renderer = create(createElement(RpcClientProvider, null, createElement(Probe))) - await Promise.resolve() - }) - expect(states.at(-1)).toBe('connected') - - await act(async () => { - await forceReconnect?.(HOST.id) - }) - expect(first.closeMock).toHaveBeenCalled() - expect(states.at(-1)).toBe('connecting') - expect(states).not.toContain('disconnected') - } finally { - act(() => renderer?.unmount()) - } - }) }) describe('useAllHostClients', () => { diff --git a/mobile/src/transport/connection/mobile-endpoint-supervisor-relay-race.test.ts b/mobile/src/transport/connection/mobile-endpoint-supervisor-relay-race.test.ts index 81ac5496981..8b9eb4e5875 100644 --- a/mobile/src/transport/connection/mobile-endpoint-supervisor-relay-race.test.ts +++ b/mobile/src/transport/connection/mobile-endpoint-supervisor-relay-race.test.ts @@ -3,12 +3,10 @@ import { dependencies, FakeLogicalClient, FakeRelaySession, - FakeSession, host, relay } from './mobile-endpoint-supervisor-test-fakes' import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor' -import { createStableLogicalRpcClient } from './stable-logical-rpc-client' vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' })) @@ -55,58 +53,6 @@ describe('mobile endpoint supervisor relay race after a mid-session LAN loss', ( supervisor.stop() }) - it('paces relay dials by the shared cooldown while relay is also unreachable', async () => { - // A relay socket that never authenticates fails its migration. - const { logical, openRelay, supervisor } = await startOnLan( - vi.fn(() => new FakeRelaySession('connecting')) - ) - - for (let i = 0; i < 60; i++) { - redialDirect(logical) - await vi.advanceTimersByTimeAsync(2_000) - } - - // 60 redials in 2 min; each attempt is a cell dial plus a director-resolved retry. - // Racing every redial would open 120 sockets; the 0.5 s→30 s backoff keeps it under 20. - expect(openRelay.mock.calls.length).toBeGreaterThan(0) - expect(openRelay.mock.calls.length).toBeLessThanOrEqual(20) - supervisor.stop() - }) - - it('races each slow LAN blip once and closes the relay socket the LAN beat', async () => { - // The real logical client owns the lost-race close: it aborts after relay authentication. - const direct = new FakeSession('connected') - const logical = createStableLogicalRpcClient(direct, 'lan') - const relaySessions: FakeRelaySession[] = [] - const openRelay = vi.fn(() => { - const session = new FakeRelaySession('connecting') - relaySessions.push(session) - return session - }) - const supervisor = new MobileEndpointSupervisor( - logical, - host.id, - relay, - dependencies({ openRelay, randomBytes: () => new Uint8Array([255, 255]) }) - ) - await supervisor.start() - - for (let flap = 0; flap < 10; flap++) { - direct.publishState('reconnecting') - direct.publishState('connecting') - await vi.advanceTimersByTimeAsync(3_000) - direct.publishState('connected') - relaySessions.at(-1)?.publishState('connected') - await vi.advanceTimersByTimeAsync(10_000) - } - - // Accepted cost: one relay dial per blip past the 2.5 s head start, each closed once it loses. - expect(openRelay).toHaveBeenCalledTimes(10) - expect(relaySessions.every((session) => session.close.mock.calls.length > 0)).toBe(true) - expect(logical.getActivePath()).toBe('lan') - supervisor.stop() - }) - it('drops a race deferred by cooldown once the LAN comes back', async () => { const { logical, openRelay, supervisor } = await startOnLan( vi.fn(() => new FakeRelaySession('connecting')) diff --git a/mobile/src/transport/hosts/host-endpoint-edit.test.ts b/mobile/src/transport/hosts/host-endpoint-edit.test.ts deleted file mode 100644 index 9608ca495fe..00000000000 --- a/mobile/src/transport/hosts/host-endpoint-edit.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { resolveHostEndpointEdit } from './host-endpoint-edit' - -describe('resolveHostEndpointEdit', () => { - it.each([ - ['ws://192.168.1.10:6768', 'wss://tunnel.example.com', 'wss://tunnel.example.com:443'], - ['wss://old.example.com:8443', ' WSS://tunnel.example.com ', 'wss://tunnel.example.com:443'], - ['ws://192.168.1.10:6768', 'wss://[2001:db8::2]', 'wss://[2001:db8::2]:443'], - ['ws://192.168.1.10:6768', 'wss://tunnel.example.com:9443', 'wss://tunnel.example.com:9443'], - ['ws://192.168.1.10:6768', 'tunnel.example.com', 'ws://tunnel.example.com:6768'], - [ - 'wss://old.example.com:8443/orca?route=runtime', - 'wss://tunnel.example.com', - 'wss://tunnel.example.com:443/orca?route=runtime' - ] - ])( - 'resolves explicit secure URLs independently of the saved port (%s → %s)', - (stored, input, expected) => { - expect(resolveHostEndpointEdit(stored, input)).toEqual({ - kind: 'changed', - endpoint: expected - }) - } - ) - - it.each([ - ['surrounding whitespace', ' desk.example.com '], - ['hostname case', 'DESK.EXAMPLE.COM'], - ['explicit default port', 'desk.example.com:443'], - ['percent-encoded hostname', 'wss://%64esk.example.com:443'] - ])('preserves routed endpoint bytes for equivalent %s', (_label, input) => { - const stored = 'wss://Desk.Example.com/%6Fruntime?route=%72ed' - - expect(resolveHostEndpointEdit(stored, input)).toEqual({ - kind: 'unchanged', - endpoint: stored - }) - }) - - it('preserves the hidden route when the authority changes', () => { - expect( - resolveHostEndpointEdit('wss://old.example.com/%6Fruntime?route=%72ed', 'new.example.com') - ).toEqual({ - kind: 'changed', - endpoint: 'wss://new.example.com:443/%6Fruntime?route=%72ed' - }) - }) -}) diff --git a/mobile/src/transport/hosts/host-endpoint.test.ts b/mobile/src/transport/hosts/host-endpoint.test.ts deleted file mode 100644 index 997286e0981..00000000000 --- a/mobile/src/transport/hosts/host-endpoint.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { displayHostEndpoint, normalizeHostEndpoint } from './host-endpoint' - -describe('normalizeHostEndpoint', () => { - it('preserves explicit ws :80 and wss :443 instead of rewriting to fallback', () => { - expect(normalizeHostEndpoint('ws://192.168.1.10:80', { fallbackPort: '6768' })).toEqual({ - ok: true, - endpoint: 'ws://192.168.1.10:80' - }) - expect(normalizeHostEndpoint('wss://desk.example:443', { fallbackPort: '6768' })).toEqual({ - ok: true, - endpoint: 'wss://desk.example:443' - }) - expect(displayHostEndpoint('ws://192.168.1.10:80')).toBe('192.168.1.10:80') - expect(displayHostEndpoint('wss://desk.example:443')).toBe('desk.example:443') - }) - - it('preserves wss when re-normalizing bare host:port via fallbackScheme', () => { - expect( - normalizeHostEndpoint('desk.example:8443', { fallbackScheme: 'wss', fallbackPort: '8443' }) - ).toEqual({ - ok: true, - endpoint: 'wss://desk.example:8443' - }) - }) -}) diff --git a/mobile/src/transport/hosts/host-name-identity.test.ts b/mobile/src/transport/hosts/host-name-identity.test.ts index f175b608414..0c4878d0ef4 100644 --- a/mobile/src/transport/hosts/host-name-identity.test.ts +++ b/mobile/src/transport/hosts/host-name-identity.test.ts @@ -85,20 +85,6 @@ describe('host name identity', () => { } describe('legacy classification', () => { - it('does not re-classify an adopted machine name once identity fields exist', async () => { - // A record the descriptor writer already touched: non-generated name, no override. - storedHostsRaw = JSON.stringify([ - { - ...GENERATED_HOST, - name: 'm4airs-Air', - lastKnownMachineName: 'm4airs-Air', - lastKnownHostPlatform: 'darwin' - } - ]) - const hosts = await loadHosts() - expect(hosts[0]?.personalName).toBeUndefined() - }) - it('drops only an identity value this build cannot read, never the paired host', async () => { // A newer build's platform, or an empty string, as a rolled-back app would find them. storedHostsRaw = JSON.stringify([ @@ -119,39 +105,7 @@ describe('host name identity', () => { }) }) - describe('updateHostDescriptor', () => { - it('clears a stale machine name when a live host stops reporting one', async () => { - await updateHostDescriptor(GENERATED_HOST.id, { - machineName: 'm4airs-Air', - platform: 'darwin' - }) - await updateHostDescriptor(GENERATED_HOST.id, { machineName: null, platform: 'darwin' }) - const record = stored().find(({ id }) => id === GENERATED_HOST.id) - expect(record?.lastKnownMachineName).toBeUndefined() - expect(record?.name).toBe('m4airs-Air') - }) - }) - describe('re-pair', () => { - it('preserves the override and descriptor a pairing save knows nothing about', async () => { - await updateHostDescriptor(TYPED_HOST.id, { machineName: 'm4airs-Air', platform: 'darwin' }) - await savePairedHost({ - id: TYPED_HOST.id, - name: 'Windows-Low Spec', - endpoint: 'ws://10.0.0.9:6768', - deviceToken: 'fresh-token', - publicKeyB64: TYPED_HOST.publicKeyB64, - lastConnected: 99 - }) - expect(stored().find(({ id }) => id === TYPED_HOST.id)).toMatchObject({ - name: 'Windows-Low Spec', - personalName: 'Windows-Low Spec', - lastKnownMachineName: 'm4airs-Air', - lastKnownHostPlatform: 'darwin', - endpoint: 'ws://10.0.0.9:6768' - }) - }) - it('does not roll back identity changed since a connection took its profile snapshot', async () => { await updateHostDescriptor(TYPED_HOST.id, { machineName: 'Studio', platform: 'darwin' }) // Use a connection-held snapshot to prove saves cannot roll back later identity changes. @@ -168,14 +122,4 @@ describe('host name identity', () => { }) }) }) - - describe('phone override edit', () => { - it('clearing the override returns to the desktop-reported name', async () => { - await updateHostDescriptor(TYPED_HOST.id, { machineName: 'm4airs-Air', platform: 'darwin' }) - await updateHostNameAndEndpoint(TYPED_HOST.id, { personalName: null }) - const record = stored().find(({ id }) => id === TYPED_HOST.id) - expect(record?.personalName).toBeUndefined() - expect(record?.name).toBe('m4airs-Air') - }) - }) }) diff --git a/mobile/src/transport/hosts/host-store-endpoint.test.ts b/mobile/src/transport/hosts/host-store-endpoint.test.ts deleted file mode 100644 index e84ad12e8e4..00000000000 --- a/mobile/src/transport/hosts/host-store-endpoint.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import AsyncStorage from '@react-native-async-storage/async-storage' -import * as SecureStore from 'expo-secure-store' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { loadHosts, resetHostStoreForTests, updateHostNameAndEndpoint } from './host-store' -import { resetMobileRelayHostOverlayStoreForTests } from './mobile-relay-host-overlay-store' - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { - getItem: vi.fn(), - setItem: vi.fn(), - removeItem: vi.fn() - } -})) - -vi.mock('expo-secure-store', () => ({ - getItemAsync: vi.fn(), - setItemAsync: vi.fn(), - deleteItemAsync: vi.fn(), - WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY' -})) - -vi.mock('react-native', () => ({ - Platform: { OS: 'ios' } -})) - -describe('relay routing after a host edit', () => { - const OVERLAY_KEY = 'orca:mobile-relay:host-overlays:v2' - const OLD_ENDPOINT = 'ws://192.168.1.10:6768' - const NEW_ENDPOINT = 'ws://192.168.1.20:6768' - const relay = { - v: 1 as const, - directorUrl: 'https://relay.onorca.dev', - cellUrl: 'https://relay-c1.onorca.dev', - assignmentEpoch: 7, - relayHostId: 'AbCdEf0123_-xyZ9', - e2eeFraming: 2 as const - } - - const storage = new Map() - - beforeEach(() => { - resetHostStoreForTests() - resetMobileRelayHostOverlayStoreForTests() - storage.clear() - storage.set( - 'orca:hosts', - JSON.stringify([ - { id: 'host-1', name: 'Desk', endpoint: OLD_ENDPOINT, publicKeyB64: 'pk', lastConnected: 1 } - ]) - ) - // An older build's record: a copy of the row's address beside the relay. - storage.set( - OVERLAY_KEY, - JSON.stringify([ - { - v: 2, - hostId: 'host-1', - endpoints: [ - { id: 'direct-primary', kind: 'lan', url: OLD_ENDPOINT }, - { id: 'relay-primary', kind: 'relay', url: 'wss://relay-c1.onorca.dev/v1/connect/id' } - ], - relayHostId: relay.relayHostId, - relay - } - ]) - ) - vi.mocked(AsyncStorage.getItem).mockReset() - vi.mocked(AsyncStorage.getItem).mockImplementation(async (key) => storage.get(key) ?? null) - vi.mocked(AsyncStorage.setItem).mockReset() - vi.mocked(AsyncStorage.setItem).mockImplementation(async (key, value) => { - storage.set(key, value) - }) - vi.mocked(SecureStore.getItemAsync).mockResolvedValue('device-token') - vi.mocked(SecureStore.setItemAsync).mockReset() - }) - - it('loads only the edited address, whatever an older overlay stored', async () => { - await updateHostNameAndEndpoint('host-1', { endpoint: NEW_ENDPOINT }) - - const [host] = await loadHosts() - expect(host).toEqual({ - id: 'host-1', - name: 'Desk', - personalName: 'Desk', - endpoint: NEW_ENDPOINT, - publicKeyB64: 'pk', - lastConnected: 1, - deviceToken: 'device-token', - relay - }) - }) -}) diff --git a/mobile/src/transport/hosts/host-store.test.ts b/mobile/src/transport/hosts/host-store.test.ts index e6218ba96e8..04b82058be9 100644 --- a/mobile/src/transport/hosts/host-store.test.ts +++ b/mobile/src/transport/hosts/host-store.test.ts @@ -1,6 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import './mobile-relay-host-overlay' -import type { MobileRelayHostOverlay } from './mobile-relay-host-overlay' const asyncStorageMock = vi.hoisted(() => ({ getItem: vi.fn(), @@ -166,29 +165,6 @@ describe('host-store list mutations', () => { ).resolves.toBe('replacement-token') }) - it('clears stale relay state when an existing host is re-paired direct-only', async () => { - const overlay: MobileRelayHostOverlay = { - v: 2, - hostId: HOST_ONE.id, - endpoints: [ - { id: 'direct-primary', kind: 'lan', url: HOST_ONE.endpoint }, - { - id: 'relay-primary', - kind: 'relay', - url: 'wss://relay-c1.onorca.dev/v1/connect/AbCdEf0123_-xyZ9' - } - ], - relayHostId: HOST_ONE_RELAY.relayHostId, - relay: HOST_ONE_RELAY - } - storedOverlayRaw = JSON.stringify([overlay]) - - await savePairedHost({ ...HOST_ONE, deviceToken: 'replacement-token' }) - - expect(JSON.parse(storedOverlayRaw!)).toEqual([]) - expect(secureStoreMock.deleteItemAsync).not.toHaveBeenCalled() - }) - it('refuses an early same-key token write without durable cleanup intent', async () => { const replacement = { ...HOST_TWO, diff --git a/src/main/claude/claude-informational-row.test.ts b/src/main/claude/claude-informational-row.test.ts deleted file mode 100644 index 8bd8ff68d62..00000000000 --- a/src/main/claude/claude-informational-row.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentSessionJournalIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { openAgentSessionJournal } from '../native-chat/agent-session-journal/journal-store-factory' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' -import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('provider-1', 'leaf-1') -} - -/** Informational frame shape from CLI 2.1.280. */ -function informational( - level: 'info' | 'notice' | 'suggestion' | 'warning', - content: string -): Record { - return { - type: 'system', - subtype: 'informational', - content, - level, - uuid: `5d3c1f0e-7a2b-4c6d-9e8f-00000000000${level.length}`, - session_id: 'provider-1' - } -} - -let root = '' - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-informational-')) -}) - -afterEach(async () => { - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -async function itemsFor(frames: Record[]) { - const journal = await openAgentSessionJournal({ - identity: IDENTITY, - database: openTestJournalHostDatabase(root), - now: () => 1_700_000_000_000, - mintEpoch: () => 'epoch-1' - }) - const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - deferred.bind({ journal, fence: 1, publish: vi.fn() }) - const translator = createClaudeJournalTranslator({ sink: deferred.sink, fallbackIdPrefix: '1' }) - for (const frame of frames) { - translator.handle({ type: 'message', sessionId: 'orca-session', message: frame }) - await deferred.drained() - } - return journal.snapshot().items.map((item) => item.body) -} - -describe('a Claude informational frame', () => { - it.each(['info', 'notice', 'suggestion'] as const)('writes no row at level %s', async (level) => { - expect(await itemsFor([informational(level, `A ${level} note`)])).toEqual([]) - }) - - it('writes its own words as one warning row at level warning', async () => { - const content = - 'UserPromptSubmit operation blocked by hook: secrets are not allowed\n\nOriginal prompt: deploy it' - const items = await itemsFor([informational('warning', content)]) - - expect(items).toEqual([{ kind: 'status', tone: 'warning', text: content }]) - }) -}) diff --git a/src/main/claude/claude-model-catalog-probe.test.ts b/src/main/claude/claude-model-catalog-probe.test.ts index 8cb9dac7e30..e807112bf26 100644 --- a/src/main/claude/claude-model-catalog-probe.test.ts +++ b/src/main/claude/claude-model-catalog-probe.test.ts @@ -55,7 +55,6 @@ describe('claude model catalog probe', () => { it.each([ [[], [], ['/orca-probe', '/orca-probe'], 'user,project,local'], [['node_modules/claude/cli.js'], [], ['/chat-a', '/chat-b'], 'user'], - [['--env-file=work env', '--', 'claude'], [], ['/chat-a', '/chat-b'], 'user'], [[], ['--settings', 'settings.json'], ['/chat-a', '/chat-b'], 'user'] ])( 'lists prefix %j with arguments %j from %j, reading %s settings', diff --git a/src/main/claude/structured/claude-full-access-policy-perf.test.ts b/src/main/claude/structured/claude-full-access-policy-perf.test.ts deleted file mode 100644 index 56db3f993aa..00000000000 --- a/src/main/claude/structured/claude-full-access-policy-perf.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { performance } from 'node:perf_hooks' -import { afterEach, expect, it, vi } from 'vitest' -import { createClaudeFullAccessPolicy } from './claude-full-access-policy' - -const SESSION = '819cf9f8-e43c-4ad7-b50f-54aa158a726a' -const CHUNK_BYTES = 1000 - -afterEach(() => { - vi.restoreAllMocks() -}) - -const line = (frame: Record): string => `${JSON.stringify(frame)}\n` - -type Work = { chars: number; parses: number; newlineSearched: number; screened: number } - -/** Drives the real policy and counts the characters it searches, so a rescan cannot hide in time. */ -function observeWire(frames: number): Work { - const delta = line({ - type: 'stream_event', - event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'ok — '.repeat(8) } }, - session_id: SESSION - }) - // A tool result spanning thousands of chunks, as large file reads do. - const longLine = line({ - type: 'user', - message: { - role: 'user', - content: [{ type: 'tool_result', content: 'y'.repeat(frames * 3000) }] - }, - session_id: SESSION - }) - const expected: [string, boolean][] = [] - let wire = '' - for (let index = 0; index < frames; index += 1) { - wire += delta - if (index % 10 === 0) { - const mode = index % 20 === 0 ? 'plan' : 'bypassPermissions' - wire += line({ type: 'system', subtype: 'status', permissionMode: mode, session_id: SESSION }) - wire += line({ - type: 'control_request', - request_id: `r${index}`, - request: { subtype: 'can_use_tool', tool_name: 'Bash', input: {}, tool_use_id: `t${index}` } - }) - expected.push([`r${index}`, mode === 'bypassPermissions']) - } - if (index === frames / 2) { - wire += longLine - } - } - const bytes = Buffer.from(wire) - const policy = createClaudeFullAccessPolicy(SESSION) - // Node's own internals keep their original string methods, so these count only the policy's calls. - const { indexOf, includes } = String.prototype - let newlineSearched = 0 - let screened = 0 - const parse = vi.spyOn(JSON, 'parse') - const searches = vi.spyOn(String.prototype, 'indexOf').mockImplementation(function ( - this: string, - search: string, - position?: number - ) { - const found = indexOf.call(this, search, position) - newlineSearched += (found === -1 ? this.length : found + search.length) - (position ?? 0) - return found - }) - const screens = vi.spyOn(String.prototype, 'includes').mockImplementation(function ( - this: string, - search: string, - position?: number - ) { - screened += this.length - return includes.call(this, search, position) - }) - - const started = performance.now() - // Fixed-size chunks split frames and multibyte characters, as pipe reads do. - try { - for (let offset = 0; offset < bytes.length; offset += CHUNK_BYTES) { - policy.observe(bytes.subarray(offset, offset + CHUNK_BYTES)) - } - } finally { - searches.mockRestore() - screens.mockRestore() - } - const elapsedMs = performance.now() - started - const parses = parse.mock.calls.length - parse.mockRestore() - const work = { chars: wire.length, parses, newlineSearched, screened } - console.info('claude-full-access-policy-perf', { - frames, - bytes: bytes.length, - ...work, - elapsedMs - }) - - // Newlines are looked for in new text only, and each completed line is screened at most twice, - // checked per size so a rescanning policy fails here before the larger run exhausts memory. - expect(newlineSearched).toBeLessThanOrEqual(wire.length) - expect(screened).toBeLessThanOrEqual(2 * wire.length) - // Only mode reports and permission requests are parsed; deltas and the long line never are. - expect(parses).toBe(expected.length * 2) - // Unread requests stay until the SDK hands each to canUseTool, however many queue up. - expect(policy.retained()).toEqual({ partialChars: 0, requests: expected.length }) - for (const [requestId, fullAccess] of expected) { - expect(policy.allows(requestId), requestId).toBe(fullAccess) - } - expect(policy.retained()).toEqual({ partialChars: 0, requests: 0 }) - return work -} - -it('searches each stdout character a bounded number of times, however long a line grows', () => { - const small = observeWire(300) - const large = observeWire(3000) - // Ten times the output, including a ten times longer line, costs ten times the work. - expect(large.newlineSearched).toBeLessThanOrEqual(10 * small.newlineSearched + CHUNK_BYTES) - expect(large.screened).toBeLessThanOrEqual(10 * small.screened + CHUNK_BYTES) - expect(large.parses).toBe(10 * small.parses) -}) diff --git a/src/main/claude/structured/claude-structured-execution-recording.test.ts b/src/main/claude/structured/claude-structured-execution-recording.test.ts index bc2b1f50b73..b20f110b9e6 100644 --- a/src/main/claude/structured/claude-structured-execution-recording.test.ts +++ b/src/main/claude/structured/claude-structured-execution-recording.test.ts @@ -14,7 +14,7 @@ import { HOST_TEST_SESSION as SESSION } from '../../native-chat/agent-session-wi const claudeTurnEnds = (connection: Parameters[0]) => claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' }) -it.each(['low', 'high', undefined])( +it.each(['high', undefined])( 'admits accepted high independently of resolved effort (effective %s)', async (effective) => { const models = [ diff --git a/src/main/claude/structured/launch/claude-structured-applied-options.test.ts b/src/main/claude/structured/launch/claude-structured-applied-options.test.ts index ac112bb968c..07b4c3e57a3 100644 --- a/src/main/claude/structured/launch/claude-structured-applied-options.test.ts +++ b/src/main/claude/structured/launch/claude-structured-applied-options.test.ts @@ -46,16 +46,6 @@ const SETTINGS = { effective: { model: 'haiku' }, sources: [{ source: 'userSettings', settings: { model: 'haiku' } }], applied: { model: 'claude-haiku-4-5-20251001', effort: null, advisor: null, ultracode: false } - }, - envSonnet: { - effective: {}, - sources: [], - applied: { model: 'claude-sonnet-5', effort: 'high', advisor: null, ultracode: false } - }, - settingsHaikuEnvSonnet: { - effective: { model: 'haiku' }, - sources: [{ source: 'userSettings', settings: { model: 'haiku' } }], - applied: { model: 'claude-sonnet-5', effort: 'high', advisor: null, ultracode: false } } } @@ -69,29 +59,7 @@ function startedWithoutATurn(settings: unknown) { }) } -async function readCurrent(settings: unknown) { - const adapter = await acquired(startedWithoutATurn(settings)) - return (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current -} - describe('Claude model before the first turn', () => { - it.each([ - ['nothing overrides the default', SETTINGS.noOverride, 'claude-opus-5-5[1m]', 'medium'], - ['settings name a model', SETTINGS.settingsHaiku, 'claude-haiku-4-5-20251001', undefined], - ['the env names a model', SETTINGS.envSonnet, 'claude-sonnet-5', 'high'], - ['the env overrides the settings', SETTINGS.settingsHaikuEnvSonnet, 'claude-sonnet-5', 'high'] - ])( - 'names what Claude will apply when %s, unconfirmed', - async (_case, settings, model, effort) => { - const current = await readCurrent(settings) - - expect(current.model).toBe(model) - expect(current.effort).toBe(effort) - expect(current.confirmed ?? []).not.toContain('model') - expect(current.confirmed ?? []).not.toContain('effort') - } - ) - it('uses native applied effort despite settings High, before and after a reply', async () => { // Claude Code 2.1.318: no flag applies Medium; --effort low applies Low. const claude = startedWithoutATurn({ @@ -156,13 +124,6 @@ describe('Claude model before the first turn', () => { await adapter.closeAll() }) - it('marks an unknown applied model as defaulted for the host to resolve', async () => { - const current = await readCurrent({ effective: {}, sources: [] }) - - expect(current.defaulted).toEqual(['model']) - expect(current.effort).toBeUndefined() - }) - it('lets the first turn confirm or correct it', async () => { const claude = startedWithoutATurn(SETTINGS.settingsHaiku) const adapter = await acquired(claude) diff --git a/src/main/claude/structured/launch/claude-structured-child-env.test.ts b/src/main/claude/structured/launch/claude-structured-child-env.test.ts index 006cd0f2a6e..6241c13d929 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.test.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.test.ts @@ -32,7 +32,7 @@ it('resolves a custom Claude command against the login shell PATH', async () => } }) -it('names Orca as the Claude client unless the launch environment sets one', () => { +it('isolates inherited Claude stamps before applying launch settings', () => { const sources = { command: 'claude', prefixArgs: [], diff --git a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts index d3fb98dccf4..47779af453c 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts @@ -15,12 +15,7 @@ const MODEL_ROW = { } describe('codex model catalog probe', () => { - it.each([ - [[]], - [['node_modules/@openai/codex/bin/codex.js']], - [['--env-file=work env', '--', 'codex']], - [['-c', 'model_instructions_file="./prompt.md"']] - ])( + it.each([[[]]])( "lists a command line with arguments %j from Orca's folder for every chat", async (prefixArgs) => { // The chat's repo never picks the list, so no listing runs in a chat's folder. diff --git a/src/main/daemon/providers/adapter/daemon-preserved-endpoint-loss.ts b/src/main/daemon/providers/adapter/daemon-preserved-endpoint-loss.ts new file mode 100644 index 00000000000..9d9e305a481 --- /dev/null +++ b/src/main/daemon/providers/adapter/daemon-preserved-endpoint-loss.ts @@ -0,0 +1,60 @@ +import { isDaemonEndpointGoneError } from '../../protocol/daemon-errors' +import { inspectProcessSignal } from '../../endpoint/identity/daemon-process-inspection' + +/** + * Delays between reconnect attempts after a preserved daemon's connection drops; the last repeats. + * Loss needs this many attempts in a row to find the endpoint refused or missing: a timeout or any + * other error cannot tell a busy host from a dead one, so it restarts the count. + */ +export const PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS: readonly number[] = [ + 500, 2_000, 5_000, 30_000 +] +export const PRESERVED_ENDPOINT_LOSS_REQUIRED_GONE = 3 + +export type PreservedEndpointLossVerdict = 'gone' | 'reachable' | 'abandoned' + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +/** + * A gone endpoint alone does not prove the process is gone on POSIX: its socket name can be + * unlinked under a live daemon. A Windows pipe exists only while its server handle is open, and + * PID reuse makes a PID probe unsound there, so the missing pipe is the proof. + */ +export function preservedDaemonProcessExited(pid: number | undefined): boolean { + if (process.platform === 'win32') { + return true + } + return pid !== undefined && inspectProcessSignal(pid) === 'missing' +} + +/** Decide whether a daemon Orca cannot respawn is gone for good, so its PTYs can end as host loss. */ +export async function confirmPreservedEndpointLoss(args: { + connect: () => Promise + shouldContinue: () => boolean + processExited: () => boolean + delaysMs?: readonly number[] + requiredGone?: number + sleep?: (ms: number) => Promise +}): Promise { + const sleep = args.sleep ?? delay + const delays = args.delaysMs ?? PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS + const requiredGone = args.requiredGone ?? PRESERVED_ENDPOINT_LOSS_REQUIRED_GONE + let gone = 0 + for (let attempt = 0; ; attempt++) { + await sleep(delays[Math.min(attempt, delays.length - 1)] ?? 0) + if (!args.shouldContinue()) { + return 'abandoned' + } + try { + await args.connect() + return 'reachable' + } catch (error) { + gone = isDaemonEndpointGoneError(error) && args.processExited() ? gone + 1 : 0 + } + if (gone >= requiredGone) { + return 'gone' + } + } +} diff --git a/src/main/daemon/providers/adapter/daemon-pty-adapter-options.ts b/src/main/daemon/providers/adapter/daemon-pty-adapter-options.ts index cfa65471e1d..b70e83de8f2 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-adapter-options.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-adapter-options.ts @@ -15,6 +15,10 @@ export type DaemonPtyAdapterOptions = { readRunningWslDistros?: ReadRunningWslDistros /** Test seam; production reads each distro's boot id through the background-work gate. */ wslBridgeBootIdentity?: WslBridgeBootIdentity + /** Test seam; delays before each reconnect attempt to a dead daemon that cannot respawn. */ + preservedEndpointLossProbeDelaysMs?: readonly number[] + /** Test seam; whether a preserved daemon's process is proven gone, given its last pid. */ + preservedDaemonExited?: (pid: number | undefined) => boolean } export type DaemonRespawnReason = diff --git a/src/main/daemon/providers/adapter/daemon-pty-adapter.ts b/src/main/daemon/providers/adapter/daemon-pty-adapter.ts index 27c7825a371..3512c3e1298 100644 --- a/src/main/daemon/providers/adapter/daemon-pty-adapter.ts +++ b/src/main/daemon/providers/adapter/daemon-pty-adapter.ts @@ -12,7 +12,7 @@ import type { DaemonPtyRouterExitEvent } from '../../protocol/daemon-pty-router- import { logWslPaneDiagnostic } from '../wsl/daemon-wsl-diagnostic-log' import { classifyWslBridgeExit, WSL_DISTRO_LOSS_EXIT_CODE } from '../wsl/daemon-wsl-bridge-exit' import { isProvenProcessExit } from '../../../../shared/terminal/pty/lifecycle/terminal-exit-cause' -import { DaemonPtyDaemonRecovery } from './daemon-pty-daemon-recovery' +import { DaemonPtyPreservedHostLoss } from './daemon-pty-preserved-host-loss' import type { DaemonPtyAdapterOptions } from './daemon-pty-adapter-options' import type { DaemonEvent } from '../../protocol/daemon-stream-events' @@ -34,7 +34,7 @@ import type { import { observeDaemonAsyncIoHealth } from '../../observability/daemon-async-io-telemetry-event' import { sameEndpointIdentity } from '../../endpoint/identity/daemon-endpoint-incarnation' -export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyProvider { +export class DaemonPtyAdapter extends DaemonPtyPreservedHostLoss implements IPtyProvider { constructor(opts: DaemonPtyAdapterOptions) { super(opts) // Registered after the base listener, which marks the sessions awaiting recovery first. diff --git a/src/main/daemon/providers/adapter/daemon-pty-preserved-host-loss.ts b/src/main/daemon/providers/adapter/daemon-pty-preserved-host-loss.ts new file mode 100644 index 00000000000..9e319de1a6c --- /dev/null +++ b/src/main/daemon/providers/adapter/daemon-pty-preserved-host-loss.ts @@ -0,0 +1,98 @@ +import { createPtyExitPayload, emitPtyListeners } from './daemon-pty-listener-emission' +import { DaemonPtyDaemonRecovery } from './daemon-pty-daemon-recovery' +import type { DaemonPtyAdapterOptions } from './daemon-pty-adapter-options' +import { + confirmPreservedEndpointLoss, + PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS, + preservedDaemonProcessExited +} from './daemon-preserved-endpoint-loss' + +/** + * A daemon kept from an older Orca version has no respawn. Why (#38432): when it died, nothing + * ended its PTYs, so every pane stayed "connected" on a frozen frame and input went nowhere. + */ +export abstract class DaemonPtyPreservedHostLoss extends DaemonPtyDaemonRecovery { + private readonly preservedEndpointLossProbeDelaysMs: readonly number[] + private readonly preservedDaemonExited: (pid: number | undefined) => boolean + private preservedEndpointLossProbe: Promise | null = null + /** Set once this adapter ended its sessions because its endpoint stayed gone. */ + private preservedEndpointLossDeclared = false + + constructor(opts: DaemonPtyAdapterOptions) { + super(opts) + this.preservedEndpointLossProbeDelaysMs = + opts.preservedEndpointLossProbeDelaysMs ?? PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS + this.preservedDaemonExited = opts.preservedDaemonExited ?? preservedDaemonProcessExited + } + + protected recoverAfterEndpointLoss(): void { + if (this.respawnFn || this.activeSessionIds.size === 0) { + super.recoverAfterEndpointLoss() + return + } + this.confirmPreservedDaemonLoss() + } + + // A host proven gone runs no session, so restores (attached or not) route to the current daemon. + async probePtyLiveness(id: string): Promise { + return this.isProvenGone() ? false : await super.probePtyLiveness(id) + } + + listsSession(id: string): Promise { + return this.isProvenGone() ? Promise.resolve(false) : super.listsSession(id) + } + + /** Proven gone and not reconnected since; a later reconnect restores the daemon's own answers. */ + private isProvenGone(): boolean { + return this.preservedEndpointLossDeclared && !this.client.isConnected() + } + + private confirmPreservedDaemonLoss(): void { + if (this.preservedEndpointLossProbe || this.respawnAdoptionClosed) { + return + } + const stillLost = (): boolean => + !this.respawnAdoptionClosed && this.activeSessionIds.size > 0 && !this.client.isConnected() + const probe = confirmPreservedEndpointLoss({ + connect: () => this.ensureConnected(), + shouldContinue: stillLost, + processExited: () => this.preservedDaemonExited(this.lastAuthenticatedIdentity?.pid), + delaysMs: this.preservedEndpointLossProbeDelaysMs + }) + .then((verdict) => { + if (verdict === 'gone' && stillLost()) { + this.endPreservedSessionsAsHostLoss() + } + }) + .catch((error) => console.warn('[daemon] Preserved terminal host loss check failed:', error)) + .finally(() => { + if (this.preservedEndpointLossProbe === probe) { + this.preservedEndpointLossProbe = null + } + }) + this.preservedEndpointLossProbe = probe + } + + /** Each PTY ends as host loss with its history kept, so its pane can cold-restore. */ + private endPreservedSessionsAsHostLoss(): void { + const ids = [...this.activeSessionIds] + console.warn( + `[daemon] Terminal host v${this.protocolVersion} is gone - ending ${ids.length} session${ids.length === 1 ? '' : 's'} as host loss` + ) + this.preservedEndpointLossDeclared = true + const exits = ids.map((id) => { + const incarnationId = this.sessionIncarnations.get(id) + this.hostLossSessionIds.add(id) + this.clearExitedSessionState(id, -1, incarnationId, { closeHistory: false }) + return createPtyExitPayload(id, { code: -1, incarnationId, hostLost: true }) + }) + // State is settled for every session first, so one throwing listener cannot strand the rest. + for (const exit of exits) { + try { + emitPtyListeners(this.exitListeners, (listener) => listener(exit)) + } catch (error) { + console.warn('[daemon] Host-loss exit listener failed:', exit.id, error) + } + } + } +} diff --git a/src/main/daemon/providers/adapter/testing/daemon-preserved-endpoint-loss.test.ts b/src/main/daemon/providers/adapter/testing/daemon-preserved-endpoint-loss.test.ts new file mode 100644 index 00000000000..695a19e38e7 --- /dev/null +++ b/src/main/daemon/providers/adapter/testing/daemon-preserved-endpoint-loss.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { confirmPreservedEndpointLoss } from '../daemon-preserved-endpoint-loss' +import { DaemonProtocolError } from '../../../protocol/daemon-errors' + +function connectError(code: string): Error { + return Object.assign(new Error(`connect ${code}`), { code, syscall: 'connect' }) +} + +const sleep = async (): Promise => {} + +/** Replays connect outcomes in order; once spent, the caller no longer needs a verdict. */ +function script(outcomes: (Error | 'ok')[]) { + let index = 0 + return { + connect: async () => { + const outcome = outcomes[index++] + if (outcome instanceof Error) { + throw outcome + } + }, + shouldContinue: () => index < outcomes.length + } +} + +describe('confirmPreservedEndpointLoss', () => { + it('is gone after three refused or missing attempts in a row with the process gone', async () => { + const run = script([ + connectError('ECONNREFUSED'), + connectError('ENOENT'), + connectError('ECONNREFUSED') + ]) + await expect( + confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) + ).resolves.toBe('gone') + }) + + it('restarts the count on a timeout or other failure instead of reading it as death', async () => { + const run = script([ + connectError('ENOENT'), + connectError('ENOENT'), + new DaemonProtocolError('Connection timed out'), + connectError('EPERM'), + connectError('ENOENT'), + connectError('ENOENT') + ]) + await expect( + confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) + ).resolves.toBe('abandoned') + }) + + it('keeps checking after an unproven attempt, so a host that dies later is still caught', async () => { + const run = script([ + new DaemonProtocolError('Connection timed out'), + connectError('ENOENT'), + connectError('ENOENT'), + connectError('ENOENT'), + connectError('ENOENT') + ]) + await expect( + confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) + ).resolves.toBe('gone') + }) + + it('never declares loss while the daemon process may still be alive', async () => { + const run = script(Array.from({ length: 10 }, () => connectError('ECONNREFUSED'))) + await expect( + confirmPreservedEndpointLoss({ ...run, processExited: () => false, delaysMs: [1], sleep }) + ).resolves.toBe('abandoned') + }) + + it('stops when the host answers again', async () => { + const run = script([connectError('ECONNREFUSED'), 'ok', connectError('ECONNREFUSED')]) + await expect( + confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) + ).resolves.toBe('reachable') + }) +}) diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-preserved-host-loss.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-preserved-host-loss.test.ts new file mode 100644 index 00000000000..b9aadc7a2b4 --- /dev/null +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-preserved-host-loss.test.ts @@ -0,0 +1,171 @@ +// #38432: after an update keeps the previous version's terminal host, that host dying left its +// panes "connected" on a frozen frame. Simulates the upgrade with live sessions on both hosts. +import '../../../pty-subprocess/testing/mock-descendant-sweep' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { DaemonPtyAdapter } from '../daemon-pty-adapter' +import { DaemonPtyRouter } from '../../routing/daemon-pty-router' +import { DaemonServer } from '../../../server/daemon-server' +import { PROTOCOL_VERSION } from '../../../protocol/daemon-protocol-version' +import { getDaemonSocketPath } from '../../../launch/daemon-spawner' +import type { DaemonFileLog } from '../../../observability/daemon-file-log' +import type { DaemonPtyRouterExitEvent } from '../../../protocol/daemon-pty-router-events' +import { createMockSubprocess } from './daemon-pty-adapter-test-harness' + +const LEGACY_PROTOCOL = PROTOCOL_VERSION - 1 + +type ClientInternals = { + handleDisconnect: (generation: number) => void + connectionGeneration: number + isConnected: () => boolean +} + +function adapterClient(adapter: DaemonPtyAdapter): ClientInternals { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the adapter's own DaemonClient to drop only its transport, as a broken pipe would. + const internals = adapter as unknown as { client: ClientInternals } + return internals.client +} + +describe('a preserved older-version terminal host that dies', () => { + const servers: DaemonServer[] = [] + const adapters: DaemonPtyAdapter[] = [] + const directories: string[] = [] + let router: DaemonPtyRouter | null = null + + afterEach(async () => { + router?.dispose() + router = null + for (const adapter of adapters.splice(0)) { + adapter.dispose() + } + await Promise.all(servers.splice(0).map((server) => server.shutdown().catch(() => {}))) + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } + }) + + async function upgradeWithLiveSessions() { + const directory = mkdtempSync(join(tmpdir(), 'daemon-preserved-host-loss-')) + directories.push(directory) + const log: DaemonFileLog = { log: () => {}, close: () => {} } + const legacySocketPath = getDaemonSocketPath(directory, LEGACY_PROTOCOL) + const currentSocketPath = getDaemonSocketPath(directory, PROTOCOL_VERSION) + const legacyTokenPath = join(directory, 'legacy.token') + const currentTokenPath = join(directory, 'current.token') + const legacySubprocesses: ReturnType[] = [] + const currentSubprocesses: ReturnType[] = [] + const legacyServer = new DaemonServer({ + socketPath: legacySocketPath, + tokenPath: legacyTokenPath, + protocolVersion: LEGACY_PROTOCOL, + log, + spawnSubprocess: () => { + const subprocess = createMockSubprocess() + legacySubprocesses.push(subprocess) + return subprocess + } + }) + const currentServer = new DaemonServer({ + socketPath: currentSocketPath, + tokenPath: currentTokenPath, + protocolVersion: PROTOCOL_VERSION, + log, + spawnSubprocess: () => { + const subprocess = createMockSubprocess() + currentSubprocesses.push(subprocess) + return subprocess + } + }) + servers.push(legacyServer, currentServer) + await Promise.all([legacyServer.start(), currentServer.start()]) + + // The previous app version starts two agent panes on its own host, then quits to update. + const oldApp = new DaemonPtyAdapter({ + socketPath: legacySocketPath, + tokenPath: legacyTokenPath, + protocolVersion: LEGACY_PROTOCOL + }) + adapters.push(oldApp) + const first = await oldApp.spawn({ sessionId: 'agent-1', cols: 80, rows: 24 }) + const second = await oldApp.spawn({ sessionId: 'agent-2', cols: 80, rows: 24 }) + oldApp.dispose() + + // The updated app keeps the old host (no respawn) and starts its own. + const legacy = new DaemonPtyAdapter({ + socketPath: legacySocketPath, + tokenPath: legacyTokenPath, + protocolVersion: LEGACY_PROTOCOL, + runtimeDir: directory, + preservedEndpointLossProbeDelaysMs: [5], + // The fixture host shares this test's pid, so its exit is stubbed as proven. + preservedDaemonExited: () => true + }) + const current = new DaemonPtyAdapter({ + socketPath: currentSocketPath, + tokenPath: currentTokenPath, + protocolVersion: PROTOCOL_VERSION, + runtimeDir: directory + }) + adapters.push(legacy, current) + router = new DaemonPtyRouter({ current, legacy: [legacy] }) + await router.discoverLegacySessions() + const exits: DaemonPtyRouterExitEvent[] = [] + router.onExit((payload) => exits.push(payload)) + for (const session of [first, second]) { + await router.spawn({ sessionId: session.id, cols: 80, rows: 24, attachOnly: true }) + } + const fresh = await router.spawn({ sessionId: 'new-pane', cols: 80, rows: 24 }) + return { + router, + legacy, + legacyServer, + legacySubprocesses, + currentSubprocesses, + exits, + first, + second, + fresh + } + } + + it('ends each of its PTYs as host loss, and the panes restore on the current host', async () => { + const run = await upgradeWithLiveSessions() + expect(run.legacySubprocesses).toHaveLength(2) + expect(run.currentSubprocesses).toHaveLength(1) + + // The old host dies: its socket stays behind but nothing listens. + await run.legacyServer.shutdown() + + await vi.waitFor(() => expect(run.exits).toHaveLength(2), { timeout: 3_000 }) + expect(run.exits).toEqual( + expect.arrayContaining([ + { id: run.first.id, code: -1, incarnationId: run.first.incarnationId, hostLost: true }, + { id: run.second.id, code: -1, incarnationId: run.second.incarnationId, hostLost: true } + ]) + ) + // The current host's pane is untouched. + expect(run.exits.some((exit) => exit.id === run.fresh.id)).toBe(false) + expect(run.router.hasPty(run.fresh.id)).toBe(true) + + // Restoring the pane must not be refused because the dead host cannot answer. + const restored = await run.router.spawn({ sessionId: run.first.id, cols: 80, rows: 24 }) + expect(restored.id).toBe(run.first.id) + expect(run.currentSubprocesses).toHaveLength(2) + }) + + it('keeps the panes when the host answers again before the loss is proven', async () => { + const run = await upgradeWithLiveSessions() + // Drop only the connection; the host and its PTYs keep running. + const client = adapterClient(run.legacy) + client.handleDisconnect(client.connectionGeneration) + expect(client.isConnected()).toBe(false) + + // The first probe reconnects, which settles the check without a verdict of loss. + await vi.waitFor(() => expect(client.isConnected()).toBe(true)) + expect(run.exits).toEqual([]) + expect(run.router.hasPty(run.first.id)).toBe(true) + expect(run.router.hasPty(run.second.id)).toBe(true) + }) +}) diff --git a/src/main/rate-limits/providers/codex/codex-fetcher-auth-errors.test.ts b/src/main/rate-limits/providers/codex/codex-fetcher-auth-errors.test.ts deleted file mode 100644 index 3561c7344a8..00000000000 --- a/src/main/rate-limits/providers/codex/codex-fetcher-auth-errors.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { childSpawnMock, resolveCodexCommandMock, ptySpawnMock } = vi.hoisted(() => ({ - childSpawnMock: vi.fn(), - resolveCodexCommandMock: vi.fn(), - ptySpawnMock: vi.fn() -})) - -// Keep child-process assertions in this suite; worker transport is covered separately. -vi.mock( - '../../../worker-thread-child-process/worker-thread-child-process', - () => - import('../../../worker-thread-child-process/worker-thread-child-process-in-process.test-fixtures') -) -vi.mock('node:child_process', () => ({ - spawn: childSpawnMock -})) - -// Mock recovery so its process-table import does not require real execFile. -vi.mock('../../../codex/history/index/codex-state-db-backfill-recovery', () => ({ - startCodexStateDbBackfillRecoveryInBackground: vi.fn() -})) - -vi.mock('../../../codex-cli/command', () => ({ - resolveCodexCommand: resolveCodexCommandMock -})) - -vi.mock('node-pty', () => ({ - spawn: ptySpawnMock -})) - -vi.mock('./codex-auth-presence', () => ({ - probeCodexAuthPresence: vi.fn(() => 'present') -})) - -import { fetchCodexRateLimits } from './codex-fetcher' - -function makeRpcChild() { - const child = new EventEmitter() as EventEmitter & { - stdout: EventEmitter - stderr: EventEmitter - stdin: EventEmitter & { write: ReturnType; end: ReturnType } - kill: ReturnType - exitCode: number | null - } - child.stdout = new EventEmitter() - child.stderr = new EventEmitter() - // Graceful shutdown must wait for EOF/signal to produce exit, as real app-server does. - const exitNow = (): void => { - child.exitCode = 0 - child.emit('exit', 0, null) - } - child.stdin = Object.assign(new EventEmitter(), { write: vi.fn(), end: vi.fn(exitNow) }) - child.exitCode = null - child.kill = vi.fn(() => { - exitNow() - return true - }) - return child -} - -describe('fetchCodexRateLimits auth errors', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.clearAllMocks() - resolveCodexCommandMock.mockReturnValue('codex') - vi.stubGlobal('fetch', vi.fn()) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('returns Codex RPC auth refresh errors without masking them behind a fallback', async () => { - const rpcChild = makeRpcChild() - const authError = - 'Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.' - - childSpawnMock.mockReturnValue(rpcChild) - rpcChild.stdin.write.mockImplementation((line: string) => { - const msg = JSON.parse(line) as { id?: number; method?: string } - if (msg.method === 'initialize') { - setTimeout(() => { - rpcChild.stdout.emit( - 'data', - Buffer.from(`${JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: {} })}\n`) - ) - }, 0) - } - if (msg.method === 'account/rateLimits/read') { - setTimeout(() => { - rpcChild.stdout.emit( - 'data', - Buffer.from( - `${JSON.stringify({ - jsonrpc: '2.0', - id: msg.id, - error: { code: -32000, message: authError } - })}\n` - ) - ) - }, 0) - } - }) - - const resultPromise = fetchCodexRateLimits() - await vi.advanceTimersByTimeAsync(1) - await vi.advanceTimersByTimeAsync(1) - - await expect(resultPromise).resolves.toMatchObject({ - provider: 'codex', - session: null, - weekly: null, - status: 'error', - error: authError - }) - expect(fetch).not.toHaveBeenCalled() - expect(ptySpawnMock).not.toHaveBeenCalled() - }) - - it('returns the app-server chatgpt-auth-required error without falling back', async () => { - const rpcChild = makeRpcChild() - const authError = 'chatgpt authentication required to read rate limits' - - childSpawnMock.mockReturnValue(rpcChild) - rpcChild.stdin.write.mockImplementation((line: string) => { - const msg = JSON.parse(line) as { id?: number; method?: string } - if (msg.method === 'initialize') { - setTimeout(() => { - rpcChild.stdout.emit( - 'data', - Buffer.from(`${JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: {} })}\n`) - ) - }, 0) - } - if (msg.method === 'account/rateLimits/read') { - setTimeout(() => { - rpcChild.stdout.emit( - 'data', - Buffer.from( - `${JSON.stringify({ - jsonrpc: '2.0', - id: msg.id, - error: { code: -32600, message: authError } - })}\n` - ) - ) - }, 0) - } - }) - - const resultPromise = fetchCodexRateLimits() - await vi.advanceTimersByTimeAsync(1) - await vi.advanceTimersByTimeAsync(1) - - await expect(resultPromise).resolves.toMatchObject({ - provider: 'codex', - session: null, - weekly: null, - status: 'error', - error: authError - }) - expect(fetch).not.toHaveBeenCalled() - expect(ptySpawnMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/rate-limits/providers/codex/codex-fetcher-process-contract.test.ts b/src/main/rate-limits/providers/codex/codex-fetcher-process-contract.test.ts deleted file mode 100644 index 58dedbdcc78..00000000000 --- a/src/main/rate-limits/providers/codex/codex-fetcher-process-contract.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RunProcess from '@orca/process-host' - -const { ptySpawnMock, resolveCodexCommandMock, stubScript } = vi.hoisted(() => ({ - stubScript: { path: '' }, - ptySpawnMock: vi.fn(), - resolveCodexCommandMock: vi.fn() -})) - -// Run the Node fixture through the real process chokepoint; worker transport has separate coverage. -vi.mock( - '../../../worker-thread-child-process/worker-thread-child-process', - () => - import('../../../worker-thread-child-process/worker-thread-child-process-in-process.test-fixtures') -) -vi.mock('@orca/process-host', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - spawnProcess: (spec: Parameters[0]) => - actual.spawnProcess({ - ...spec, - program: process.execPath, - args: [stubScript.path, ...(spec.args ?? [])] - }) - } -}) - -vi.mock('../../../codex-cli/command', () => ({ - resolveCodexCommand: resolveCodexCommandMock -})) - -vi.mock('node-pty', () => ({ - spawn: ptySpawnMock -})) - -vi.mock('./codex-auth-presence', () => ({ - probeCodexAuthPresence: vi.fn(() => 'present') -})) - -vi.mock('../../../codex/history/index/codex-state-db', () => ({ - isCodexStateDbBackfillPending: vi.fn(() => false) -})) - -vi.mock('../../../codex/history/index/codex-state-db-backfill-recovery', () => ({ - startCodexStateDbBackfillRecoveryInBackground: vi.fn(() => Promise.resolve(null)) -})) - -import { fetchCodexRateLimits } from './codex-fetcher' - -const STUB_CODEX_SOURCE = ` -const expectedArgs = [ - '-c', - 'approval_policy=never', - '-c', - 'features.plugins=false', - '-s', - 'read-only', - '-a', - 'never', - 'app-server' -] -if (JSON.stringify(process.argv.slice(2)) !== JSON.stringify(expectedArgs)) { - process.stderr.write( - "error: invalid value 'untrusted' for '--ask-for-approval '\\n" + - ' [possible values: on-request, never]\\n' - ) - process.exit(2) -} -if (process.env.CODEX_HOME !== process.env.ORCA_EXPECTED_CODEX_HOME) { - process.stderr.write('managed CODEX_HOME was not preserved\\n') - process.exit(3) -} -if (process.env.ORCA_EXPECTED_PROXY_ENV) { - for (const [key, value] of Object.entries(JSON.parse(process.env.ORCA_EXPECTED_PROXY_ENV))) { - if (process.env[key] !== value) { - process.stderr.write('probe proxy environment mismatch: ' + key + '\\n') - process.exit(4) - } - } -} -let buffer = '' -function send(message) { - process.stdout.write(JSON.stringify(message) + '\\n') -} -process.stdin.setEncoding('utf8') -process.stdin.on('data', (chunk) => { - buffer += chunk - let newlineIndex - while ((newlineIndex = buffer.indexOf('\\n')) !== -1) { - const line = buffer.slice(0, newlineIndex).trim() - buffer = buffer.slice(newlineIndex + 1) - if (!line) continue - const message = JSON.parse(line) - if (message.method === 'initialize') { - send({ id: message.id, result: { userAgent: 'codex-contract/0.149.0' } }) - continue - } - if (message.method === 'account/rateLimits/read') { - send({ - id: message.id, - result: { - rateLimits: { - primary: { usedPercent: 17, windowDurationMins: 300 }, - secondary: { usedPercent: 29, windowDurationMins: 10080 } - } - } - }) - } - } -}) -process.stdin.on('end', () => process.exit(0)) -` - -let tempRoot: string -let stubPath: string -let previousExpectedHome: string | undefined - -describe('Codex rate-limit process contract', () => { - beforeEach(() => { - tempRoot = mkdtempSync(join(tmpdir(), 'orca-codex-rate-limit-contract-')) - stubPath = join(tempRoot, 'codex-contract.cjs') - writeFileSync(stubPath, STUB_CODEX_SOURCE) - previousExpectedHome = process.env.ORCA_EXPECTED_CODEX_HOME - process.env.ORCA_EXPECTED_CODEX_HOME = join(tempRoot, 'managed-codex-home') - resolveCodexCommandMock.mockReturnValue('codex') - stubScript.path = stubPath - }) - - afterEach(() => { - vi.unstubAllEnvs() - if (previousExpectedHome === undefined) { - delete process.env.ORCA_EXPECTED_CODEX_HOME - } else { - process.env.ORCA_EXPECTED_CODEX_HOME = previousExpectedHome - } - rmSync(tempRoot, { recursive: true, force: true }) - vi.clearAllMocks() - }) - - it('starts a read-only non-interactive app-server with the managed home', async () => { - await expect( - fetchCodexRateLimits({ - codexHomePath: process.env.ORCA_EXPECTED_CODEX_HOME - }) - ).resolves.toMatchObject({ - provider: 'codex', - session: { usedPercent: 17, windowMinutes: 300 }, - weekly: { usedPercent: 29, windowMinutes: 10080 }, - status: 'ok', - error: null - }) - expect(ptySpawnMock).not.toHaveBeenCalled() - }) - - it.each(['localhost;*.fixture.invalid', ''])( - 'passes configured proxy and bypass %j to the actual probe', - async (bypassRules) => { - const proxy = 'http://proxy.fixture.invalid:8080' - const expected = { - HTTP_PROXY: proxy, - HTTPS_PROXY: proxy, - ALL_PROXY: proxy, - http_proxy: proxy, - https_proxy: proxy, - all_proxy: proxy, - NO_PROXY: bypassRules.replaceAll(';', ','), - no_proxy: bypassRules.replaceAll(';', ',') - } - vi.stubEnv('NO_PROXY', 'inherited.invalid') - vi.stubEnv('no_proxy', 'inherited.invalid') - vi.stubEnv('ORCA_EXPECTED_PROXY_ENV', JSON.stringify(expected)) - - await expect( - fetchCodexRateLimits({ - codexHomePath: process.env.ORCA_EXPECTED_CODEX_HOME, - networkProxySettings: { httpProxyUrl: proxy, httpProxyBypassRules: bypassRules } - }) - ).resolves.toMatchObject({ status: 'ok', session: { usedPercent: 17 } }) - expect(process.env.NO_PROXY).toBe('inherited.invalid') - } - ) - - it.each([undefined, { httpProxyUrl: '' }, { httpProxyUrl: 'file:///invalid-proxy' }])( - 'preserves inherited proxy settings when app settings are unset or invalid: %j', - async (networkProxySettings) => { - const inherited = { - HTTPS_PROXY: 'http://inherited.fixture.invalid:8080', - NO_PROXY: 'fixture.invalid' - } - for (const [key, value] of Object.entries(inherited)) { - vi.stubEnv(key, value) - } - vi.stubEnv('ORCA_EXPECTED_PROXY_ENV', JSON.stringify(inherited)) - await expect( - fetchCodexRateLimits({ - codexHomePath: process.env.ORCA_EXPECTED_CODEX_HOME, - networkProxySettings - }) - ).resolves.toMatchObject({ status: 'ok', session: { usedPercent: 17 } }) - } - ) -}) diff --git a/src/main/rate-limits/providers/codex/codex-fetcher-rpc-exit-diagnostics.test.ts b/src/main/rate-limits/providers/codex/codex-fetcher-rpc-exit-diagnostics.test.ts index 1cadfd71314..9cc25820685 100644 --- a/src/main/rate-limits/providers/codex/codex-fetcher-rpc-exit-diagnostics.test.ts +++ b/src/main/rate-limits/providers/codex/codex-fetcher-rpc-exit-diagnostics.test.ts @@ -86,29 +86,6 @@ describe('Codex RPC exit diagnostics', () => { vi.clearAllMocks() }) - it('names the exit code and what the child reported', async () => { - const result = await runStub( - "error: invalid value 'untrusted' for '--ask-for-approval '\n" + - " [possible values: on-request, never]\n\nFor more information, try '--help'.\n", - 2 - ) - - expect(result.error).toContain('Codex RPC process exited (exit code 2)') - expect(result.error).toContain("invalid value 'untrusted'") - expect(result.error).toContain("try '--help'") - }) - - it('classifies a dead refresh token so the re-auth warning fires', async () => { - const result = await runStub( - '2026-08-20T18:04:11.221Z INFO codex_core::auth: refreshing ChatGPT tokens\n' + - 'ERROR: The ChatGPT access token could not be refreshed; please sign in again.\n', - 1 - ) - - expect(result.error).toBe('Your ChatGPT session could not be refreshed. Please sign in again.') - expect(isCodexAuthError(result.error)).toBe(true) - }) - it('keeps the re-auth phrase that path redaction would swallow', async () => { const result = await runStub( `ERROR: /Users/haris/.codex/auth.json is stale — please sign in again.\n`, diff --git a/src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.test.ts b/src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.test.ts index 2f920e73d94..38fb3fc6ba4 100644 --- a/src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.test.ts +++ b/src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.test.ts @@ -2,7 +2,6 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as WslTranscriptFsAccess from '../../../native-chat/wsl-transcript-fs-access' import Database from '../../../sqlite/sync-database' import { detectOpenCodeCredentialBackend } from '../../../opencode/opencode-credential-backend' import { resolveOpenCodeGoApiKey } from './opencode-go-api-key-source' @@ -21,17 +20,6 @@ const ENVIRONMENT_KEYS = [ 'OPENCODE_AUTH_CONTENT' ] as const -// Inject listing failures that host filesystems cannot produce portably. -const readdirFailure = vi.hoisted((): { error: unknown } => ({ error: null })) -vi.mock('../../../native-chat/wsl-transcript-fs-access', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - wslGatedReaddir: (...args: Parameters) => - readdirFailure.error ? Promise.reject(readdirFailure.error) : actual.wslGatedReaddir(...args) - } -}) - describe('resolveOpenCodeGoApiKey', () => { let dataHome: string let originalEnvironment: Partial> @@ -74,7 +62,6 @@ describe('resolveOpenCodeGoApiKey', () => { }) afterEach(() => { - readdirFailure.error = null for (const key of ENVIRONMENT_KEYS) { const value = originalEnvironment[key] if (value === undefined) { @@ -126,84 +113,4 @@ describe('resolveOpenCodeGoApiKey', () => { tier: 'opencode-auth-file' }) }) - - it('does not fall back to the auth file when valid v1 inline auth omits Go', async () => { - writeAuthFile({ 'opencode-go': { type: 'api', key: AUTH_FILE_KEY } }) - process.env.OPENCODE_AUTH_CONTENT = '{}' - process.env.OPENCODE_API_KEY = ENVIRONMENT_KEY - - await expect(resolveOpenCodeGoApiKey({ backend: 'v1' })).resolves.toEqual({ - status: 'found', - key: ENVIRONMENT_KEY, - tier: 'environment' - }) - }) - - it.each([undefined, '', ' \t\n '])( - 'does not borrow the host key when an unknown selected backend has environment key %j', - async (key) => { - vi.mocked(detectOpenCodeCredentialBackend).mockResolvedValue(null) - process.env.OPENCODE_API_KEY = ENVIRONMENT_KEY - const environment: NodeJS.ProcessEnv = { OPENCODE_API_KEY: key } - - await expect(resolveOpenCodeGoApiKey({ environment })).resolves.toEqual({ status: 'missing' }) - expect(detectOpenCodeCredentialBackend).toHaveBeenCalledWith(environment, undefined) - } - ) - - it('propagates unreadable selected context instead of reading host credentials', async () => { - writeAuthFile({ 'opencode-go': { type: 'api', key: AUTH_FILE_KEY } }) - const input = {} - Object.defineProperty(input, 'environment', { - get: () => { - throw new Error('Selected profile metadata is unreadable') - } - }) - - await expect(resolveOpenCodeGoApiKey(input)).rejects.toThrow( - 'Selected profile metadata is unreadable' - ) - }) - - it.each(['v1', 'v2'] as const)( - 'keeps System and selected data roots isolated for %s', - async (backend) => { - writeAuthFile({ 'opencode-go': { type: 'api', key: AUTH_FILE_KEY } }) - const system = { XDG_DATA_HOME: dataHome, OPENCODE_DB: ':memory:' } - const selectedDataHome = join(dataHome, 'selected') - mkdirSync(join(selectedDataHome, 'opencode'), { recursive: true }) - writeFileSync( - join(selectedDataHome, 'opencode', 'auth.json'), - JSON.stringify({ - 'opencode-go': { type: 'api', key: 'selected-auth-placeholder' } - }) - ) - const { path } = writeCredentialDatabase([ - { - value: JSON.stringify({ type: 'key', key: 'selected-table-placeholder' }), - active: 1, - created: 1 - } - ]) - const selected = { XDG_DATA_HOME: selectedDataHome, OPENCODE_DB: path } - const inherited = { ...process.env } - - const first = await resolveOpenCodeGoApiKey({ environment: system, backend }) - const managed = await resolveOpenCodeGoApiKey({ environment: selected, backend }) - const restored = await resolveOpenCodeGoApiKey({ environment: system, backend }) - - expect(first).toEqual({ status: 'found', key: AUTH_FILE_KEY, tier: 'opencode-auth-file' }) - expect(managed).toEqual( - backend === 'v1' - ? { status: 'found', key: 'selected-auth-placeholder', tier: 'opencode-auth-file' } - : { - status: 'found', - key: 'selected-table-placeholder', - tier: 'opencode-credential-database' - } - ) - expect(restored).toEqual(first) - expect(process.env).toEqual(inherited) - } - ) }) diff --git a/src/main/rate-limits/providers/opencode-go/opencode-go-status-parsing.test.ts b/src/main/rate-limits/providers/opencode-go/opencode-go-status-parsing.test.ts index f6adb4173fe..dbfb15f8037 100644 --- a/src/main/rate-limits/providers/opencode-go/opencode-go-status-parsing.test.ts +++ b/src/main/rate-limits/providers/opencode-go/opencode-go-status-parsing.test.ts @@ -1,81 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - isOpenCodeGoExplicitNoAccessPayload, - parseOpenCodeGoBillingStatusPayload, - parseOpenCodeGoStatusPayload, - parseOpenCodeGoUsageApiPayload -} from './opencode-go-status-parsing' - -const ISSUE_PAYLOAD = { - access: { - meters: { - fiveHour: { - resetsAt: '2026-09-18T12:42:04.962Z', - limitMicroCents: '1200000000', - usedMicroCents: '121745383' - }, - week: { - resetsAt: '2026-09-21T00:00:00.000Z', - limitMicroCents: '3000000000', - usedMicroCents: '121745383' - }, - month: { - limitMicroCents: '6000000000', - usedMicroCents: '121745383' - } - } - } -} - -describe('parseOpenCodeGoStatusPayload', () => { - it('maps fiveHour/week/month meters into session/weekly/monthly windows', () => { - const parsed = parseOpenCodeGoStatusPayload(JSON.stringify(ISSUE_PAYLOAD)) - - expect(parsed).not.toBeNull() - expect(parsed?.session).toEqual({ - usedPercent: (121745383 / 1_200_000_000) * 100, - windowMinutes: 300, - resetsAt: Date.parse('2026-09-18T12:42:04.962Z'), - resetDescription: null - }) - expect(parsed?.weekly).toEqual({ - usedPercent: (121745383 / 3_000_000_000) * 100, - windowMinutes: 10_080, - resetsAt: Date.parse('2026-09-21T00:00:00.000Z'), - resetDescription: null - }) - expect(parsed?.monthly).toEqual({ - usedPercent: (121745383 / 6_000_000_000) * 100, - windowMinutes: 43_200, - resetsAt: null, - resetDescription: null - }) - }) - - it('caps usedPercent at 100 and floors at 0', () => { - const parsed = parseOpenCodeGoStatusPayload( - JSON.stringify({ - access: { - meters: { - fiveHour: { - resetsAt: '2026-09-18T12:42:04.962Z', - limitMicroCents: '100', - usedMicroCents: '150' - }, - week: { - resetsAt: '2026-09-21T00:00:00.000Z', - limitMicroCents: '100', - usedMicroCents: '-5' - } - } - } - }) - ) - - expect(parsed?.session?.usedPercent).toBe(100) - expect(parsed?.weekly?.usedPercent).toBe(0) - }) -}) +import { parseOpenCodeGoBillingStatusPayload } from './opencode-go-status-parsing' describe('parseOpenCodeGoBillingStatusPayload', () => { it('maps the verified PAYG micro-cent string into USD major units', () => { @@ -89,76 +13,4 @@ describe('parseOpenCodeGoBillingStatusPayload', () => { ) ).toBe(27.86781005) }) - - it('preserves zero and negative balances', () => { - expect( - parseOpenCodeGoBillingStatusPayload( - JSON.stringify({ - billingMode: 'prepaid', - mode: 'pay-as-you-go', - balanceMicroCents: '0' - }) - ) - ).toBe(0) - expect( - parseOpenCodeGoBillingStatusPayload( - JSON.stringify({ - billingMode: 'prepaid', - mode: 'pay-as-you-go', - balanceMicroCents: '-125000000' - }) - ) - ).toBe(-1.25) - }) - - it.each([ - { billingMode: 'credit', mode: 'pay-as-you-go', balanceMicroCents: '100000000' }, - { billingMode: 'seat', mode: 'pay-as-you-go', balanceMicroCents: '100000000' }, - { billingMode: 'prepaid', mode: 'invoiceable', balanceMicroCents: '100000000' }, - { billingMode: 'prepaid', mode: 'pay-as-you-go', balanceMicroCents: 100000000 }, - { billingMode: 'prepaid', mode: 'pay-as-you-go', balanceMicroCents: '1.5' }, - { - billingMode: 'prepaid', - mode: 'pay-as-you-go', - balanceMicroCents: '9007199254740992' - } - ])('rejects unsupported or unsafe billing payloads: $billingMode/$mode', (payload) => { - expect(parseOpenCodeGoBillingStatusPayload(JSON.stringify(payload))).toBeNull() - }) -}) - -describe('isOpenCodeGoExplicitNoAccessPayload', () => { - it('accepts only explicit JSON null or access:null without an error verdict', () => { - expect(isOpenCodeGoExplicitNoAccessPayload('null')).toBe(true) - expect(isOpenCodeGoExplicitNoAccessPayload('{"access":null}')).toBe(true) - expect( - isOpenCodeGoExplicitNoAccessPayload('{"access":null,"error":{"type":"AuthError"}}') - ).toBe(false) - expect(isOpenCodeGoExplicitNoAccessPayload('{"access":{}}')).toBe(false) - expect(isOpenCodeGoExplicitNoAccessPayload('{}')).toBe(false) - expect(isOpenCodeGoExplicitNoAccessPayload('')).toBe(false) - expect(isOpenCodeGoExplicitNoAccessPayload('{not json')).toBe(false) - }) -}) - -describe('parseOpenCodeGoUsageApiPayload', () => { - it('clamps an out-of-range percent and tolerates a missing resetsAt', () => { - const parsed = parseOpenCodeGoUsageApiPayload( - JSON.stringify({ - usage: { - rolling: { status: 'rate-limited', percent: 140 }, - weekly: { status: 'ok', percent: -5, resetsAt: 'not a date' } - } - }) - ) - - expect(parsed?.session).toEqual({ - usedPercent: 100, - windowMinutes: 300, - resetsAt: null, - resetDescription: null - }) - expect(parsed?.weekly.usedPercent).toBe(0) - expect(parsed?.monthly).toBeNull() - }) }) diff --git a/src/main/rate-limits/service/service-account-target-selection.test.ts b/src/main/rate-limits/service/service-account-target-selection.test.ts index 5a85a8a5941..3e7afe8b6de 100644 --- a/src/main/rate-limits/service/service-account-target-selection.test.ts +++ b/src/main/rate-limits/service/service-account-target-selection.test.ts @@ -77,66 +77,6 @@ describe('RateLimitService', () => { resetRateLimitProviderMocks() }) - it('settles without applying a result when the managed home becomes unavailable mid-fetch', async () => { - const service = new RateLimitService() - const resolver = vi - .fn() - .mockReturnValueOnce({ kind: 'ready', codexHomePath: '/tmp/codex-home' }) - .mockReturnValue({ kind: 'skip' }) - service.setCodexHomePathResolver(resolver) - vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 20, Date.now())) - - await service.refreshForCodexAccountChange(null, { runtime: 'host' }) - - expect(resolver).toHaveBeenCalledTimes(2) - expect(fetchCodexRateLimits).toHaveBeenCalledOnce() - expect(service.getState().codex).toBeNull() - }) - - it('returns a refreshed scoped state without overwriting a target selected during reset', async () => { - const service = new RateLimitService() - const idempotencyKey = '22222222-2222-4222-8222-222222222222' - const consume = vi.mocked(consumeCodexRateLimitResetCredit) - let resolveConsume: ((outcome: 'reset') => void) | undefined - consume.mockImplementationOnce( - () => - new Promise((resolve) => { - resolveConsume = resolve - }) - ) - vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 0, Date.now())) - - service.setCodexHomePathResolver(() => ({ kind: 'ready', codexHomePath: '/tmp/new-selection' })) - const pending = service.consumeCodexRateLimitResetCredit({ - idempotencyKey, - target: { runtime: 'host', wslDistro: null }, - codexHomePath: '/tmp/approved-selection' - }) - await vi.waitFor(() => expect(consume).toHaveBeenCalledOnce()) - service.setCodexFetchTarget({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - resolveConsume?.('reset') - - await expect(pending).resolves.toMatchObject({ - outcome: 'reset', - state: { - codexTarget: { runtime: 'host', wslDistro: null }, - codex: { session: { usedPercent: 0 } } - } - }) - expect(consume).toHaveBeenCalledWith({ - codexHomePath: '/tmp/approved-selection', - idempotencyKey - }) - expect(fetchCodexRateLimits).toHaveBeenCalledWith( - expect.objectContaining({ - codexHomePath: '/tmp/approved-selection', - signal: expect.any(AbortSignal) - }) - ) - expect(service.getState().codexTarget).toEqual({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - expect(service.getState().codex).toBeNull() - }) - it('keeps the reset result scoped when the active target changes during its refresh', async () => { const service = new RateLimitService() const idempotencyKey = '33333333-3333-4333-8333-333333333333' @@ -201,120 +141,4 @@ describe('RateLimitService', () => { expect(service.getState().codex?.session?.usedPercent).toBe(0) }) - - it('does not fetch host Codex usage when WSL home resolution fails', async () => { - const service = new RateLimitService() - const resolver = vi.fn(() => ({ kind: 'ready' as const, codexHomePath: null })) - service.setCodexHomePathResolver(resolver) - service.setCodexFetchTarget({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - - vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce( - okProvider('claude', 10, Date.now()) - ) - - await service.refresh() - - expect(resolver).toHaveBeenCalledWith({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - expect(fetchCodexRateLimits).not.toHaveBeenCalled() - expect(service.getState().codex).toMatchObject({ - provider: 'codex', - status: 'error', - error: 'WSL Codex home unavailable for Ubuntu' - }) - }) - - it('does not cache host Codex usage under an outgoing WSL account', async () => { - const service = new RateLimitService() - const wslCodexHome = - '\\\\wsl.localhost\\Ubuntu\\home\\jin\\.local\\share\\orca\\codex-accounts\\a\\home' - const hostCodexHome = 'C:\\Users\\jin\\.orca\\codex-accounts\\host\\home' - service.setCodexHomePathResolver((target) => ({ - kind: 'ready', - codexHomePath: target?.runtime === 'wsl' ? wslCodexHome : hostCodexHome - })) - - vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce( - okProvider('claude', 10, Date.now()) - ) - vi.mocked(fetchCodexRateLimits) - .mockResolvedValueOnce(okProvider('codex', 20, Date.now())) - .mockResolvedValueOnce(okProvider('codex', 40, Date.now())) - - await service.refresh() - await service.refreshForCodexAccountChange('wsl-account-1', { - runtime: 'wsl', - wslDistro: 'Ubuntu' - }) - - expect(service.getState().inactiveCodexAccounts).not.toEqual( - expect.arrayContaining([expect.objectContaining({ accountId: 'wsl-account-1' })]) - ) - }) - - it('does not cache host Claude usage under an outgoing WSL account', async () => { - const service = new RateLimitService() - service.setInactiveClaudeAccountsResolver(() => [{ id: 'wsl-account-1' }]) - service.setClaudeAuthPreparationResolver(async (target) => ({ - configDir: - target?.runtime === 'wsl' - ? '\\\\wsl.localhost\\Ubuntu\\home\\jin\\.claude' - : 'C:\\Users\\jin\\.claude', - runtime: target?.runtime ?? 'host', - wslDistro: target?.wslDistro ?? null, - wslLinuxConfigDir: target?.runtime === 'wsl' ? '/home/jin/.claude' : null, - envPatch: {}, - provenance: target?.runtime === 'wsl' ? 'managed:wsl-account-1:wsl:Ubuntu' : 'system' - })) - - vi.mocked(fetchActiveClaudeRateLimits) - .mockResolvedValueOnce(okProvider('claude', 20, Date.now())) - .mockResolvedValueOnce(okProvider('claude', 40, Date.now())) - vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 20, Date.now())) - - await service.refresh() - await service.refreshForClaudeAccountChange('wsl-account-1', { - runtime: 'wsl', - wslDistro: 'Ubuntu' - }) - - expect(fetchActiveClaudeRateLimits).toHaveBeenLastCalledWith( - expect.objectContaining({ allowPtyFallback: true, allowUsagePanelSupplement: true }) - ) - - expect(service.getState().inactiveClaudeAccounts).not.toEqual( - expect.arrayContaining([expect.objectContaining({ accountId: 'wsl-account-1' })]) - ) - }) - - // Regression: the Codex home resolver is async, and a reset never waits on isFetching. - it('does not apply a stale full-refresh cycle codex result over a newer reset', async () => { - const service = new RateLimitService() - const staleHome = deferred<{ kind: 'ready'; codexHomePath: string | null }>() - const resolver = vi - .fn() - .mockReturnValueOnce(staleHome.promise) - .mockResolvedValue({ kind: 'ready', codexHomePath: '/tmp/approved-selection' }) - service.setCodexHomePathResolver(resolver) - vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue(okProvider('claude', 10, Date.now())) - vi.mocked(fetchCodexRateLimits) - .mockResolvedValueOnce(okProvider('codex', 0, Date.now())) - .mockResolvedValueOnce(okProvider('codex', 100, Date.now())) - vi.mocked(consumeCodexRateLimitResetCredit).mockResolvedValueOnce('reset') - - const staleRefresh = service.refresh() - await vi.waitFor(() => expect(resolver).toHaveBeenCalledTimes(1)) - - await expect( - service.consumeCodexRateLimitResetCredit({ - idempotencyKey: '55555555-5555-4555-8555-555555555555', - target: { runtime: 'host', wslDistro: null }, - codexHomePath: '/tmp/approved-selection' - }) - ).resolves.toMatchObject({ outcome: 'reset' }) - - staleHome.resolve({ kind: 'ready', codexHomePath: '/tmp/approved-selection' }) - await staleRefresh - - expect(service.getState().codex?.session?.usedPercent).not.toBe(100) - }) }) diff --git a/src/main/rate-limits/service/service-inactive-account-previews.test.ts b/src/main/rate-limits/service/service-inactive-account-previews.test.ts index 2a216e7af68..312507c095d 100644 --- a/src/main/rate-limits/service/service-inactive-account-previews.test.ts +++ b/src/main/rate-limits/service/service-inactive-account-previews.test.ts @@ -10,13 +10,6 @@ import { resetRateLimitProviderMocks } from './rate-limit-service-test-harness' -function inactiveCodexAccount(id: string, managedHomePath: string) { - return { - id, - resolveHome: () => ({ kind: 'ready' as const, managedHomePath }) - } -} - vi.mock('../providers/claude/claude-active-usage-fetch', () => ({ fetchActiveClaudeRateLimits: vi.fn() })) @@ -90,101 +83,6 @@ describe('RateLimitService', () => { vi.useRealTimers() }) - it('keeps sibling inactive Codex preview fetches alive when one account is evicted', async () => { - const service = new RateLimitService() - const accountFetch = deferred() - let inactiveAccounts = [ - inactiveCodexAccount('account-a', '/tmp/account-a/home'), - inactiveCodexAccount('account-b', '/tmp/account-b/home') - ] - service.setInactiveCodexAccountsResolver(() => inactiveAccounts) - vi.mocked(fetchCodexRateLimits).mockReturnValueOnce(accountFetch.promise) - - const fetchOnOpen = service.fetchInactiveCodexAccountsOnOpen() - await Promise.resolve() - expect(service.getState().inactiveCodexAccounts).toEqual([ - { accountId: 'account-a', rateLimits: null, updatedAt: 0, isFetching: true } - ]) - - inactiveAccounts = [inactiveCodexAccount('account-a', '/tmp/account-a/home')] - service.evictInactiveCodexCache('account-b') - accountFetch.resolve(okProvider('codex', 64, Date.now())) - await fetchOnOpen - - expect(fetchCodexRateLimits).toHaveBeenCalledTimes(1) - expect(service.getState().inactiveCodexAccounts).toEqual([ - { - accountId: 'account-a', - rateLimits: expect.objectContaining({ - provider: 'codex', - session: expect.objectContaining({ usedPercent: 64 }) - }), - updatedAt: expect.any(Number), - isFetching: false - } - ]) - }) - - it('does not recache an inactive Codex account that becomes active during fetch-on-open', async () => { - const service = new RateLimitService() - const accountFetch = deferred() - let inactiveAccounts = [inactiveCodexAccount('account-b', '/tmp/account-b/home')] - service.setInactiveCodexAccountsResolver(() => inactiveAccounts) - service.setCodexHomePathResolver(() => ({ - kind: 'ready', - codexHomePath: '/tmp/account-b/home' - })) - vi.mocked(fetchCodexRateLimits) - .mockReturnValueOnce(accountFetch.promise) - .mockResolvedValueOnce(okProvider('codex', 7, Date.now())) - - const fetchOnOpen = service.fetchInactiveCodexAccountsOnOpen() - await Promise.resolve() - expect(service.getState().inactiveCodexAccounts).toEqual([ - { accountId: 'account-b', rateLimits: null, updatedAt: 0, isFetching: true } - ]) - - inactiveAccounts = [] - await service.refreshForCodexAccountChange('account-a') - accountFetch.resolve(okProvider('codex', 42, Date.now())) - await fetchOnOpen - - expect(service.getState().inactiveCodexAccounts).toEqual([]) - }) - - it('does not recache an inactive Claude account removed during fetch-on-open', async () => { - const service = new RateLimitService() - const accountFetch = deferred() - let inactiveAccounts = [{ id: 'account-1' }] - service.setInactiveClaudeAccountsResolver(() => inactiveAccounts) - service.setClaudeAuthPreparationResolver(async () => ({ - configDir: '/tmp/.claude', - envPatch: {}, - provenance: 'system' - })) - vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue(okProvider('claude', 7)) - await service.refresh() - vi.mocked(fetchInactiveClaudeAccountUsage).mockReturnValueOnce(accountFetch.promise) - - const fetchOnOpen = service.fetchInactiveClaudeAccountsOnOpen() - await Promise.resolve() - expect(service.getState().inactiveClaudeAccounts).toEqual([ - { accountId: 'account-1', rateLimits: null, updatedAt: 0, isFetching: true } - ]) - - service.evictInactiveClaudeCache('account-1') - inactiveAccounts = [{ id: 'account-1' }] - await service.refreshForClaudeAccountChange('account-1') - expect(service.getState().inactiveClaudeAccounts[0]?.accountId).toBe('account-1') - - inactiveAccounts = [] - service.evictInactiveClaudeCache('account-1') - accountFetch.resolve(okProvider('claude', 42)) - await fetchOnOpen - - expect(service.getState().inactiveClaudeAccounts).toEqual([]) - }) - it('does not overwrite inactive Claude cache from a stale same-id fetch', async () => { const service = new RateLimitService() const accountFetch = deferred() diff --git a/src/main/rate-limits/service/service-live-claude-usage.test.ts b/src/main/rate-limits/service/service-live-claude-usage.test.ts deleted file mode 100644 index c776b33666d..00000000000 --- a/src/main/rate-limits/service/service-live-claude-usage.test.ts +++ /dev/null @@ -1,279 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ProviderRateLimits } from '../../../shared/rate-limit-types' -import { RateLimitService } from './rate-limit-service' -import { fetchActiveClaudeRateLimits } from '../providers/claude/claude-active-usage-fetch' -import { - deferred, - errorProvider, - flushMicrotasks, - mockFreshBackgroundProviderFetches, - okProvider, - resetRateLimitProviderMocks -} from './rate-limit-service-test-harness' - -class ObservedRateLimitService extends RateLimitService { - get claudeCheckCompletedAt(): number | null { - return this.lastClaudeCheckCompletedAt - } - - get activeRefreshPlan() { - return this.getActiveWindowRefreshPlan(Date.now()) - } -} - -const profileRouter = vi.hoisted((): { userConfigDir?: string } => ({})) -vi.mock('../../claude-accounts/claude-profile-installed-router', () => ({ - getClaudeProfileRouter: () => - profileRouter.userConfigDir ? { userConfigDir: () => profileRouter.userConfigDir } : undefined -})) - -vi.mock('../providers/claude/claude-active-usage-fetch', () => ({ - fetchActiveClaudeRateLimits: vi.fn() -})) -vi.mock('../providers/claude/claude-managed-account-usage', () => ({ - fetchInactiveClaudeAccountUsage: vi.fn() -})) - -vi.mock('../providers/codex/codex-fetcher', () => ({ - consumeCodexRateLimitResetCredit: vi.fn(), - fetchCodexRateLimits: vi.fn() -})) - -vi.mock('../providers/gemini/gemini-usage-fetcher', () => ({ - fetchGeminiRateLimits: vi.fn() -})) - -vi.mock('../providers/kimi/kimi-fetcher', () => ({ - fetchKimiRateLimits: vi.fn() -})) - -vi.mock('../providers/opencode-go/opencode-go-usage-source-selection', () => ({ - fetchOpenCodeGoUsage: vi.fn() -})) - -vi.mock('../providers/zcode/zcode-usage-fetcher', () => ({ - fetchZcodeRateLimits: vi.fn() -})) - -vi.mock('../providers/muse/muse-usage-fetcher', () => ({ - fetchMuseRateLimits: vi.fn() -})) - -vi.mock('../providers/antigravity/antigravity-usage-fetcher', () => ({ - fetchAntigravityRateLimits: vi.fn() -})) - -vi.mock('../providers/minimax/minimax-fetcher', () => ({ - fetchMiniMaxRateLimits: vi.fn() -})) - -vi.mock('../providers/grok/grok-fetcher', () => ({ - fetchGrokRateLimits: vi.fn() -})) - -vi.mock('../providers/cursor/cursor-fetcher', () => ({ - fetchCursorRateLimits: vi.fn() -})) - -vi.mock('../providers/cursor/cursor-auth', () => ({ - readCursorAuthSession: vi.fn() -})) - -vi.mock('../providers/grok/grok-auth', () => ({ - readGrokAuthSession: vi.fn(() => ({ status: 'missing' })) -})) - -vi.mock('../../minimax/minimax-cookie-store', () => ({ - hasMiniMaxSessionCookie: vi.fn(() => false) -})) - -describe('RateLimitService', () => { - beforeEach(() => { - resetRateLimitProviderMocks() - }) - - it('drops statusline posts before attribution is known or from a mismatched config dir', async () => { - vi.useFakeTimers() - try { - vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue(okProvider('claude', 18)) - mockFreshBackgroundProviderFetches() - - const service = new RateLimitService() - - // No cycle has established selected-account attribution yet. - service.ingestLiveClaudeRateLimits({ - configDir: null, - fiveHour: { used_percentage: 50 }, - sevenDay: null - }) - expect(service.getState().claude).toBeNull() - - await service.refresh() - expect(service.getState().claude?.session?.usedPercent).toBe(18) - - service.ingestLiveClaudeRateLimits({ - configDir: '/some/managed/dir', - fiveHour: { used_percentage: 99 }, - sevenDay: null - }) - expect(service.getState().claude?.session?.usedPercent).toBe(18) - - service.ingestLiveClaudeRateLimits({ - configDir: null, - fiveHour: { used_percentage: 33 }, - sevenDay: null - }) - expect(service.getState().claude?.session?.usedPercent).toBe(33) - } finally { - vi.useRealTimers() - } - }) - - it.each(['full', 'claude-only'])('isolates %s checks on switch', async (cycle) => { - vi.useFakeTimers() - try { - const staleClaudeFetch = deferred() - const incomingFetch = deferred() - vi.mocked(fetchActiveClaudeRateLimits) - .mockImplementationOnce(async () => okProvider('claude', 9)) - .mockImplementationOnce(() => staleClaudeFetch.promise) - .mockImplementationOnce(() => incomingFetch.promise) - mockFreshBackgroundProviderFetches() - - const authGate = deferred() - let resolverCalls = 0 - const service = new ObservedRateLimitService() - await service.refresh() - expect(service.claudeCheckCompletedAt).toBe(Date.now()) - service.setClaudeAuthPreparationResolver(async () => { - resolverCalls += 1 - const outgoing = resolverCalls === 1 - if (outgoing) { - await authGate.promise - } - return { - configDir: outgoing ? '/outgoing/.claude' : '/incoming/.claude', - runtime: 'host', - wslDistro: null, - wslLinuxConfigDir: null, - envPatch: { - CLAUDE_CONFIG_DIR: outgoing ? '/outgoing/.claude' : '/incoming/.claude' - }, - provenance: outgoing ? 'managed:outgoing' : 'managed:incoming' - } - }) - - // Switch while the outgoing account resolver is suspended. - const firstRefresh = cycle === 'full' ? service.refresh() : service.refreshClaudeForTarget() - await flushMicrotasks() - const switchPromise = - cycle === 'full' - ? service.refreshForClaudeAccountChange('outgoing-account') - : service.refreshClaudeForTarget({ runtime: 'wsl', wslDistro: 'Ubuntu' }) - await flushMicrotasks() - authGate.resolve() - await flushMicrotasks(8) - - // The stale resumed cycle must not authorize outgoing live posts on the new account. - const beforeOutgoingPost = service.getState().claude?.session?.usedPercent - service.ingestLiveClaudeRateLimits({ - configDir: '/outgoing/.claude', - fiveHour: { used_percentage: 99 }, - sevenDay: null - }) - expect(service.getState().claude?.session?.usedPercent).toBe(beforeOutgoingPost) - - staleClaudeFetch.resolve(okProvider('claude', 18)) - await vi.advanceTimersByTimeAsync(0) - expect(service.claudeCheckCompletedAt).toBeNull() - - service.ingestLiveClaudeRateLimits({ - configDir: '/incoming/.claude', - fiveHour: { used_percentage: 55 }, - sevenDay: null - }) - expect(service.getState().claude?.session?.usedPercent).toBe(55) - expect(service.activeRefreshPlan).toEqual({ kind: 'full' }) - incomingFetch.resolve(okProvider('claude', 18)) - await Promise.all([firstRefresh, switchPromise]) - expect(fetchActiveClaudeRateLimits).toHaveBeenCalledTimes(3) - expect(service.claudeCheckCompletedAt).toBe(Date.now()) - } finally { - vi.useRealTimers() - } - }) - - it('keeps the newer weekly value when an idle session re-posts an older one for the same window', async () => { - vi.useFakeTimers() - try { - // OAuth and statusline reset timestamps differ in precision. - const sessionReset = Date.now() + 128 * 60 * 1000 + 123 - const weeklyReset = Date.now() + 125 * 60 * 60 * 1000 + 456 - const win = (usedPercent: number, resetsAt: number, windowMinutes: number) => ({ - usedPercent, - windowMinutes, - resetsAt, - resetDescription: null - }) - vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue({ - ...okProvider('claude', 10), - session: win(10, sessionReset, 300), - weekly: win(25, weeklyReset, 10080) - }) - mockFreshBackgroundProviderFetches() - const service = new RateLimitService() - await service.refresh() - const fetched = service.getState().claude - const post = (session: number | null, weekly: number, weeklyResetAt = weeklyReset) => - service.ingestLiveClaudeRateLimits({ - configDir: null, - fiveHour: - session === null - ? null - : { used_percentage: session, resets_at: Math.floor(sessionReset / 1000) }, - sevenDay: { used_percentage: weekly, resets_at: Math.floor(weeklyResetAt / 1000) } - }) - - // Idle sessions can drop the expired 5h window while repeating stale weekly data; discard the whole stale post. - await vi.advanceTimersByTimeAsync(60 * 1000) - post(null, 8) - expect(service.getState().claude).toEqual(fetched) - - post(10, 8) - expect(service.getState().claude).toEqual(fetched) - post(null, 90, weeklyReset - 7 * 24 * 60 * 60 * 1000) - expect(service.getState().claude).toEqual(fetched) - vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce({ - ...errorProvider('claude', 'rate limited'), - usageMetadata: { retryAtMs: Date.now() + 60 * 60 * 1000, failureKind: 'rate-limited' } - }) - await service.refresh() - const failed = service.getState().claude - post(10, 8) - expect(service.getState().claude).toEqual(failed) - post(10, 25) - expect(service.getState().claude?.session?.resetsAt).toBe(sessionReset) - expect(service.getState().claude?.status).toBe('ok') - expect(service.getState().claude?.usageMetadata?.retryAtMs).toBe( - failed?.usageMetadata?.retryAtMs - ) - post(11, 25) - expect(service.getState().claude?.weekly?.resetsAt).toBe(weeklyReset) - const grownSessionReset = service.getState().claude?.session?.resetsAt - post(11, 26) - expect(service.getState().claude?.session?.resetsAt).toBe(grownSessionReset) - expect(service.getState().claude?.weekly?.usedPercent).toBe(26) - - post(null, 1, weeklyReset + 7 * 24 * 60 * 60 * 1000) - expect(service.getState().claude?.weekly?.usedPercent).toBe(1) - service.ingestLiveClaudeRateLimits({ - configDir: null, - fiveHour: null, - sevenDay: { utilization: 0 } - }) - expect(service.getState().claude?.weekly?.usedPercent).toBe(0) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.test.ts new file mode 100644 index 00000000000..669972dc427 --- /dev/null +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import '../../../orca-runtime-tests/runtime-test-module-registration.spec' +import { createRuntime } from '../../../orca-runtime-tests/orca-runtime-test-fixtures.spec' + +const CHAT = 'orca_session_id:0f9c2f6e-6c1b-4f5e-9d8a-2b7f3c4d5e6f' + +describe('terminal commands addressed to a chat', () => { + it('refuses read and send as a chat session instead of a stale terminal handle', async () => { + const runtime = createRuntime() + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { tabs: [], leaves: [] }) + const refusal = { + code: 'terminal_unsupported_for_agent_session', + message: expect.stringContaining(`orca orchestration send --to ${CHAT}`) + } + + await expect(runtime.readTerminal(CHAT)).rejects.toMatchObject(refusal) + await expect( + runtime.sendTerminal(CHAT, { text: 'hi', enter: true }, { inputKind: 'driving' }) + ).rejects.toMatchObject(refusal) + }) +}) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.ts index 82fc4b48cdb..2372b9cf4c5 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-terminal-refusal.ts @@ -3,6 +3,7 @@ import type { OrchestrationDb } from '../../db/orchestration-db' import { resolveStructuredWorkerAuthority } from './structured-worker-authority' +import { parseOrcaSessionAddress } from '../../../../../shared/orca-session-address' const TERMINAL_HANDLE_STALE = 'terminal_handle_stale' const AGENT_SESSION_HAS_NO_TERMINAL = 'terminal_unsupported_for_agent_session' @@ -11,14 +12,23 @@ export function structuredWorkerTerminalRefusal( handle: string, db: OrchestrationDb | null | undefined ): Error { - if (!resolveStructuredWorkerAuthority(handle, db)) { - return new Error(TERMINAL_HANDLE_STALE) + if (resolveStructuredWorkerAuthority(handle, db)) { + return agentSessionRefusal( + `${handle} is an agent session, not a terminal, so terminal commands cannot address it. ` + + 'Read its output with `orca terminal read` or `orca orchestration worker-read --source transcript`, ' + + 'send it work with `orca orchestration send`, and open it from its chat tab.' + ) } - const error = new Error( - `${handle} is an agent session, not a terminal, so terminal commands cannot address it. ` + - 'Read its output with `orca terminal read` or `orca orchestration worker-read --source transcript`, ' + - 'send it work with `orca orchestration send`, and open it from its chat tab.' - ) - Object.assign(error, { code: AGENT_SESSION_HAS_NO_TERMINAL }) - return error + // A chat address never names a terminal, live or not. + if (parseOrcaSessionAddress(handle)) { + return agentSessionRefusal( + `${handle} is a chat session, not a terminal, so terminal commands cannot address it. ` + + `Message it with \`orca orchestration send --to ${handle}\`.` + ) + } + return new Error(TERMINAL_HANDLE_STALE) +} + +function agentSessionRefusal(message: string): Error { + return Object.assign(new Error(message), { code: AGENT_SESSION_HAS_NO_TERMINAL }) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-with-agent.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-with-agent.test.ts new file mode 100644 index 00000000000..f640d1041e8 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-terminal-with-agent.test.ts @@ -0,0 +1,24 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' + +describe('worker-start --terminal with --agent', () => { + const h = createOrchestrationWorkerReleaseHarness() + beforeEach(() => h.setup()) + afterEach(() => h.cleanup()) + + it('refuses, saying --terminal continues the running agent, before any Dispatch', async () => { + await expect( + h.call('orchestration.workerStart', { + from: 'term_coord', + terminal: 'term_worker', + agent: 'codex', + spec: 'reuse the worker' + }) + ).rejects.toMatchObject({ + code: 'invalid_argument', + message: + '--terminal continues the agent already running there, in its current conversation. To start fresh, use --worktree or --agent without --terminal.' + }) + expect(h.db.db.prepare('SELECT count(*) AS n FROM dispatch_contexts').get()).toEqual({ n: 0 }) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts index 8151c172445..5e0a0977644 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-validation.ts @@ -12,6 +12,9 @@ import type { WorkerStartInput } from './worker-start-schema' type WorkerStartLaunch = ReturnType +const TERMINAL_WITH_AGENT_REFUSAL = + '--terminal continues the agent already running there, in its current conversation. To start fresh, use --worktree or --agent without --terminal.' + export function validateFederatedWorkerStartPlacement( params: WorkerStartInput, createsWorktree: boolean @@ -35,10 +38,7 @@ export function validateFederatedWorkerStartPlacement( ) } if (params.terminal && params.agent) { - throw new OrchestrationError( - 'invalid_argument', - '--terminal reuses an existing agent and cannot combine with --agent.' - ) + throw new OrchestrationError('invalid_argument', TERMINAL_WITH_AGENT_REFUSAL) } if (!params.terminal && !params.agent) { throw new OrchestrationError( @@ -57,10 +57,7 @@ export function prepareLocalWorkerStart(args: { const { params, createsWorktree, runtime } = args assertWorkerLaunchPreferencesCreateTerminal(params) if (params.terminal && params.agent) { - throw new OrchestrationError( - 'invalid_argument', - '--terminal reuses an existing agent and cannot combine with --agent.' - ) + throw new OrchestrationError('invalid_argument', TERMINAL_WITH_AGENT_REFUSAL) } if (createsWorktree && params.terminal) { throw new OrchestrationError( @@ -116,10 +113,7 @@ export function prepareFederationAttachmentWorkerStart(args: { ) } if (params.terminal && params.agent) { - throw new OrchestrationError( - 'invalid_argument', - '--terminal reuses an existing agent and cannot combine with --agent.' - ) + throw new OrchestrationError('invalid_argument', TERMINAL_WITH_AGENT_REFUSAL) } return resolveWorkerStartAgent({ runtime, diff --git a/src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts b/src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts index cf3538343a1..74a81dc0efa 100644 --- a/src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts +++ b/src/main/skills/discovery/claude-plugin-skill-sources-wsl.test.ts @@ -6,16 +6,6 @@ function record(...fields: string[]): string { } describe('WSL Claude plugin metadata', () => { - it('decodes present files and retains missing files as null', () => { - const settings = JSON.stringify({ enabledPlugins: { 'plugin@market': true } }) - const output = [ - record('F', '0', '1', Buffer.from(settings).toString('base64')), - record('F', '1', '0', '') - ].join('') - - expect(parseWslClaudePluginMetadataOutput(output, 2)).toEqual([settings, null]) - }) - it('rejects malformed metadata responses', () => { expect(() => parseWslClaudePluginMetadataOutput(record('F', '4', '1', ''), 1)).toThrow( 'invalid response' diff --git a/src/main/skills/package-archive/skill-package-creation.test.ts b/src/main/skills/package-archive/skill-package-creation.test.ts index 5e912d3cb17..bac5070ed31 100644 --- a/src/main/skills/package-archive/skill-package-creation.test.ts +++ b/src/main/skills/package-archive/skill-package-creation.test.ts @@ -1,4 +1,4 @@ -import { chmod, lstat, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { gunzipSync, gzipSync } from 'node:zlib' @@ -136,33 +136,6 @@ describe('skill package creation and extraction', () => { ).rejects.toThrow('skill-package-tar-truncated') }) - it('cancels during streamed extraction and removes partial bytes', async () => { - const root = await temporaryDirectory() - const created = await createSkillPackageArchive({ - sourceDirectory: await createSkill(root), - archivePath: join(root, 'package.tar.gz'), - packageId: 'package_1', - versionId: 'version_1' - }) - let checks = 0 - const signal = { - get aborted() { - checks += 1 - return checks >= 3 - } - } as AbortSignal - const destinationDirectory = join(root, 'cancelled-extraction') - - await expect( - extractSkillPackageArchive({ - archivePath: created.archivePath, - destinationDirectory, - signal - }) - ).rejects.toThrow('skill-install-cancelled') - await expect(lstat(destinationDirectory)).rejects.toMatchObject({ code: 'ENOENT' }) - }) - it('rejects content checksum and SKILL identity mismatches', async () => { const root = await temporaryDirectory() const created = await createSkillPackageArchive({ diff --git a/src/main/skills/sharing/skill-share-preparation.test.ts b/src/main/skills/sharing/skill-share-preparation.test.ts index 6bd5f82ae54..552409c769c 100644 --- a/src/main/skills/sharing/skill-share-preparation.test.ts +++ b/src/main/skills/sharing/skill-share-preparation.test.ts @@ -69,23 +69,4 @@ describe('SkillSharePreparationService', () => { expect(prepared.skills?.[0]?.executablePaths).toEqual(['run.sh']) }) - - it('enforces the preparation cap while archives are still being created', async () => { - const { root, source } = await createSource() - const service = new SkillSharePreparationService(join(root, 'preparations'), { - findOwnedPackageId: nameIsFree, - publishVersion: vi.fn(), - createShare: vi.fn() - }) - - const results = await Promise.allSettled( - Array.from({ length: 9 }, () => service.prepare({ sourceDirectory: source })) - ) - - expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(8) - expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1) - expect(results.find((result) => result.status === 'rejected')).toMatchObject({ - reason: new Error('skill-share-preparation-limit') - }) - }) }) diff --git a/src/main/speech/openai-transcription-client.ts b/src/main/speech/openai-transcription-client.ts index b17ba3411cf..452685c9b29 100644 --- a/src/main/speech/openai-transcription-client.ts +++ b/src/main/speech/openai-transcription-client.ts @@ -1,17 +1,18 @@ import { getMainHttpClient } from '../network/http-client' import { resampleToRate } from './stt-audio-resample' import { replaceRetiredSpeechModelId } from './model-catalog' +import { + CLOUD_TRANSCRIPTION_SAMPLE_RATE, + MAX_CLOUD_TRANSCRIPTION_SECONDS, + cloudTranscriptionTimeoutMs +} from '../../shared/dictation-finish-deadlines' export const OPENAI_TRANSCRIPTION_MODEL_BY_ID: Record = { 'openai-gpt-transcribe': 'gpt-transcribe' } export const OPENAI_TRANSCRIPTION_URL = 'https://api.openai.com/v1/audio/transcriptions' -const CLOUD_TRANSCRIPTION_SAMPLE_RATE = 16000 -const MAX_CLOUD_AUDIO_SAMPLES = 10 * 60 * CLOUD_TRANSCRIPTION_SAMPLE_RATE -// Room to answer plus the upload time of the WAV at 1 Mbit/s (125 bytes per ms). -const TRANSCRIPTION_RESPONSE_ALLOWANCE_MS = 30_000 -const UPLOAD_BYTES_PER_MS = 125 +const MAX_CLOUD_AUDIO_SAMPLES = MAX_CLOUD_TRANSCRIPTION_SECONDS * CLOUD_TRANSCRIPTION_SAMPLE_RATE export type OpenAiTranscriptionResponse = { text?: unknown @@ -154,9 +155,7 @@ export class OpenAiTranscriptionSession { // A named WAV blob satisfies multipart uploads without temporary files. form.append('file', new Blob([wav], { type: 'audio/wav' }), 'dictation.wav') - const timeout = AbortSignal.timeout( - TRANSCRIPTION_RESPONSE_ALLOWANCE_MS + Math.ceil(wav.byteLength / UPLOAD_BYTES_PER_MS) - ) + const timeout = AbortSignal.timeout(cloudTranscriptionTimeoutMs(this.audioSamples)) try { return await this.upload(form, AbortSignal.any([this.abortController.signal, timeout])) } catch (error) { diff --git a/src/main/speech/stt-session-stop.ts b/src/main/speech/stt-session-stop.ts index 1480be40b54..29a4e55820c 100644 --- a/src/main/speech/stt-session-stop.ts +++ b/src/main/speech/stt-session-stop.ts @@ -7,8 +7,8 @@ import { } from './stt-session-state' import { waitForSttWorkerStop, type SttWorkerStopOutcome } from './stt-worker-stop' import { STT_WORKER_HUNG_ERROR } from './stt-worker-process' +import { LOCAL_DICTATION_STOP_TIMEOUT_MS } from '../../shared/dictation-finish-deadlines' -const STOP_DICTATION_TIMEOUT_MS = 60_000 // A cancel waits only this long behind a busy decode before giving up on it. const DISCARD_DICTATION_TIMEOUT_MS = 2_000 @@ -74,7 +74,7 @@ function stopLocalSession( worker: engine.worker, streamId: session.streamId, sink: session.sink, - timeoutMs: discard ? DISCARD_DICTATION_TIMEOUT_MS : STOP_DICTATION_TIMEOUT_MS, + timeoutMs: discard ? DISCARD_DICTATION_TIMEOUT_MS : LOCAL_DICTATION_STOP_TIMEOUT_MS, discard, finish: (outcome) => finishLocalStop(state, session, engine, outcome, discard) }) diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index 868ff78c622..920bbe305d8 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -101,7 +101,7 @@ export function createMainWindow( const settings = store?.getSettings() browserManager.setDictationShortcutForwardingPredicate(() => { const voice = store?.getSettings().voice - // Guests forward only keydown, so Hold's release can't reach the renderer; the page keeps the key then. + // Chromium drops a page's key releases after a press cancelled here, so Hold can't see its release; the page keeps the key then. return voice?.enabled === true && voice.dictationMode !== 'hold' }) const windowMaterial = resolveWindowMaterial( diff --git a/src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx b/src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx deleted file mode 100644 index 375c806f1a9..00000000000 --- a/src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx +++ /dev/null @@ -1,198 +0,0 @@ -// @vitest-environment happy-dom - -import { - deferred, - editState, - flushPromises, - jiraIssue, - otherIssue, - runtimeMocks, - saveTitle, - selectIssue, - store, - StoreBackedWorkspace -} from './__mocks__/jira-issue-workspace-edit-fixture' -import { act, fireEvent, render, screen } from '@testing-library/react' -import { describe, expect, it, vi } from 'vitest' -import type { JiraIssue, JiraMutationResult } from '../../../shared/jira/jira-types' -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' -import { getDefaultSettings } from '../../../shared/constants' -import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' -import { TooltipProvider } from '@/components/ui/tooltip' -import JiraIssueWorkspace from './JiraIssueWorkspace' - -describe('JiraIssueWorkspace optimistic edits', () => { - it.each([true, false])( - 'captures the default host when a save settles after navigation (%s)', - async (ok) => { - const oldSave = deferred() - runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(oldSave.promise) - const contextKey = getProviderRuntimeContextKey(editState.settings) - const view = render( - - - - ) - await flushPromises() - saveTitle('Old title', 'Local edit') - await flushPromises() - editState.settings = { ...getDefaultSettings(''), activeRuntimeEnvironmentId: 'remote-1' } - runtimeMocks.jiraGetIssueForTarget.mockImplementation(async (source: RuntimeClientTarget) => - jiraIssue(source.kind === 'environment' ? 'Remote title' : 'Local edit') - ) - view.rerender( - - - - ) - await flushPromises() - await act(async () => - oldSave.resolve(ok ? { ok: true } : { ok: false, error: 'Local edit rejected' }) - ) - await flushPromises() - - expect(runtimeMocks.jiraUpdateIssueForTarget).toHaveBeenCalledWith( - { kind: 'local' }, - 'ENG-1', - { title: 'Local edit' }, - 'site-1' - ) - expect(runtimeMocks.jiraGetIssueForTarget).toHaveBeenLastCalledWith( - ok ? { kind: 'local' } : { kind: 'environment', environmentId: 'remote-1' }, - 'ENG-1', - 'site-1' - ) - expect(store.patchJiraIssue).toHaveBeenLastCalledWith( - 'ENG-1', - expect.objectContaining({ title: ok ? 'Local edit' : 'Old title' }), - expect.objectContaining({ contextKey, siteId: 'site-1' }) - ) - expect(screen.getByDisplayValue('Remote title')).toBeDefined() - } - ) - - it('keeps loaded and submitted comments while a title save patches the shared cache', async () => { - runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(deferred<{ ok: true }>().promise) - runtimeMocks.jiraIssueCommentsForTarget.mockResolvedValue([ - { id: 'server', body: 'Existing comment', createdAt: '2026-09-01' } - ]) - runtimeMocks.jiraAddIssueCommentForTarget.mockResolvedValue({ ok: true, id: 'added' }) - render() - await flushPromises() - fireEvent.change(screen.getByPlaceholderText('Add a Jira comment...'), { - target: { value: 'New comment' } - }) - fireEvent.click(screen.getByRole('button', { name: 'Comment' })) - await flushPromises() - saveTitle('Old title', 'New title') - await flushPromises() - expect(screen.getByText('Existing comment')).toBeDefined() - expect(screen.getByText('New comment')).toBeDefined() - expect(runtimeMocks.jiraIssueCommentsForTarget).toHaveBeenCalledTimes(1) - }) - - it('keeps a cleared priority cleared when an older detail load arrives', async () => { - const initialLoad = deferred() - const initial = jiraIssue('Old title', { priority: { id: '1', name: 'High' } }) - runtimeMocks.jiraGetIssueForTarget.mockReturnValue(initialLoad.promise) - runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(deferred<{ ok: true }>().promise) - render() - await flushPromises() - fireEvent.click(screen.getByRole('button', { name: 'High' })) - fireEvent.click(await screen.findByRole('button', { name: 'No priority' })) - await act(async () => initialLoad.resolve(initial)) - await flushPromises() - expect(screen.queryByRole('button', { name: 'High' })).toBeNull() - expect(runtimeMocks.jiraGetIssueForTarget).toHaveBeenCalledTimes(1) - expect(runtimeMocks.jiraIssueCommentsForTarget).toHaveBeenCalledTimes(1) - }) - - it('allows editing a newly opened issue while an earlier save is still pending', async () => { - const oldSave = deferred<{ ok: true }>() - runtimeMocks.jiraUpdateIssueForTarget - .mockReturnValueOnce(oldSave.promise) - .mockResolvedValue({ ok: true }) - runtimeMocks.jiraGetIssueForTarget.mockImplementation( - async (_settings: unknown, key: string) => - key === 'ENG-2' ? otherIssue : jiraIssue(editState.serverTitle) - ) - render() - await flushPromises() - saveTitle('Old title', 'New title') - await act(async () => selectIssue(otherIssue)) - await flushPromises() - saveTitle('Other issue', 'Other updated') - await flushPromises() - expect(runtimeMocks.jiraUpdateIssueForTarget).toHaveBeenCalledTimes(2) - await act(async () => oldSave.resolve({ ok: true })) - await flushPromises() - expect(screen.getByText('ENG-2')).toBeDefined() - }) - - it('still hydrates fields the user did not edit when the initial load lands late', async () => { - const initialLoad = deferred() - runtimeMocks.jiraGetIssueForTarget.mockImplementationOnce(() => initialLoad.promise) - runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(deferred<{ ok: true }>().promise) - render() - await flushPromises() - - saveTitle('Old title', 'New title') - await flushPromises() - await act(async () => initialLoad.resolve(jiraIssue('Old title', { labels: ['backend'] }))) - await flushPromises() - - expect(screen.getByDisplayValue('New title')).toBeDefined() - expect(screen.getByDisplayValue('backend')).toBeDefined() - }) - - it.each([ - ['succeeds', { ok: true }], - ['fails', { ok: false, error: 'Nope' }] - ] as const)( - 'stays on the newly opened issue when a save for the previous one %s', - async (_, outcome) => { - // The task page reuses this instance; a late save must not restore a previously selected issue. - const update = deferred() - runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(update.promise) - runtimeMocks.jiraGetIssueForTarget.mockImplementation( - async (_settings: unknown, key: string) => - key === 'ENG-2' ? otherIssue : jiraIssue(editState.serverTitle) - ) - render() - await flushPromises() - - saveTitle('Old title', 'New title') - await flushPromises() - await act(async () => selectIssue(otherIssue)) - await flushPromises() - expect(screen.getByText('ENG-2')).toBeDefined() - editState.serverTitle = 'New title' - await act(async () => update.resolve(outcome)) - await flushPromises() - - expect(screen.getByText('ENG-2')).toBeDefined() - expect(screen.queryByText('ENG-1')).toBeNull() - expect(screen.getByDisplayValue('Other issue')).toBeDefined() - } - ) - - it('does not let a slow initial load overwrite a title saved meanwhile', async () => { - const initialLoad = deferred() - runtimeMocks.jiraGetIssueForTarget - .mockImplementationOnce(() => initialLoad.promise) - .mockImplementation(async () => jiraIssue(editState.serverTitle)) - runtimeMocks.jiraUpdateIssueForTarget.mockImplementation(async () => { - editState.serverTitle = 'New title' - return { ok: true } - }) - render() - await flushPromises() - - saveTitle('Old title', 'New title') - await flushPromises() - await act(async () => initialLoad.resolve(jiraIssue('Old title'))) - await flushPromises() - - expect(screen.getByDisplayValue('New title')).toBeDefined() - }) -}) diff --git a/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx b/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx index 4d1cf996009..36b4a3a5aa6 100644 --- a/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx +++ b/src/renderer/src/components/automations/AutomationsPage.refresh-selection.spec.tsx @@ -132,18 +132,6 @@ describe('AutomationsPage refresh', () => { expect(reads()).toHaveLength(beforeEvents + 2) } ) - - it('does not re-run the whole refresh when the settings identity changes', async () => { - const { rerender } = await renderPage() - expect(api.automations.list).toHaveBeenCalledTimes(1) - - mocks.state.settings = { ...(mocks.state.settings as Record) } - await rerender() - - // Settings no longer aim the list, so a new settings object is not a reason - // to re-fetch every host. - expect(api.automations.list).toHaveBeenCalledTimes(1) - }) }) describe('AutomationsPage selection', () => { diff --git a/src/renderer/src/components/dictation/DictationIndicator.tsx b/src/renderer/src/components/dictation/DictationIndicator.tsx index e92f2b1ab89..e28f3d62f16 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.tsx @@ -75,7 +75,8 @@ function useIsCloudModel(): boolean { let current = true if (!catalogRequest) { catalogRequest = Promise.resolve() - .then(() => window.api.speech.getCatalog()) + // The paired web client's fallback resolves with nothing rather than a list. + .then(async () => (await window.api.speech.getCatalog()) ?? []) .catch(() => []) } void catalogRequest.then((catalog) => { diff --git a/src/renderer/src/components/dictation/use-hold-dictation-gesture.test.tsx b/src/renderer/src/components/dictation/use-hold-dictation-gesture.test.tsx deleted file mode 100644 index 961152c20b4..00000000000 --- a/src/renderer/src/components/dictation/use-hold-dictation-gesture.test.tsx +++ /dev/null @@ -1,257 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { DictationState } from '../../../../shared/speech-types' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import { getDefaultSettings, getDefaultVoiceSettings } from '../../../../shared/constants' -import { useHoldDictationGesture } from './use-hold-dictation-gesture' -import { dictationShortcutModeSettings } from '../../../../shared/dictation-shortcut-mode' - -const originalUserAgent = navigator.userAgent - -let root: Root | null = null -let container: HTMLDivElement | null = null -let dictationState: DictationState -let dictationMode: 'auto' | 'hold' -let terminalShortcutPolicy: 'orca-first' | 'terminal-first' -let startDictation: ReturnType void>> -let stopDictation: ReturnType void>> - -function setUserAgent(userAgent: string): void { - Object.defineProperty(navigator, 'userAgent', { - configurable: true, - value: userAgent - }) -} - -function holdSettings(): GlobalSettings { - return { - ...getDefaultSettings('/home/test'), - terminalShortcutPolicy, - voice: { - ...getDefaultVoiceSettings(), - enabled: true, - sttModel: 'test-model', - ...dictationShortcutModeSettings(dictationMode) - } - } -} - -function Probe(): null { - useHoldDictationGesture({ - canStartDictation: () => dictationState === 'idle', - isDictationUnderway: () => dictationState === 'starting' || dictationState === 'listening', - keybindings: {}, - settings: holdSettings(), - startDictation, - stopDictation - }) - return null -} - -function dispatchKeyDown(init: KeyboardEventInit): KeyboardEvent { - const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }) - window.dispatchEvent(event) - return event -} - -function dispatchKeyUp(init: KeyboardEventInit): KeyboardEvent { - const event = new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init }) - window.dispatchEvent(event) - return event -} - -async function renderProbe(): Promise { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - await act(async () => { - root?.render() - }) -} - -function beginHold(init: KeyboardEventInit = {}): void { - act(() => { - dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, ...init }) - }) - dictationState = 'listening' -} - -beforeEach(() => { - setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)') - dictationState = 'idle' - dictationMode = 'hold' - terminalShortcutPolicy = 'orca-first' - startDictation = vi.fn<() => void>() - stopDictation = vi.fn<() => void>() -}) - -afterEach(async () => { - if (root) { - await act(async () => { - root?.unmount() - }) - } - root = null - container?.remove() - container = null - setUserAgent(originalUserAgent) - vi.clearAllMocks() -}) - -describe('useHoldDictationGesture', () => { - it('stops after a layout-aware shortcut key release drops the modifier flag', async () => { - await renderProbe() - - beginHold({ key: 'e', code: 'KeyD' }) - - act(() => { - dispatchKeyUp({ key: 'e', code: 'KeyD', metaKey: false }) - }) - - expect(startDictation).toHaveBeenCalledTimes(1) - expect(stopDictation).toHaveBeenCalledTimes(1) - }) - - it('stops when the required modifier is released before the shortcut key', async () => { - await renderProbe() - - beginHold() - - act(() => { - dispatchKeyUp({ key: 'Meta', code: 'MetaLeft', metaKey: false }) - }) - - expect(startDictation).toHaveBeenCalledTimes(1) - expect(stopDictation).toHaveBeenCalledTimes(1) - }) - - it('keeps a held dictation when its callbacks and keybindings are re-created', async () => { - await renderProbe() - - beginHold() - - const firstStopDictation = stopDictation - startDictation = vi.fn<() => void>() - stopDictation = vi.fn<() => void>() - await act(async () => { - root?.render() - }) - - expect(firstStopDictation).not.toHaveBeenCalled() - expect(stopDictation).not.toHaveBeenCalled() - - act(() => { - dispatchKeyUp({ key: 'e', code: 'KeyE', metaKey: false }) - }) - - expect(stopDictation).toHaveBeenCalledTimes(1) - }) - - it('does not restart from key repeat after dictation stopped on its own', async () => { - await renderProbe() - - beginHold() - dictationState = 'idle' - - act(() => { - dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, repeat: true }) - }) - - expect(startDictation).toHaveBeenCalledTimes(1) - }) -}) - -describe('useHoldDictationGesture in Auto mode', () => { - let now = 0 - - beforeEach(() => { - dictationMode = 'auto' - now = 1000 - vi.spyOn(performance, 'now').mockImplementation(() => now) - }) - - it('keeps recording after a tap and stops on the next press', async () => { - await renderProbe() - - // macOS drops the E keyup under Cmd, so the tap ends only when Cmd lets go. - beginHold() - now += 600 - act(() => { - dispatchKeyUp({ key: 'Meta', code: 'MetaLeft', metaKey: false }) - }) - expect(stopDictation).not.toHaveBeenCalled() - - act(() => { - dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true }) - }) - expect(startDictation).toHaveBeenCalledTimes(1) - expect(stopDictation).toHaveBeenCalledTimes(1) - }) - - it('stops on release after a press held for 300 ms', async () => { - await renderProbe() - - beginHold() - now += 300 - act(() => { - dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, repeat: true }) - }) - act(() => { - dispatchKeyUp({ key: 'Meta', code: 'MetaLeft', metaKey: false }) - }) - - expect(startDictation).toHaveBeenCalledTimes(1) - expect(stopDictation).toHaveBeenCalledTimes(1) - }) - - it('starts a hold pressed while the last dictation was still finishing', async () => { - await renderProbe() - dictationState = 'stopping' - - act(() => { - dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true }) - }) - dictationState = 'idle' - act(() => { - dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, repeat: true }) - }) - - expect(stopDictation).not.toHaveBeenCalled() - expect(startDictation).toHaveBeenCalledTimes(1) - }) - - it('leaves the shortcut to the IME while composing', async () => { - await renderProbe() - - const event = dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, isComposing: true }) - - expect(event.defaultPrevented).toBe(false) - expect(startDictation).not.toHaveBeenCalled() - }) - - it('leaves the shortcut to a terminal that owns its keys', async () => { - terminalShortcutPolicy = 'terminal-first' - await renderProbe() - const terminalInput = document.createElement('textarea') - terminalInput.className = 'xterm-helper-textarea' - document.body.appendChild(terminalInput) - - const event = new KeyboardEvent('keydown', { - bubbles: true, - cancelable: true, - key: 'e', - code: 'KeyE', - metaKey: true - }) - act(() => { - terminalInput.dispatchEvent(event) - }) - terminalInput.remove() - - expect(event.defaultPrevented).toBe(false) - expect(startDictation).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx index d04bcf20276..f4b13750029 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -102,28 +102,6 @@ it('keeps the branch checkout strip open after selecting a badge context-menu ac expect(container.querySelector('form')?.textContent).toContain('Check out branch topic?') }) -it('renders converging branch lanes and a detached root without duplicate child keys', async () => { - const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) - getHistory.mockReset().mockResolvedValue({ - ...result, - items: [ - { id: 'a', subject: 'a', message: 'a', parentIds: ['root'] }, - { id: 'b', subject: 'b', message: 'b', parentIds: ['root'] }, - { id: 'c', subject: 'c', message: 'c', parentIds: ['root'] }, - { id: 'detached', subject: 'detached', message: 'detached', parentIds: [] }, - { id: 'root', subject: 'root', message: 'root', parentIds: [] } - ] - }) - await act(async () => - root.render( - - - - ) - ) - expect(errors.mock.calls.filter(([message]) => String(message).includes('same key'))).toEqual([]) -}) - it('recovers silently after each later token expiry and ignores refreshes for other worktrees', async () => { let history: ReturnType function History() { diff --git a/src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-client.test.ts b/src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-client.test.ts deleted file mode 100644 index 30b82b77773..00000000000 --- a/src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-client.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { MarkdownPreviewDocumentClient } from './markdown-preview-document-client' -import { - MARKDOWN_PREVIEW_WORKER_TIMEOUT_MS, - type MarkdownPreviewWorkerResult -} from './markdown-preview-document-types' - -class WorkerTransport extends EventTarget implements Worker { - onmessage: Worker['onmessage'] = null - onerror: Worker['onerror'] = null - onmessageerror: Worker['onmessageerror'] = null - postMessage = vi.fn<(message: unknown) => void>() - terminate = vi.fn() - reply(result: MarkdownPreviewWorkerResult): void { - this.onmessage?.(new MessageEvent('message', { data: result })) - } -} - -afterEach(() => vi.useRealTimers()) -describe('Markdown preview worker ownership', () => { - it('cancels a timed-out search without terminating a working preview', async () => { - vi.useFakeTimers() - const worker = new WorkerTransport() - const failure = vi.fn() - const client = new MarkdownPreviewDocumentClient(worker, failure) - const search = client.request({ type: 'search', query: 'needle' }).catch((error) => error) - await vi.advanceTimersByTimeAsync(MARKDOWN_PREVIEW_WORKER_TIMEOUT_MS) - expect(await search).toEqual(new Error('Preview search timed out.')) - expect(worker.postMessage).toHaveBeenLastCalledWith({ id: 2, type: 'cancel-search' }) - expect(worker.terminate).not.toHaveBeenCalled() - expect(failure).not.toHaveBeenCalled() - worker.reply({ id: 1, type: 'search', matches: [], truncated: false }) - const blocks = client.request({ type: 'blocks', indices: [0] }) - worker.reply({ id: 3, type: 'blocks', blocks: [] }) - expect(await blocks).toMatchObject({ type: 'blocks' }) - expect(vi.getTimerCount()).toBe(0) - client.close() - }) -}) diff --git a/src/renderer/src/components/feature-tips/feature-tip-startup-gate.test.ts b/src/renderer/src/components/feature-tips/feature-tip-startup-gate.test.ts deleted file mode 100644 index 9a33ceba369..00000000000 --- a/src/renderer/src/components/feature-tips/feature-tip-startup-gate.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createGlobalSettingsFixture } from '../../../../shared/global-settings-test-fixture' -import { getDefaultVoiceSettings } from '../../../../shared/constants' -import { useAppStore } from '../../store' -import { getPendingFeatureTips } from './feature-tip-startup-gate' - -afterEach(() => { - useAppStore.setState(useAppStore.getInitialState(), true) - vi.unstubAllGlobals() -}) - -it('offers the rollout after historical completion and consumes only its own exposure', () => { - vi.stubGlobal('window', { api: { ui: { set: vi.fn().mockResolvedValue(undefined) } } }) - const settings = createGlobalSettingsFixture({ - voice: { ...getDefaultVoiceSettings(), enabled: true }, - aiVaultSearch: { enabled: true, historyDays: null }, - telemetry: { - optedIn: true, - installId: 'install', - existedBeforeTelemetryRelease: true, - chatUiLaunchTipCohort: 'control', - chatUiLaunchTipRolloutCohort: 'treatment' - } - }) - useAppStore.setState({ - settings, - featureTipsSeenIds: ['chat-ui-here', 'cmd-j-palette'] - }) - const pendingTipIds = () => - getPendingFeatureTips({ - seenTipIds: useAppStore.getState().featureTipsSeenIds, - cliInstalled: true, - featureInteractions: {}, - chatUiLaunchTipVariant: 'chat-ui-off', - settings, - webClient: false - }).map((tip) => tip.id) - - expect(pendingTipIds()).toEqual(['chat-ui-here']) - useAppStore.getState().markFeatureTipsSeen(['chat-ui-here']) - expect(useAppStore.getState().featureTipsSeenIds).toEqual([ - 'chat-ui-here', - 'cmd-j-palette', - 'chat-ui-here-rollout-v1' - ]) - expect(pendingTipIds()).toEqual([]) -}) diff --git a/src/renderer/src/components/github-item-dialog/load-item-details/work-item-details-issue-target.test.ts b/src/renderer/src/components/github-item-dialog/load-item-details/work-item-details-issue-target.test.ts deleted file mode 100644 index 81baee6bf4c..00000000000 --- a/src/renderer/src/components/github-item-dialog/load-item-details/work-item-details-issue-target.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { - getWorkItemDetailsCacheKey, - invalidateWorkItemDetailsCacheByMatch, - touchWorkItemDetailsCache, - workItemDetailsCache -} from './work-item-details-cache' - -vi.mock('@/lib/work-items/github/github-work-item-details-cache-events', () => ({ - onGitHubWorkItemDetailsCacheMutation: vi.fn() -})) - -const keyArgs = { - repoId: 'repo-1', - repoPath: '/home/fixture/widgets', - type: 'issue' as const, - number: 12, - issueSourcePreference: 'origin' -} -const ORIGIN = { owner: 'fork-owner', repo: 'widgets', host: 'github.com' } -const UPSTREAM = { owner: 'upstream-owner', repo: 'widgets', host: 'github.com' } - -describe('issue detail cache repository identity', () => { - it('invalidates both repository variants after a mutation', () => { - const originKey = getWorkItemDetailsCacheKey({ ...keyArgs, ownerRepo: ORIGIN }) - const upstreamKey = getWorkItemDetailsCacheKey({ ...keyArgs, ownerRepo: UPSTREAM }) - touchWorkItemDetailsCache(originKey, { details: null, fetchedAt: 0 }) - touchWorkItemDetailsCache(upstreamKey, { details: null, fetchedAt: 0 }) - - invalidateWorkItemDetailsCacheByMatch(keyArgs) - - expect(workItemDetailsCache.has(originKey)).toBe(false) - expect(workItemDetailsCache.has(upstreamKey)).toBe(false) - }) -}) diff --git a/src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx b/src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx deleted file mode 100644 index 586b448eeea..00000000000 --- a/src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx +++ /dev/null @@ -1,145 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { i18n, loadRendererUiLanguage } from '@/i18n/i18n' -import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' -import { TooltipProvider } from '../../ui/tooltip' -import { LinearIntegrationCard } from './linear-integration-card' - -type StoreState = { - linearStatus: { - connected: boolean - workspaces?: { id: string; organizationName: string; displayName: string; email?: string }[] - } - linearStatusChecked: boolean - linearStatusContextKey: string | null - disconnectLinear: () => Promise - disconnectLinearWorkspace: (workspaceId?: string) => Promise - checkLinearConnection: (force?: boolean) => Promise - testLinearConnection: (workspaceId: string) => Promise<{ ok: boolean; error?: string }> - settings: { activeRuntimeEnvironmentId: string | null } - openSettingsPage: () => void - openSettingsTarget: (target: { pane: string; repoId: string | null }) => void -} - -const mocks = vi.hoisted(() => ({ - store: { current: null as StoreState | null } -})) - -vi.mock('@/store/index', () => ({ - useAppStore: Object.assign( - (selector: (state: StoreState) => unknown) => { - if (!mocks.store.current) { - throw new Error('Store state was not installed') - } - return selector(mocks.store.current) - }, - { getState: () => mocks.store.current } - ) -})) - -vi.mock('@/components/linear-api-key-dialog', () => ({ - LinearApiKeyDialog: ({ onConnected }: { onConnected?: () => void }) => ( - - ) -})) - -let root: Root | null = null -let container: HTMLDivElement | null = null - -function installStore( - connected: boolean, - settings: StoreState['settings'] = { activeRuntimeEnvironmentId: null } -): StoreState { - const state: StoreState = { - linearStatus: { - connected, - workspaces: connected - ? [ - { - id: 'workspace-1', - organizationName: 'Acme', - displayName: 'Acme workspace', - email: 'linear@example.test' - } - ] - : [] - }, - linearStatusChecked: true, - linearStatusContextKey: getProviderRuntimeContextKey(settings), - disconnectLinear: vi.fn(async () => {}), - disconnectLinearWorkspace: vi.fn(async () => {}), - checkLinearConnection: vi.fn(async () => {}), - testLinearConnection: vi.fn(async () => ({ ok: true })), - settings, - openSettingsPage: vi.fn(), - openSettingsTarget: vi.fn() - } - mocks.store.current = state - return state -} - -async function renderCard(): Promise { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - await act(async () => { - root?.render( - - - - ) - }) - return container -} - -describe('LinearIntegrationCard account scope', () => { - beforeEach(() => { - // Stub the skill scan so the CTA renders setup state rather than a bridge error. - Object.defineProperty(window, 'api', { - configurable: true, - value: { - skills: { discover: async () => ({ skills: [], sources: [], scannedAt: 0 }) } - } - }) - }) - - afterEach(async () => { - if (root) { - await act(async () => { - root?.unmount() - }) - } - root = null - container?.remove() - container = null - mocks.store.current = null - await i18n.changeLanguage(await loadRendererUiLanguage('en')) - Reflect.deleteProperty(window, 'api') - }) - - it('clears verification state after adding another Linear workspace', async () => { - installStore(true) - const rendered = await renderCard() - - await act(async () => { - Array.from(rendered.querySelectorAll('button')) - .find((button) => button.textContent === 'Test') - ?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - expect(rendered.textContent).toContain('Verified') - - await act(async () => { - rendered - .querySelector('[data-testid="simulate-linear-connected"]') - ?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(rendered.textContent).not.toContain('Verified') - }) -}) diff --git a/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.appearance.test.tsx b/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.appearance.test.tsx index 7228e7622d9..8d491592066 100644 --- a/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.appearance.test.tsx +++ b/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.appearance.test.tsx @@ -18,9 +18,6 @@ import { useNativeChatDisclosures } from '../../messages/disclosure/native-chat-disclosure-store' -import { i18n } from '@/i18n/i18n' -import { TranslationScopeProvider } from '@/i18n/translation-scope-provider' - { const QUESTION = 'What would you like me to do next in this repo?' const ASK_INPUT = { questions: [{ question: QUESTION }] } @@ -288,66 +285,3 @@ import { TranslationScopeProvider } from '@/i18n/translation-scope-provider' }) }) } - -{ - function runHeader(container: HTMLElement): HTMLElement { - const header = container.querySelector('button') - if (!header) { - throw new Error('run header did not render') - } - return header - } - - describe('tool run sentences', () => { - afterEach(async () => { - cleanup() - await i18n.changeLanguage('en') - }) - - it('relabels an already-mounted run and its rows when the UI language changes', async () => { - const blocks: NativeChatBlock[] = [ - { type: 'tool-call', name: 'Bash', input: { command: 'false' }, state: 'failed' }, - { type: 'tool-result', output: 'exit 1', isError: true }, - { - type: 'tool-call', - name: 'Agent', - input: { description: 'explore settings' }, - state: 'completed' - } - ] - const { container } = render( - , - { wrapper: TranslationScopeProvider } - ) - const header = runHeader(container) - expect(header).toHaveTextContent('Ran 1 command and ran 1 agent · 1 failed') - expect(screen.getByText('Subagent')).toBeInTheDocument() - expect(screen.getByText('Background workflow')).toBeInTheDocument() - expect(screen.getByText('Output: /tmp/result.txt')).toBeInTheDocument() - - await act(async () => { - await i18n.changeLanguage('es') - }) - - expect(header).toHaveTextContent('Se ejecutó 1 comando y se ejecutó 1 agente · 1 fallidas') - expect(header).toHaveAccessibleName(/Llamadas a herramientas fallidas: 1/) - expect(screen.getByText('Subagente')).toBeInTheDocument() - expect(screen.getByText('Flujo de trabajo en segundo plano')).toBeInTheDocument() - expect(screen.getByText('Salida: /tmp/result.txt')).toBeInTheDocument() - expect(screen.getByText('bloqueado · con error')).toBeInTheDocument() - }) - }) -} diff --git a/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.test.tsx b/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.test.tsx deleted file mode 100644 index c377da829d7..00000000000 --- a/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.test.tsx +++ /dev/null @@ -1,217 +0,0 @@ -// @vitest-environment happy-dom -import type * as OriginalModule0 from '@/runtime/provider-accounts/observations/runtime-provider-accounts-client' -import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { NativeChatUsageLimitActionsProvider } from './NativeChatUsageLimitActions' -import { NativeChatNoticeRow } from '../messages/notices/NativeChatNoticeRow' -import type { NativeChatOrcaStopView } from '../messages/notices/native-chat-orca-stop-context' -import { TooltipProvider } from '@/components/ui/tooltip' - -import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types' -import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' -import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' -import type { useNativeChatUsageLimitAutoContinue } from './use-native-chat-usage-limit-auto-continue' - -const mocks = vi.hoisted(() => ({ - readSnapshot: { - canSwitchAccount: true, - transcriptPath: '/work/chat.jsonl' - }, - follows: true, - watch: vi.fn(), - options: vi.fn(), - snapshot: vi.fn(), - select: vi.fn(), - dialog: vi.fn() -})) -let status = new Map>() -vi.mock('@/runtime/native-chat/host-capabilities/structured-agent-session-host-capability', () => ({ - useStructuredAgentSessionHostCapabilityState: () => 'supported' -})) -vi.mock('@/runtime/native-chat/status/structured-agent-session-status-feed', () => ({ - getStructuredAgentSessionStatusFeed: () => ({ - activate: () => () => {}, - subscribe: () => () => {}, - getSnapshot: () => status - }) -})) -vi.mock('../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: mocks.options -})) -vi.mock('@/runtime/native-chat/naming/structured-conversation-name', () => ({ - useStructuredChatTabConversationName: () => 'My chat' -})) -vi.mock('../../../runtime/provider-accounts/ownership/use-active-account-owner', () => ({ - useActiveAccountOwner: () => ({ - target: { kind: 'environment', environmentId: 'other' }, - wslHostDistro: null - }) -})) -vi.mock('@/lib/windows-terminal-capabilities', () => ({ - getWindowsTerminalCapabilityOwnerKey: () => 'local', - useWindowsTerminalCapabilities: () => ({ wslDistros: [] }) -})) -vi.mock( - '@/runtime/provider-accounts/observations/runtime-provider-accounts-client', - async (importOriginal) => ({ - ...(await importOriginal()), - fetchProviderAccountsSnapshot: mocks.snapshot, - watchProviderAccounts: mocks.watch, - selectClaudeProviderAccount: mocks.select, - emptyClaudeAccountsState: () => ({ - accounts: [], - activeAccountId: null, - activeAccountIdsByRuntime: { host: null, wsl: {} } - }) - }) -) -vi.mock('@/lib/provider-accounts/claude-account-switch-sessions', () => ({ - handleRunningClaudeSessionsAfterSwitch: vi.fn() -})) -vi.mock('@/components/agent-session-continuation/AgentSessionContinuationDialog', () => ({ - AgentSessionContinuationDialog: (props: { - onOpenChange: (open: boolean) => void - onStarted?: () => void - }) => { - mocks.dialog(props) - return ( - <> - - - - ) - } -})) -beforeEach(() => { - status = new Map() - mocks.options.mockResolvedValue(mocks.readSnapshot) - mocks.watch.mockImplementation((target, handlers) => { - let closed = false - void mocks.snapshot(target).then((value: unknown) => { - if (!closed) { - handlers.onSnapshot(value) - } - }) - return { - close: () => { - closed = true - } - } - }) -}) -afterEach(() => { - cleanup() - vi.clearAllMocks() - vi.useRealTimers() - mocks.follows = true -}) - -function row( - target: RuntimeClientTarget = { kind: 'local' }, - offered = true, - agent: AgentType = 'claude', - messages: readonly NativeChatMessage[] = [], - recovery: Parameters[0]['recovery'] = { - readCurrent: true, - canSwitchAccount: mocks.follows - }, - automatic?: ReturnType -) { - const view: NativeChatOrcaStopView = { - hostLabel: null, - remoteHost: target.kind !== 'local', - continueAvailable: false, - offeredTurnItemId: null, - continueNow: vi.fn(), - usageLimitTurnItemId: offered ? 'cut' : null, - usageLimitAutoContinue: automatic, - onUsageLimitHandOffStarted: automatic?.kind === 'scheduled' ? automatic.cancel : undefined, - continueUsageLimit: vi.fn() - } - return ( - - - - - - ) -} -function expectInlineActions(accountName: string | null) { - const leadIn = screen.getByText('Continue this chat without waiting:') - const actions = leadIn.parentElement - const handOff = screen.getByRole('button', { name: 'Hand Off to Another Agent' }) - const account = accountName ? screen.getByRole('button', { name: accountName }) : null - expect(actions).toHaveClass('flex', 'flex-wrap', 'items-center') - expect(Array.from(actions?.children ?? [])).toEqual([ - leadIn, - ...(account ? [account.parentElement] : []), - handOff - ]) - if (account) { - expect(account.parentElement).toHaveClass('w-32', 'shrink-0') - } -} -it('admits one preparation and discards it after Continue supersedes the cut', async () => { - let answer: (value: typeof mocks.readSnapshot) => void = () => {} - mocks.options.mockImplementation( - () => - new Promise((resolve) => { - answer = resolve - }) - ) - mocks.follows = false - const view = render(row()) - expect( - screen.getByText('Continue this chat without waiting:').parentElement?.querySelector('.w-32') - ).toBeNull() - expectInlineActions(null) - const button = screen.getByRole('button', { name: 'Hand Off to Another Agent' }) - fireEvent.click(button) - fireEvent.click(button) - expect(mocks.options).toHaveBeenCalledTimes(1) - expect(button).toBeDisabled() - view.rerender(row({ kind: 'local' }, false)) - answer(mocks.readSnapshot) - await waitFor(() => expect(mocks.dialog).not.toHaveBeenCalled()) - view.rerender(row()) - mocks.options.mockResolvedValue(mocks.readSnapshot) - fireEvent.click(screen.getByRole('button', { name: 'Hand Off to Another Agent' })) - await screen.findByText('Cancel hand-off') - fireEvent.click(screen.getByText('Cancel hand-off')) - expect(screen.queryByText('Cancel hand-off')).toBeNull() -}) diff --git a/src/renderer/src/components/plugins/frames/plugin-frame-host-declarative.test.ts b/src/renderer/src/components/plugins/frames/plugin-frame-host-declarative.test.ts deleted file mode 100644 index 6befaf7c128..00000000000 --- a/src/renderer/src/components/plugins/frames/plugin-frame-host-declarative.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { createPluginFrameEnvelopeHandler, type PluginFrameHostOptions } from './plugin-frame-host' -import { pluginWebviewFrameWindow } from './plugin-frame-host-lanes' - -vi.mock('./plugin-panel-design-token-css', () => ({ - currentPluginFrameTheme: () => ({ colorScheme: 'dark', tokens: '' }) -})) - -const guestContext = { userActivation: true, transport: 'guest' as const } -const flush = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)) - -function declarativeGuest(overrides: Partial = {}) { - const webview = { send: vi.fn() } - const onRender = vi.fn() - const onRefused = vi.fn() - const callHostMethod = vi.fn().mockResolvedValue({ ok: true, value: null }) - const handle = createPluginFrameEnvelopeHandler({ - surface: 'panel', - getFrameWindow: () => pluginWebviewFrameWindow(webview), - getSessionToken: () => 'token', - callHostMethod, - declarative: { onRender, onError: vi.fn(), onRefused }, - ...overrides - }) - const render = (tree: unknown, revision = 1) => - handle({ orca: 1, kind: 'evt', event: 'ui.render', payload: { revision, tree } }, guestContext) - return { handle, render, onRender, onRefused, callHostMethod, webview } -} - -describe('declarative render lane', () => { - it("ignores the hidden guest's own activation for user-gesture methods", async () => { - const consumeHostActivation = vi.fn(() => false) - const { handle, callHostMethod } = declarativeGuest({ consumeHostActivation }) - const open = (id: number) => ({ - orca: 1, - kind: 'req', - id, - method: 'shell.openExternal', - params: { url: 'https://example.com' } - }) - handle(open(1), guestContext) - await flush() - expect(callHostMethod).not.toHaveBeenCalled() - consumeHostActivation.mockReturnValue(true) - handle(open(2), { userActivation: false, transport: 'guest' }) - await flush() - expect(callHostMethod).toHaveBeenCalledOnce() - }) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-publication-gate.test.ts b/src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-publication-gate.test.ts deleted file mode 100644 index f01e17da20b..00000000000 --- a/src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-session-publication-gate.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - markInputQuietSchedulerInput, - resetInputQuietSchedulerForTest -} from '@/lib/input-quiet-scheduler' -import type { AiVaultListResult } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' -import { AiVaultSessionPublicationGate } from './ai-vault-session-publication-gate' - -const FIRST: AiVaultListResult = { sessions: [], issues: [], scannedAt: '2026-08-09T00:00:00.000Z' } -const SECOND: AiVaultListResult = { ...FIRST, scannedAt: '2026-08-09T00:00:01.000Z' } - -afterEach(() => { - vi.useRealTimers() - resetInputQuietSchedulerForTest() -}) - -describe('AiVaultSessionPublicationGate', () => { - // A chat-link snapshot right after a restart cancels the gate; it must not drop the saved list. - it('shows a late saved list after a cancel but never over a newer published list', async () => { - const shown = vi.fn() - const gate = new AiVaultSessionPublicationGate() - gate.showUntilPublished(Promise.resolve(FIRST), shown) - gate.cancel() - await Promise.resolve() - expect(shown).toHaveBeenCalledWith(FIRST) - - const late = vi.fn() - gate.showUntilPublished(Promise.resolve(FIRST), late) - gate.publish(SECOND, vi.fn()) - await Promise.resolve() - expect(late).not.toHaveBeenCalled() - }) - - it('still shows a late saved list when the list published meanwhile was cancelled before it landed', async () => { - vi.useFakeTimers() - const shown = vi.fn() - const published = vi.fn() - const gate = new AiVaultSessionPublicationGate() - gate.showUntilPublished(Promise.resolve(FIRST), shown) - markInputQuietSchedulerInput() - gate.publish(SECOND, published) - gate.cancel() - await Promise.resolve() - vi.advanceTimersByTime(1_000) - - expect(published).not.toHaveBeenCalled() - expect(shown).toHaveBeenCalledWith(FIRST) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/comments/pr-comments-ai-launch-ack.test.ts b/src/renderer/src/components/right-sidebar/checks-panel/comments/pr-comments-ai-launch-ack.test.ts deleted file mode 100644 index 265146d1e6e..00000000000 --- a/src/renderer/src/components/right-sidebar/checks-panel/comments/pr-comments-ai-launch-ack.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { PRComment } from '../../../../../../shared/github/comment-types' -import { - canPostPRReviewThreadReply, - resolvePRReviewReplyThreadId -} from './pr-comments-ai-launch-ack' - -function comment(overrides: Partial = {}): PRComment { - return { - id: 1, - author: 'alice', - authorAvatarUrl: '', - body: 'Please update this.', - createdAt: '2026-05-14T00:00:00Z', - url: 'https://github.com/acme/widgets/pull/42#discussion_r1', - ...overrides - } -} - -describe('canPostPRReviewThreadReply', () => { - // Review-summary anchors override thread metadata; their IDs would 404 on the nested replies endpoint. - it('rejects review summaries even when thread metadata is present', () => { - expect( - canPostPRReviewThreadReply( - comment({ - id: 5, - threadId: 'T1', - path: 'src/a.ts', - url: 'https://github.com/acme/widgets/pull/42#pullrequestreview-999' - }) - ) - ).toBe(false) - }) -}) - -describe('resolvePRReviewReplyThreadId', () => { - it('refuses a path-only match when the file holds several threads', () => { - const existing = [ - comment({ id: 1, threadId: 'T_one', path: 'src/a.ts', line: 3 }), - comment({ id: 2, threadId: 'T_two', path: 'src/a.ts', line: 40 }) - ] - expect( - resolvePRReviewReplyThreadId({ - parent: comment({ id: 50, path: 'src/a.ts', line: undefined }), - existingComments: existing - }) - ).toBeUndefined() - // A line-scoped parent still matches its own thread. - expect( - resolvePRReviewReplyThreadId({ - parent: comment({ id: 50, path: 'src/a.ts', line: 40 }), - existingComments: existing - }) - ).toBe('T_two') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/checks-panel/logs/check-log-initial-diagnostic-position.test.ts b/src/renderer/src/components/right-sidebar/checks-panel/logs/check-log-initial-diagnostic-position.test.ts deleted file mode 100644 index 4d478c5ed82..00000000000 --- a/src/renderer/src/components/right-sidebar/checks-panel/logs/check-log-initial-diagnostic-position.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it } from 'vitest' -import { PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR as separator } from '../../../../../../shared/source-control/checks/logs/check-job-log-tail-slice' -import { findInitialCheckLogDiagnostic } from './check-log-initial-diagnostic-position' - -describe('synthetic diagnostic excerpts', () => { - it('keeps an inline diagnostic with stack context ahead of a later standalone error', () => { - const text = '[worker] failed TypeError: invalid argument\n at worker.ts:3:4\nError: later' - const anchor = findInitialCheckLogDiagnostic(text) - expect(anchor && text.slice(anchor.start, anchor.end)).toBe('TypeError: invalid argument') - expect(anchor && text.slice(anchor.nearbyStackStart, anchor.nearbyStackEnd)).toBe( - ' at worker.ts:3:4' - ) - }) - - it('does not borrow a diagnostic or its frame from across the omission boundary', () => { - const text = `[worker] caught Error: expected\n${separator}\nError: failed to open database at database.ts:4:5\n at real.ts:8:9` - const anchor = findInitialCheckLogDiagnostic(text) - expect(anchor && text.slice(anchor.start, anchor.end)).toBe( - 'Error: failed to open database at database.ts:4:5' - ) - expect(anchor && text.slice(anchor.nearbyStackStart, anchor.nearbyStackEnd)).toBe( - ' at real.ts:8:9' - ) - const fallback = findInitialCheckLogDiagnostic( - `[worker] caught Error: expected\n${separator}\n at real.ts:8:9` - ) - expect(fallback?.nearbyStackStart).toBeUndefined() - }) - - it('retains unframed inline diagnostics as the recent-segment fallback', () => { - const text = `Error: earlier failure\n${separator}\n[worker] failed EACCES: open database\n##[error]Process completed with exit code 1` - const anchor = findInitialCheckLogDiagnostic(text) - expect(anchor && text.slice(anchor.start, anchor.end)).toBe('EACCES: open database') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/listing/open-uncommitted-entry.test.ts b/src/renderer/src/components/right-sidebar/source-control/listing/open-uncommitted-entry.test.ts deleted file mode 100644 index cbe7b2d0d71..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/listing/open-uncommitted-entry.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createEditorStore } from '@/store/slices/editor/editor-slice-test-harness' -import type { GitStatusEntry } from '../../../../../../shared/git/status/git-status-types' -import { openUncommittedEntry } from './open-uncommitted-entry' - -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) -vi.mock('@/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab', () => ({ - notifyHostOfMirroredEditorClose: vi.fn() -})) - -function markdownEntry(overrides: Partial = {}): GitStatusEntry { - return { - path: 'docs/new.md', - status: 'untracked', - area: 'untracked', - ...overrides - } -} - -describe('openUncommittedEntry', () => { - it.each(['source', 'changes'] as const)('preserves an explicit %s choice on reselect', (mode) => { - const store = createEditorStore() - const entry = markdownEntry() - openUncommittedEntry(store.getState(), 'wt-1', '/repo', entry) - const fileId = store.getState().openFiles[0].id - if (mode === 'changes') { - store.getState().setEditorViewMode(fileId, 'changes') - } else { - store.getState().setMarkdownViewMode(fileId, 'source') - } - - openUncommittedEntry(store.getState(), 'wt-1', '/repo', entry) - - const state = store.getState() - expect(state.openFiles).toHaveLength(1) - expect(mode === 'changes' ? state.editorViewMode[fileId] : state.markdownViewMode[fileId]).toBe( - mode - ) - }) -}) diff --git a/src/renderer/src/components/settings/accounts/AccountsPane.owner-scope.test.tsx b/src/renderer/src/components/settings/accounts/AccountsPane.owner-scope.test.tsx deleted file mode 100644 index 1d1cc3b2c25..00000000000 --- a/src/renderer/src/components/settings/accounts/AccountsPane.owner-scope.test.tsx +++ /dev/null @@ -1,215 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import { i18n } from '@/i18n/i18n' -import { getDefaultSettings } from '../../../../../shared/constants' -import type { - ClaudeManagedAccountSummary, - ClaudeRateLimitAccountsState -} from '../../../../../shared/managed-account-types' -import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' -import { AccountsPane } from './AccountsPane' -import type { SettingsHostScope } from '../host-scope/settings-host-scope' -import type { SettingsNavigationTarget } from '@/lib/settings-navigation-types' - -// Why: focus deliberately points at another server; the pane must follow hostScope only. -const focusedElsewhere = { - ...getDefaultSettings('/synthetic'), - activeRuntimeEnvironmentId: 'focused-server' -} -const scopeFor = (environmentId: string | null): SettingsHostScope => ({ - target: environmentId ? { kind: 'environment', environmentId } : { kind: 'local' }, - available: true -}) -const renderPane = (scope: SettingsHostScope): React.JSX.Element => ( - -) - -const fake = vi.hoisted(() => { - const state: { - query: string - pendingSelect: ((roster: unknown) => void) | null - write: ReturnType - add: ReturnType - navigate: (target: SettingsNavigationTarget) => void - rosters: Map - watchedTargets: unknown[] - selects: unknown[][] - } = { - query: 'claude', - pendingSelect: null, - write: vi.fn(), - add: vi.fn(), - navigate: () => {}, - rosters: new Map(), - watchedTargets: [], - selects: [] - } - return state -}) -vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn() } })) -vi.mock('@/store/index', () => ({ - useAppStore: (selector: (state: Record) => unknown) => - selector({ - settingsSearchQuery: fake.query, - settings: focusedElsewhere, - openSettingsTarget: (target: SettingsNavigationTarget) => fake.navigate(target), - openSettingsPage: fake.write, - rateLimits: { - codex: null, - codexTarget: { runtime: 'host', wslDistro: null }, - minimax: null, - cursor: { updatedAt: 0 }, - grok: { updatedAt: 0 }, - inactiveClaudeAccounts: [], - claudeTarget: { runtime: 'host', wslDistro: null } - }, - runtimeEnvironments: [], - runtimeStatusByEnvironmentId: new Map(), - recordFeatureInteraction: fake.write, - fetchSettings: fake.write, - fetchInactiveClaudeAccountUsage: fake.write - }) -})) -vi.mock('@/runtime/provider-accounts/sign-in/runtime-antigravity-accounts-client', () => ({ - callAntigravityAccounts: vi.fn(), - callAntigravityChatSignIn: vi.fn(), - subscribeAntigravityChatSignIn: vi.fn() -})) -vi.mock('@/runtime/provider-accounts/observations/runtime-provider-accounts-client', () => { - const empty = () => ({ - accounts: [], - activeAccountId: null, - activeAccountIdsByRuntime: { host: null, wsl: {} } - }) - return { - emptyClaudeAccountsState: empty, - emptyCodexAccountsState: empty, - getProviderAccountsOwnerKey: (target: RuntimeClientTarget) => - target.kind === 'environment' ? target.environmentId : 'local', - watchProviderAccounts: ( - target: RuntimeClientTarget, - handlers: { onSnapshot: (snapshot: unknown) => void } - ) => { - fake.watchedTargets.push(target) - handlers.onSnapshot({ - claude: fake.rosters.get(target.kind === 'environment' ? target.environmentId : 'local'), - codex: empty(), - rateLimits: null - }) - return { close: vi.fn() } - }, - fetchProviderAccountsSnapshot: async (target: RuntimeClientTarget) => ({ - claude: fake.rosters.get(target.kind === 'environment' ? target.environmentId : 'local') - }), - selectClaudeProviderAccount: (...args: unknown[]) => { - fake.selects.push(args) - return new Promise((resolve) => { - fake.pendingSelect = resolve - }) - }, - selectCodexProviderAccount: fake.write, - removeClaudeProviderAccount: fake.write, - removeCodexProviderAccount: fake.write - } -}) - -function claudeRoster(id: string, email: string, active: boolean): ClaudeRateLimitAccountsState { - const account: ClaudeManagedAccountSummary = { - id, - email, - authMethod: 'subscription-oauth', - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - const activeId = active ? id : null - return { - accounts: [account], - activeAccountId: activeId, - activeAccountIdsByRuntime: { host: activeId, wsl: {} } - } -} - -vi.mock('@/lib/provider-accounts/claude-account-switch-sessions', () => ({ - handleRunningClaudeSessionsAfterSwitch: vi.fn(async () => 'no-running-sessions') -})) -vi.mock('../../../runtime/provider-accounts/ownership/use-active-account-owner', () => ({ - useActiveAccountOwner: () => ({ target: { kind: 'local' }, wslHostDistro: null }) -})) -vi.mock('@/lib/windows-terminal-capabilities', () => ({ - getWindowsTerminalCapabilityOwnerKey: () => 'local', - useWindowsTerminalCapabilities: () => ({ wslDistros: ['Ubuntu'] }) -})) - -beforeEach(async () => { - await i18n.changeLanguage('en') - vi.mocked(toast.error).mockClear() - fake.query = 'claude' - fake.write.mockClear() - fake.add.mockReset() - fake.add.mockImplementation(async () => fake.rosters.get('local')) - fake.pendingSelect = null - fake.watchedTargets = [] - fake.selects = [] - fake.rosters.set('local', claudeRoster('acct-l', 'local@desktop.test', false)) - fake.rosters.set('server-a', claudeRoster('acct-a', 'alpha@server-a.test', false)) - fake.rosters.set('server-b', claudeRoster('acct-b', 'beta@server-b.test', false)) - Object.assign(window, { - api: { - claudeAccounts: { add: fake.add }, - minimaxCredentials: { - getStatus: vi.fn(async () => ({ cookieConfigured: false, apiKeyConfigured: false })) - }, - codexConfigSync: { - status: vi.fn(async () => ({ state: 'synced', reason: null, systemConfigPath: '/x' })) - } - } - }) -}) -afterEach(() => { - cleanup() - vi.restoreAllMocks() - Reflect.deleteProperty(window, 'api') -}) - -it("drops a server's late account result after the page moves to another server", async () => { - const view = render(renderPane(scopeFor('server-a'))) - await act(async () => {}) - fireEvent.click(screen.getByText('alpha@server-a.test')) - expect(fake.pendingSelect).not.toBeNull() - - await act(async () => view.rerender(renderPane(scopeFor('server-b')))) - expect(screen.getByText('beta@server-b.test')).toBeTruthy() - - await act(async () => fake.pendingSelect?.(claudeRoster('acct-a', 'alpha@server-a.test', true))) - - expect(screen.queryByText('alpha@server-a.test')).toBeNull() - expect(screen.getByText('beta@server-b.test')).toBeTruthy() -}) - -it('keeps a late account result once the pane is back on the server it was sent to', async () => { - const view = render(renderPane(scopeFor('server-a'))) - await act(async () => {}) - fireEvent.click(screen.getByText('alpha@server-a.test')) - for (const environmentId of ['server-b', 'server-a']) { - await act(async () => view.rerender(renderPane(scopeFor(environmentId)))) - } - const alphaRow = (): HTMLElement => { - const row = screen.getByText('alpha@server-a.test').closest('button') - expect(row).not.toBeNull() - return row ?? document.body - } - expect(within(alphaRow()).queryByText('Active')).toBeNull() - - await act(async () => fake.pendingSelect?.(claudeRoster('acct-a', 'alpha@server-a.test', true))) - - expect(within(alphaRow()).getByText('Active')).toBeTruthy() -}) diff --git a/src/renderer/src/components/settings/developer-permissions/developer-permissions-search.test.ts b/src/renderer/src/components/settings/developer-permissions/developer-permissions-search.test.ts deleted file mode 100644 index ffb180ce1dc..00000000000 --- a/src/renderer/src/components/settings/developer-permissions/developer-permissions-search.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { afterAll, describe, expect, it } from 'vitest' - -import { i18n } from '@/i18n/i18n' -import { getDeveloperPermissionsPaneSearchEntries } from './developer-permissions-search' -import { matchesSettingsSearch } from '../search/settings-search' - -// Use macOS 26’s actual Local Network translations (SecurityPrivacyExtension LOCAL_NETWORK). -const MACOS_LOCAL_NETWORK_LABEL = { - en: 'local network', - es: 'red local', - ja: 'ローカルネットワーク', - ko: '로컬 네트워크', - zh: '本地网络' -} as const - -function getLanEntry() { - const entry = getDeveloperPermissionsPaneSearchEntries().find((candidate) => - candidate.keywords?.includes('usb') - ) - if (!entry) { - throw new Error('LAN, USB, and Bluetooth search entry is missing') - } - return entry -} - -async function searchInLocale(locale: string, query: string): Promise { - await i18n.changeLanguage(locale) - return matchesSettingsSearch(query, getLanEntry()) -} - -describe('developer permissions LAN search', () => { - afterAll(async () => { - await i18n.changeLanguage('en') - }) - - it.each(Object.entries(MACOS_LOCAL_NETWORK_LABEL))( - 'finds the LAN row from the macOS Local Network wording in %s', - async (locale, label) => { - expect(await searchInLocale(locale, label)).toBe(true) - } - ) - - it('keeps the English LAN aliases findable in every locale', async () => { - for (const locale of Object.keys(MACOS_LOCAL_NETWORK_LABEL)) { - for (const query of ['lan', 'local network', 'local-network']) { - expect(await searchInLocale(locale, query)).toBe(true) - } - } - }) - - it('keeps the localized LAN wording findable', async () => { - expect(await searchInLocale('zh', '局域网')).toBe(true) - expect(await searchInLocale('ja', 'LAN')).toBe(true) - expect(await searchInLocale('ko', 'LAN')).toBe(true) - expect(await searchInLocale('es', 'LAN')).toBe(true) - }) -}) diff --git a/src/renderer/src/components/settings/shortcuts/keybinding-title-copy.test.ts b/src/renderer/src/components/settings/shortcuts/keybinding-title-copy.test.ts deleted file mode 100644 index ae7fe38db06..00000000000 --- a/src/renderer/src/components/settings/shortcuts/keybinding-title-copy.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { - agentTabActionId, - getKeybindingDefinition -} from '../../../../../shared/keybindings/definitions' -import type { - KeybindingActionId, - KeybindingDefinition -} from '../../../../../shared/keybindings/types' -import { i18n } from '@/i18n/i18n' -import { localizeKeybindingDefinition } from './keybinding-title-copy' - -function definition(actionId: KeybindingActionId): KeybindingDefinition { - const found = getKeybindingDefinition(actionId) - if (!found) { - throw new Error(`missing ${actionId}`) - } - return found -} - -describe('localizeKeybindingDefinition', () => { - afterEach(async () => { - await i18n.changeLanguage('en') - }) - - it('localizes built-in titles, keeps English searchable, and leaves plugin titles alone', async () => { - await i18n.changeLanguage('ko') - const quickOpen = definition('worktree.quickOpen') - - const localized = localizeKeybindingDefinition(quickOpen) - expect(localized.title).not.toBe(quickOpen.title) - expect(localized.group).not.toBe(quickOpen.group) - expect(localized.searchKeywords).toEqual( - expect.arrayContaining([quickOpen.title, quickOpen.group]) - ) - const agentTab = definition(agentTabActionId('claude')) - const agentTitle = localizeKeybindingDefinition(agentTab).title - expect(agentTitle).not.toBe(agentTab.title) - expect(agentTitle).toContain('Claude') - - const plugin: KeybindingDefinition = { - ...quickOpen, - id: 'plugin:orca-samples.tasks/open', - title: 'Open Tasks — Tasks', - group: 'Plugins' - } - expect(localizeKeybindingDefinition(plugin)).toBe(plugin) - }) -}) diff --git a/src/renderer/src/components/settings/terminal/TerminalInteractionSection.test.tsx b/src/renderer/src/components/settings/terminal/TerminalInteractionSection.test.tsx deleted file mode 100644 index 710397a6731..00000000000 --- a/src/renderer/src/components/settings/terminal/TerminalInteractionSection.test.tsx +++ /dev/null @@ -1,49 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createGlobalSettingsFixture } from '../../../../../shared/global-settings-test-fixture' -import { useAppStore } from '../../../store' -import { TerminalInteractionSection } from './TerminalInteractionSection' - -const i18nMock = vi.hoisted(() => { - const translations: Record = {} - return { language: 'en', translations } -}) - -vi.mock('@/i18n/i18n', () => ({ - translate: (key: string, defaultValue: string) => i18nMock.translations[key] ?? defaultValue, - i18n: i18nMock -})) - -vi.mock('@/i18n/localized-catalog', () => ({ - createLocalizedCatalog: (factory: () => unknown) => factory -})) - -describe('TerminalInteractionSection scroll on input', () => { - beforeEach(() => { - useAppStore.setState({ settingsSearchQuery: '' }) - }) - - afterEach(() => { - cleanup() - i18nMock.language = 'en' - i18nMock.translations = {} - }) - - it('keeps the row visible for a localized search keyword', () => { - i18nMock.language = 'de' - i18nMock.translations = { 'components.settings.terminal.search.snap': 'einrasten' } - useAppStore.setState({ settingsSearchQuery: 'einrasten' }) - - render( - - ) - - expect(screen.getByRole('switch', { name: 'Scroll to Bottom on Input' })).toBeTruthy() - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-board/search/workspace-kanban-search.test.ts b/src/renderer/src/components/sidebar/workspace-board/search/workspace-kanban-search.test.ts deleted file mode 100644 index 925c9c877e9..00000000000 --- a/src/renderer/src/components/sidebar/workspace-board/search/workspace-kanban-search.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import type { Repo } from '../../../../../../shared/repo-types' -import type { Worktree } from '../../../../../../shared/worktree/types' -import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' -import { matchWorkspaceBoardWorktrees } from './workspace-kanban-search' - -function worktree(overrides: Partial & { id: string }): Worktree { - return { - repoId: 'repo-a', - displayName: 'Workspace', - path: `/${overrides.id}`, - branch: 'main', - baseBranch: 'main', - isPinned: false, - sortOrder: 1, - hostId: 'local', - ...overrides - } as Worktree -} - -const repoMap = new Map([ - ['repo-a', { id: 'repo-a', displayName: 'orca' } as Repo], - ['repo-b', { id: 'repo-b', displayName: 'atlas' } as Repo] -]) - -function match(worktrees: Worktree[], query: string): ReadonlySet | null { - return matchWorkspaceBoardWorktrees({ worktrees, query, repoMap }) -} - -function identities(...worktrees: Worktree[]): Set { - return new Set(worktrees.map(getWorktreeHostIdentity)) -} - -describe('matchWorkspaceBoardWorktrees', () => { - it('separates two same-id host rows', () => { - const local = worktree({ id: 'shared', branch: 'refs/heads/local-only' }) - const remote = worktree({ - id: local.id, - hostId: 'ssh:box', - branch: 'refs/heads/remote-only' - }) - - expect(match([local, remote], 'local-only')).toEqual(identities(local)) - expect(match([local, remote], 'remote-only')).toEqual(identities(remote)) - expect(match([local], 'local-only')).toEqual(identities(local)) - }) -}) diff --git a/src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx b/src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx deleted file mode 100644 index ac375059338..00000000000 --- a/src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx +++ /dev/null @@ -1,164 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { ReactNode } from 'react' -import { useAppStore } from '@/store' -import { getDefaultSettings } from '../../../../shared/constants' -import { - accountHost, - accountTransport -} from '@/runtime/provider-accounts/observations/provider-account-observation.test-fixture' -import { ClaudeSwitcherMenu } from './ClaudeSwitcherMenu' - -const mocks = vi.hoisted(() => ({ rpc: vi.fn() })) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: mocks.rpc -})) -vi.mock('@/lib/provider-accounts/claude-account-switch-sessions', () => ({ - handleRunningClaudeSessionsAfterSwitch: vi.fn() -})) -vi.mock('@/lib/windows-terminal-capabilities', () => ({ - useWindowsTerminalCapabilities: () => ({ wslDistros: [], isLoading: false }), - getWindowsTerminalCapabilityOwnerKey: () => 'local' -})) -vi.mock('./ProviderDetailsMenu', () => ({ - ProviderDetailsMenu: ({ children }: { children: ReactNode }) =>
{children}
-})) -vi.mock('@/components/ui/dropdown-menu', () => ({ - DropdownMenuLabel: ({ children }: { children: ReactNode }) =>
{children}
, - DropdownMenuSeparator: () => null, - DropdownMenuItem: ({ - children, - disabled, - onSelect - }: { - children: ReactNode - disabled?: boolean - onSelect: (event: { preventDefault: () => void }) => void - }) => ( -
{ - if (!disabled) { - onSelect({ preventDefault: () => {} }) - } - }} - > - {children} -
- ) -})) -const initial = useAppStore.getState() -afterEach(() => { - cleanup() - useAppStore.setState(initial, true) - vi.clearAllMocks() -}) -function deferred() { - let resolve!: (value: T) => void - let reject!: (error: Error) => void - const promise = new Promise((done, fail) => { - resolve = done - reject = fail - }) - return { promise, resolve, reject } -} -function replacementOwner(id: string | null) { - useAppStore.setState((state) => ({ - settings: { ...state.settings!, activeRuntimeEnvironmentId: id } - })) -} -function row(id: string) { - return screen.getByText(`${id}@example.com`).closest('[role="menuitem"]')! -} -async function expand() { - if (screen.queryByText('b@example.com')) { - return - } - fireEvent.click(screen.getAllByText('a@example.com')[0]) - await act(async () => {}) -} - -it.each([ - ['select', 'resolve'], - ['select', 'reject'], - ['sign-in', 'resolve'], - ['sign-in', 'reject'] -] as const)( - 'retires pending %s with its owner after late %s and admits a replacement action', - async (operation, settlement) => { - const local = accountHost(), - a = accountHost(), - b = accountHost() - const transport = accountTransport({ a, b }) - const pending = deferred() - const select = vi.fn(() => pending.promise) - const reauthenticate = vi.fn(() => pending.promise) - if (operation === 'sign-in') { - local.snapshot.claude.accounts[1].needsSignIn = true - } - Object.defineProperty(window, 'api', { - configurable: true, - value: { - ...window.api, - claudeAccounts: { - ...window.api.claudeAccounts, - list: async () => local.snapshot.claude, - select, - reauthenticate - }, - codexAccounts: { ...window.api.codexAccounts, list: async () => local.snapshot.codex } - } - }) - mocks.rpc.mockImplementation(async (target) => - target.environmentId === 'a' ? pending.promise : b.snapshot.claude - ) - useAppStore.setState({ - settings: { - ...getDefaultSettings('/test'), - claudeManagedAccounts: local.snapshot.claude.accounts.map((account) => ({ - ...account, - managedAuthPath: '/unused' - })), - activeClaudeManagedAccountId: 'a', - activeClaudeManagedAccountIdsByRuntime: { host: 'a', wsl: {} }, - activeRuntimeEnvironmentId: operation === 'sign-in' ? null : 'a' - }, - fetchSettings: vi.fn(async () => {}), - fetchInactiveClaudeAccountUsage: vi.fn(async () => {}) - }) - render() - await act(async () => {}) - await expand() - fireEvent.click(row('b')) - await act(async () => {}) - expect(operation === 'sign-in' ? reauthenticate : mocks.rpc).toHaveBeenCalledTimes(1) - expect(row('b').getAttribute('aria-disabled')).toBe('true') - await act(async () => replacementOwner('b')) - await expand() - // The old answer is deliberately different from the replacement owner's authoritative roster. - const late = { - ...a.snapshot.claude, - activeAccountId: 'b', - activeAccountIdsByRuntime: { host: 'b', wsl: {} } - } - await act(async () => { - if (settlement === 'resolve') { - pending.resolve(late) - } else { - pending.reject(new Error('Fixture operation failed')) - } - }) - expect(row('b').getAttribute('aria-disabled')).toBe('false') - fireEvent.click(row('b')) - await act(async () => {}) - expect(mocks.rpc).toHaveBeenLastCalledWith( - { kind: 'environment', environmentId: 'b' }, - 'accounts.selectClaude', - { accountId: 'b' }, - { timeoutMs: 30000 } - ) - expect(transport.streams.some((stream) => stream.host === 'b')).toBe(true) - } -) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-close-terminal.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-close-terminal.test.ts deleted file mode 100644 index 4ee8af6e867..00000000000 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-close-terminal.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -// @vitest-environment happy-dom -import { beforeEach, expect, it, vi } from 'vitest' -import type { RuntimeTerminalWait } from '../../../../shared/runtime-types' -import type { ExecutionHostId } from '../../../../shared/execution-host' -const mocks = vi.hoisted(() => ({ - call: vi.fn(), - close: vi.fn(), - state: { - tabsByWorktree: { workspace: [{ id: 'tab', createdAt: 1 }] }, - terminalLayoutsByTabId: { - tab: { - root: { - type: 'split', - first: { type: 'leaf', leafId: 'a' }, - second: { type: 'leaf', leafId: 'b' } - }, - ptyIdsByLeafId: { a: 'pty-a', b: 'pty-b' } - } - }, - ptyIdsByTabId: { tab: ['pty-a', 'pty-b'] }, - terminalPtyIncarnationsByPaneKey: { 'tab:a': 'inc-a', 'tab:b': 'inc-b' } - } -})) -vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state } })) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: mocks.call -})) -vi.mock('@/runtime/native-chat/session-ownership/structured-agent-session-owner', () => ({ - structuredAgentSessionTargetForHost: (host: string) => - host === 'local' ? { kind: 'local' } : { kind: 'environment', environmentId: 'paired' } -})) -vi.mock('../terminal/terminal-tab-actions', () => ({ closeTerminalTab: mocks.close })) -import { closeCliChatResumeTerminal } from './cli-chat-resume-close-terminal' -const source = { - tabId: 'tab', - workspaceId: 'workspace', - paneKey: 'tab:a', - agent: 'claude', - providerSessionId: 'conversation', - executionHostId: 'local' -} as const -const hooks = (closing = vi.fn()) => ({ prepared: vi.fn(), closing, refused: vi.fn() }) -function deferred() { - let resolve: (value: T) => void = () => {} - const promise = new Promise((done) => { - resolve = done - }) - return { resolve, promise } -} -beforeEach(() => { - vi.clearAllMocks() - mocks.state.terminalPtyIncarnationsByPaneKey['tab:a'] = 'inc-a' - mocks.call.mockImplementation(async (_target, method, params) => { - if (method === 'terminal.resolvePane') { - const leaf = params.paneKey.endsWith(':b') ? 'b' : 'a' - return { - terminal: { handle: `handle-${leaf}`, ptyId: `pty-${leaf}`, incarnationId: `inc-${leaf}` } - } - } - return { wait: { satisfied: true, status: 'exited', exitCode: 0 } } - }) - mocks.close.mockImplementation((_tab, options) => { - options.beforeClose() - }) -}) -it.each(['local', 'runtime:paired'])( - 'pins every split PTY before ordinary tab close on %s and waits for all exits', - async (executionHostId) => { - const exit = deferred<{ - wait: Pick - }>() - mocks.call.mockImplementation(async (_target, method, params) => { - if (method === 'terminal.resolvePane') { - const leaf = params.paneKey.endsWith(':b') ? 'b' : 'a' - return { - terminal: { handle: `handle-${leaf}`, ptyId: `pty-${leaf}`, incarnationId: `inc-${leaf}` } - } - } - return params.terminal === 'handle-b' - ? exit.promise - : { wait: { satisfied: true, status: 'exited', exitCode: 0 } } - }) - const closing = vi.fn(() => - expect(mocks.call.mock.calls.filter((call) => call[1] === 'terminal.wait')).toHaveLength(2) - ) - let finished = false - const closeHooks = hooks(closing) - const run = closeCliChatResumeTerminal( - { ...source, executionHostId }, - () => true, - closeHooks, - new AbortController().signal - ).then((value) => { - finished = true - return value - }) - await vi.waitFor(() => expect(closing).toHaveBeenCalledOnce()) - expect(finished).toBe(false) - expect(closeHooks.prepared).toHaveBeenCalledOnce() - // Only the split's other pane can ask about running work, and the chat keeps the worktree open. - expect(mocks.close).toHaveBeenCalledWith( - 'tab', - expect.objectContaining({ - consentedPtyId: 'pty-a', - preserveWorktreeSelection: true, - onCancel: expect.any(Function) - }) - ) - exit.resolve({ wait: { satisfied: true, status: 'exited', exitCode: 0 } }) - await expect(run).resolves.toBe(true) - } -) -it('leaves the tab and opens nothing when the ordinary close confirmation is cancelled', async () => { - mocks.close.mockImplementation((_tab, options) => options.onCancel()) - const closing = vi.fn() - await expect( - closeCliChatResumeTerminal(source, () => true, hooks(closing), new AbortController().signal) - ).resolves.toBe(false) - expect(closing).not.toHaveBeenCalled() - expect(mocks.call.mock.calls.filter((call) => call[1] === 'terminal.wait')).toHaveLength(0) -}) -it.each([ - { - satisfied: true, - status: 'exited', - exitCode: -1, - exitCause: { kind: 'unknown', reason: 'stop_unverified' } - }, - { satisfied: true, status: 'unknown', exitCode: null }, - new Error('timeout') -])('goes on once an exit the host could not prove settles: %j', async (wait) => { - mocks.call.mockImplementation(async (_target, method, params) => { - const leaf = params.paneKey?.endsWith(':b') ? 'b' : 'a' - return method === 'terminal.resolvePane' - ? { - terminal: { handle: `handle-${leaf}`, ptyId: `pty-${leaf}`, incarnationId: `inc-${leaf}` } - } - : wait instanceof Error - ? Promise.reject(wait) - : { wait } - }) - await expect( - closeCliChatResumeTerminal(source, () => true, hooks(), new AbortController().signal) - ).resolves.toBe(true) -}) -it('rechecks the source incarnation after an existing close dialog and says the close was dropped', async () => { - mocks.close.mockImplementation((_tab, options) => { - mocks.state.terminalPtyIncarnationsByPaneKey['tab:a'] = 'replacement' - expect(options.beforeClose()).toBe(false) - options.onCancel() - }) - const closeHooks = hooks() - await expect( - closeCliChatResumeTerminal(source, () => true, closeHooks, new AbortController().signal) - ).resolves.toBe(false) - expect(closeHooks.refused).toHaveBeenCalledOnce() - expect(closeHooks.closing).not.toHaveBeenCalled() - expect(mocks.call.mock.calls.filter((call) => call[1] === 'terminal.wait')).toHaveLength(0) -}) -it('reports a vetoed confirmed close to its run even after the run was retired', async () => { - const controller = new AbortController() - let reenter: (() => boolean) | undefined - mocks.close.mockImplementation((_tab, options) => { - reenter = options.beforeClose - }) - const closeHooks = hooks() - const run = closeCliChatResumeTerminal(source, () => true, closeHooks, controller.signal) - await vi.waitFor(() => expect(reenter).toBeDefined()) - controller.abort() - await expect(run).resolves.toBe(false) - expect(reenter?.()).toBe(false) - // The run, not this helper, knows whether a newer continuation owns the confirmation. - expect(closeHooks.refused).toHaveBeenCalledOnce() - expect(closeHooks.closing).not.toHaveBeenCalled() -}) diff --git a/src/renderer/src/components/tab-bar/cli-chat-resume-run-close.test.ts b/src/renderer/src/components/tab-bar/cli-chat-resume-run-close.test.ts deleted file mode 100644 index e38473b574a..00000000000 --- a/src/renderer/src/components/tab-bar/cli-chat-resume-run-close.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof' -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { CliChatResumeSource } from './cli-chat-resume-source' -import type * as FrameDrawnChatTabPlacementModule from '@/lib/frame-drawn-chat-tab-placement' -import type * as CloseTerminalModule from './cli-chat-resume-close-terminal' - -const mocks = vi.hoisted(() => { - const state: { source: CliChatResumeSource | null } = { source: null } - return { - ...state, - sourceCapability: vi.fn(), - closeCapability: vi.fn(), - capabilityState: vi.fn(), - closeTerminal: vi.fn(), - probe: vi.fn(), - createCapability: vi.fn(), - call: vi.fn(), - createSupport: vi.fn(), - toast: vi.fn(), - activate: vi.fn(async () => true), - frameDrawn: false - } -}) -vi.mock('./cli-chat-resume-close-terminal', async (importOriginal) => ({ - ...(await importOriginal()), - closeCliChatResumeTerminal: mocks.closeTerminal -})) -vi.mock('./cli-chat-resume-source', () => ({ resolveCliChatResumeSource: () => mocks.source })) -vi.mock('../terminal/pty-running-work-probe', () => ({ probePtyRunningWork: mocks.probe })) -vi.mock( - '../../runtime/native-chat/host-capabilities/structured-agent-session-host-support', - () => ({ - structuredAgentSessionHostSupports: mocks.closeCapability, - structuredAgentSessionHostCapabilityState: async (...args: unknown[]) => - (await mocks.capabilityState(...args)) ?? - ((await mocks.closeCapability(...args)) ? 'supported' : 'unsupported'), - supportsStructuredAgentSessionCliSource: mocks.sourceCapability, - supportsStructuredAgentSessionCreateMessage: mocks.createCapability - }) -) - -vi.mock('../../runtime/native-chat/requests/structured-agent-session-call', () => ({ - callStructuredAgentSession: (...args: unknown[]) => - args[1] === 'agentSession.createSupport' ? mocks.createSupport(args[2]) : mocks.call(...args) -})) -vi.mock('@/runtime/native-chat/tab-inventory/structured-session-tab-inventory', () => ({ - readStructuredSessionTabInventory: async () => { - throw new Error('Reply unavailable') - } -})) -vi.mock('@/lib/agent-session/launch/structured-agent-session-create-hydration', () => ({ - publishStructuredAgentSessionCreateHydration: vi.fn() -})) -vi.mock('sonner', () => ({ toast: { error: mocks.toast } })) -// A frame-drawn server workspace's create carries the tab's place, read as it is sent. -vi.mock('@/lib/frame-drawn-chat-tab-placement', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - withFrameDrawnChatTabPlacement: ( - intent: Parameters[0] - ) => - mocks.frameDrawn - ? { ...intent.params, tabPlacement: { groupId: 'g-1' } } - : actual.withFrameDrawnChatTabPlacement(intent) - } -}) -vi.mock('@/lib/activate-ai-vault-structured-session', () => ({ - activateAiVaultStructuredSession: mocks.activate -})) -// Switch-on, main opens the chat's tab and its frame draws it. -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => ({ - ...( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -})) -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (importOriginal) => ({ - ...(await importOriginal()), - runtimeEnvironmentSupportsCapability: async () => true -})) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) - -import { useAppStore } from '@/store' - -import { getStructuredAgentSessionLaunchLifecycle } from '@/lib/agent-session/launch/structured-agent-session-launch-registry' -import { startStructuredAgentLaunch } from '@/lib/agent-session/launch/structured-agent-session-launch' -import { resolveWebSessionVisibleTabId } from '@/runtime/web-session-tabs-sync/navigation/web-session-focus-intent' -import { - drawTabsFromMain, - type TabsDrawnFromMain -} from '@/store/slices/tabs/tabs-drawn-from-main.test-fixture' -import { runCliChatResume } from './cli-chat-resume-run' - -import { - SOURCE, - refuse, - resetCliChatResumeRun, - showAgentInSource, - tabs -} from './cli-chat-resume-run.test-fixture' - -const creates = () => mocks.call.mock.calls.filter(([, method]) => method === 'agentSession.create') - -let main: TabsDrawnFromMain | undefined -afterEach(() => { - vi.useRealTimers() - vi.unstubAllGlobals() - main?.close() - main = undefined -}) -beforeEach(async () => { - resetCliChatResumeRun(mocks) - mocks.createSupport.mockResolvedValue({ supported: true }) - main = await drawTabsFromMain(useAppStore) -}) - -describe('close terminal then continue on capable hosts', () => { - beforeEach(() => { - mocks.closeCapability.mockResolvedValue(true) - showAgentInSource() - }) - - it('leaves a tab the user picked while the chat waited on the close', async () => { - mocks.closeTerminal.mockImplementation(async (_source, _current, hooks) => { - useAppStore.getState().createUnifiedTab('wt-1', 'agent-session', { - id: 'picked', - entityId: 'picked-chat' - }) - expect(resolveWebSessionVisibleTabId(useAppStore.getState(), 'wt-1')).toBe('picked') - hooks.prepared() - hooks.closing() - mocks.source = null - return true - }) - await runCliChatResume(SOURCE) - await main?.settle() - expect(creates()).toHaveLength(1) - expect(resolveWebSessionVisibleTabId(useAppStore.getState(), 'wt-1')).toBe('picked') - }) - - it('starts the chat anew when the closed terminal never saved its conversation', async () => { - const answer = mocks.call.getMockImplementation() - mocks.call.mockImplementationOnce(async (_target, method) => { - expect(method).toBe('agentSession.create') - return { ok: false, refusal: refuse('transcriptNotFound') } - }) - await runCliChatResume(SOURCE) - await vi.waitFor(() => expect(creates()).toHaveLength(2)) - const [first, second] = creates().map(([, , params]) => params) - expect(first.resumeFrom?.providerSessionId).toBe(SOURCE.providerSessionId) - expect(second.resumeFrom).toBeUndefined() - expect(second.envelope.sessionId).toBe(first.envelope.sessionId) - mocks.call.mockImplementation(answer!) - await main?.settle() - expect(tabs().map((tab) => tab.entityId)).toEqual([first.envelope.sessionId]) - expect(mocks.toast).not.toHaveBeenCalled() - }) - - // Joining it would re-send an unconfirmed chat's create beside the still-running CLI. - it.each(['pending', 'visibility-unknown'])( - 'shows a %s chat already opening this conversation and keeps the terminal', - async (lifecycle) => { - // Its create never answers, or its reply is lost and the host can't be asked whether it exists. - const answer = mocks.call.getMockImplementation() - mocks.call.mockImplementation((...args: unknown[]) => - args[1] !== 'agentSession.create' - ? answer?.(...args) - : lifecycle === 'pending' - ? new Promise(() => undefined) - : Promise.reject(new Error('response lost')) - ) - const other = startStructuredAgentLaunch('wt-1', 'claude', { - requestId: 'other-resume', - resumeFrom: { providerSessionId: SOURCE.providerSessionId } - }) - await vi.waitFor(() => { - expect(creates().length).toBeGreaterThan(0) - expect(getStructuredAgentSessionLaunchLifecycle('wt-1', other.sessionId)).toBe(lifecycle) - }) - const sent = creates().length - await runCliChatResume(SOURCE, true) - await main?.settle() - expect(mocks.closeTerminal).not.toHaveBeenCalled() - expect(tabs().map((tab) => tab.entityId)).toEqual([other.sessionId]) - expect(creates()).toHaveLength(sent) - expect(mocks.toast).not.toHaveBeenCalled() - } - ) -}) diff --git a/src/renderer/src/components/tab-bar/tab-agent-launch-options.test.ts b/src/renderer/src/components/tab-bar/tab-agent-launch-options.test.ts deleted file mode 100644 index 39e79b0878b..00000000000 --- a/src/renderer/src/components/tab-bar/tab-agent-launch-options.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - buildTabAgentLaunchOptions, - buildTabAgentLaunchOptionsFromRows, - findMatchingTabAgentLaunchOptions -} from './tab-agent-launch-options' - -describe('tab agent launch options', () => { - it('ranks an exact alias above weaker prefix matches', () => { - const options = buildTabAgentLaunchOptions(['codebuff', 'codex', 'copilot'], { - codebuff: 'codex-tools' - }) - - // The weaker codex-tools prefix starts first, so exact codex must move ahead. - expect(findMatchingTabAgentLaunchOptions('codex', options)[0]?.agent).toBe('codex') - expect(findMatchingTabAgentLaunchOptions('co', options).map((o) => o.agent)).toEqual( - expect.arrayContaining(['codex', 'copilot', 'codebuff']) - ) - }) - - it('does not match on a mid-string substring that would hijack file results', () => { - const options = buildTabAgentLaunchOptions(['opencode', 'claude']) - - // Agent rows outrank files, so broad mid-string hits must not hijack the result list. - expect(findMatchingTabAgentLaunchOptions('ode', options)).toEqual([]) - }) -}) - -it('projects the same CLI label, unavailable reason and stable chat ID as static rows', () => { - const unavailable = buildTabAgentLaunchOptionsFromRows([ - { kind: 'chat-unavailable', agent: 'claude', reason: 'ssh' }, - { kind: 'cli', agent: 'claude' }, - { kind: 'cli', agent: 'codex', chat: true } - ]) - expect(unavailable).toMatchObject([ - { id: 'chat:claude', label: 'Claude', reason: 'No chat over SSH', disabled: true }, - { id: 'cli:claude', label: 'Claude (CLI)', disabled: false }, - { id: 'cli:codex', label: 'Codex (CLI)', disabled: false } - ]) - // Typing the agent's name and pressing Enter launches its CLI, not the disabled chat. - expect(findMatchingTabAgentLaunchOptions('claude', unavailable)[0]?.id).toBe('cli:claude') - expect( - findMatchingTabAgentLaunchOptions('codex', unavailable).map((option) => [ - option.id, - option.row?.kind - ]) - ).toEqual([['cli:codex', 'cli']]) -}) diff --git a/src/renderer/src/components/tab-group/workspace-tab-close-commands.frame-flush.test.ts b/src/renderer/src/components/tab-group/workspace-tab-close-commands.frame-flush.test.ts deleted file mode 100644 index d78ec3e2a31..00000000000 --- a/src/renderer/src/components/tab-group/workspace-tab-close-commands.frame-flush.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' - -const requestEditorFileClose = vi.hoisted(() => vi.fn<(fileId: string) => void>()) -vi.mock('../editor/autosave/editor-autosave', () => ({ requestEditorFileClose })) - -import { useAppStore } from '../../store' -import { makeOpenFile } from '../../store/slices/editor/types/open-file.test-fixture' -import { makeUnifiedTab } from '../../store/slices/tabs/tab-group.test-fixture' -import { registerEditorFrameFlush } from '../editor/save/flush/editor-pending-flush' -import { createWorkspaceTabCloseCommands } from './workspace-tab-close-commands' - -const worktreeId = 'wt' -const tabOf = (entityId: string) => - makeUnifiedTab({ id: 'tab', worktreeId, groupId: 'g', entityId, contentType: 'editor' }) -const drainMicrotasks = () => new Promise((resolve) => setImmediate(resolve)) - -let removeFrame = () => {} -afterEach(() => removeFrame()) - -// Why: a rename keeps the tab id but moves its entity while the frame is flushing. -it('closes the renamed file, prompting when it is dirty, after the frame flush', async () => { - let answer: (flushed: boolean) => void = () => {} - removeFrame = registerEditorFrameFlush('old', () => new Promise((resolve) => (answer = resolve))) - useAppStore.setState({ - openFiles: [makeOpenFile({ id: 'old', worktreeId })], - unifiedTabsByWorktree: { [worktreeId]: [tabOf('old')] } - }) - createWorkspaceTabCloseCommands({ worktreeId, groupTabs: [tabOf('old')] }).closeItem('tab') - - useAppStore.setState({ - openFiles: [makeOpenFile({ id: 'new', worktreeId, isDirty: true })], - unifiedTabsByWorktree: { [worktreeId]: [tabOf('new')] } - }) - answer(true) - await drainMicrotasks() - - expect(requestEditorFileClose).toHaveBeenCalledWith('new', { tabId: 'tab' }) - expect(useAppStore.getState().unifiedTabsByWorktree[worktreeId]).toHaveLength(1) -}) diff --git a/src/renderer/src/components/task-page/jira/Content.board-owner.test.tsx b/src/renderer/src/components/task-page/jira/Content.board-owner.test.tsx deleted file mode 100644 index 124f199d0bf..00000000000 --- a/src/renderer/src/components/task-page/jira/Content.board-owner.test.tsx +++ /dev/null @@ -1,123 +0,0 @@ -// @vitest-environment happy-dom - -import { useState, type ComponentProps } from 'react' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { TaskPageComposerActionsModel } from '../use-task-page-composer-actions' -import type { TaskPageJiraBoardView } from './task-page-jira-board-view' -import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' -import { defaultJiraListColumnIds, visibleJiraListColumns } from '../../jira-list-columns' -import { bumpProviderRuntimeSessionGeneration } from '@/runtime/hosts/observations/provider-runtime-context' -import { TaskPageJiraContent } from './Content' -import type * as I18n from '@/i18n/i18n' - -type BoardProps = ComponentProps -vi.mock('@/components/task-page/jira/task-page-jira-board-view', () => ({ - TaskPageJiraBoardView: ({ target, scopeKey }: BoardProps) => { - const [draft, setDraft] = useState('') - return ( -
- setDraft(event.target.value)} - /> - {JSON.stringify(target)} - {scopeKey} -
- ) - } -})) -vi.mock('@/components/JiraIssueWorkspace', () => ({ default: () => null })) -vi.mock('@/components/task-page/linear/Content', () => ({ TaskPageLinearContent: () => null })) -vi.mock('@/components/jira-list-columns-menu', () => ({ JiraListColumnsMenu: () => null })) -vi.mock('@/i18n/i18n', async (importOriginal) => ({ - ...(await importOriginal()), - translate: (_key: string, fallback: string) => fallback -})) - -afterEach(cleanup) - -const source: TaskSourceContext = { - kind: 'task-source', - provider: 'jira', - projectId: 'content-owner-project', - hostId: 'runtime:explicit-jira-owner' -} - -function model(sourceContext: TaskSourceContext | null): TaskPageComposerActionsModel { - const columns = defaultJiraListColumnIds() - const fixture = { - jiraStatus: { credentialError: null }, - jiraHasWorkspace: false, - getJiraIssueWorkspaces: () => [], - jiraStatusReady: true, - jiraConnected: true, - selectedJiraSiteId: 'site-a', - hideTaskSource: vi.fn(), - taskSource: 'jira', - closeTaskDetailPage: vi.fn(), - selectedJiraIssue: null, - jiraDetailSourceContext: sourceContext, - openJiraDetailPage: vi.fn(), - jiraIssues: [], - jiraLoading: false, - jiraError: null, - jiraErrorDetailsOpen: false, - setJiraErrorDetailsOpen: vi.fn(), - jiraJqlRejection: null, - jiraSearchInput: '', - jiraOrderBy: 'updated', - jiraOrderDirection: 'desc', - handleJiraSort: vi.fn(), - jiraColumnIds: columns, - jiraColumns: visibleJiraListColumns(columns), - toggleJiraColumn: vi.fn(), - displayedJiraIssues: [], - displayedJiraStatusOrder: null, - sortedJiraIssues: [], - setJiraConnectOpen: vi.fn(), - handleUseJiraItem: vi.fn(), - jiraViewMode: 'board', - setJiraViewMode: vi.fn(), - jiraCurrentSprint: true, - setJiraCurrentSprint: vi.fn(), - jiraTaskSourceContext: sourceContext, - jiraTaskSourceScopeKey: 'content-source-scope', - accountBackedTaskSourceHostId: 'runtime:account-jira-owner', - providerRuntimeContextKey: 'runtime:unrelated-ui-a#0', - setJiraRefreshNonce: vi.fn() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This presentation fixture supplies every field read by the Jira content branch. - return fixture as unknown as TaskPageComposerActionsModel -} - -it.each([ - { label: 'explicit', sourceContext: source, owner: 'explicit-jira-owner' }, - { label: 'default', sourceContext: null, owner: 'account-jira-owner' } -])( - 'keeps the $label Jira owner draft through unrelated focus and clears it for a new session', - ({ sourceContext, owner }) => { - const current = model(sourceContext) - const { rerender } = render() - expect(screen.getByTestId('board-owner').textContent).toBe( - JSON.stringify({ kind: 'environment', environmentId: owner }) - ) - const initialScope = screen.getByTestId('board-scope').textContent - fireEvent.change(screen.getByRole('textbox', { name: 'Pending board comment' }), { - target: { value: 'Keep this draft' } - }) - current.providerRuntimeContextKey = 'runtime:unrelated-ui-b#0' - rerender() - expect(screen.getByDisplayValue('Keep this draft')).toBeDefined() - expect(screen.getByTestId('board-scope').textContent).toBe(initialScope) - - bumpProviderRuntimeSessionGeneration() - rerender() - expect(screen.queryByDisplayValue('Keep this draft')).toBeNull() - expect(screen.getByTestId('board-scope').textContent).not.toBe(initialScope) - expect(screen.getByTestId('board-owner').textContent).toBe( - JSON.stringify({ kind: 'environment', environmentId: owner }) - ) - } -) diff --git a/src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts b/src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts deleted file mode 100644 index 67c4487edcb..00000000000 --- a/src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { JiraIssue } from '../../../../../shared/jira/jira-types' -import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context' -import { readLinkedJiraIssues } from './task-page-jira-linked-issues' -const source: TaskSourceContext = { - kind: 'task-source', - provider: 'jira', - projectId: 'app', - hostId: 'runtime:remote' -} -const issue: JiraIssue = { - id: '1', - key: 'APP-1', - title: 'Fix login', - siteId: 'a', - url: 'https://a.example/browse/APP-1', - project: { id: '1', key: 'APP', name: 'Application' }, - issueType: { id: '1', name: 'Bug' }, - status: { id: '1', name: 'Open', categoryKey: 'new', categoryName: 'Open' }, - labels: [], - createdAt: '', - updatedAt: '' -} -describe('Jira Has Workspace issue reads', () => { - it('keeps successful reads when another site fails and reports the failure', async () => { - const search = vi - .fn() - .mockResolvedValueOnce([issue]) - .mockRejectedValueOnce(new Error('Site unavailable')) - const result = await readLinkedJiraIssues( - [ - { key: 'APP-1', siteId: 'a' }, - { key: 'APP-2', siteId: 'b' } - ], - search, - source, - false - ) - expect(result.issues).toEqual([issue]) - expect(result.error).not.toBeNull() - }) - it('does not accept a same-key result from the wrong Jira site', async () => { - const search = vi.fn().mockResolvedValue([{ ...issue, siteId: 'other' }]) - const result = await readLinkedJiraIssues( - [{ key: 'APP-1', siteId: 'a' }], - search, - source, - false - ) - expect(result.issues).toEqual([]) - expect(result.error).not.toBeNull() - }) -}) diff --git a/src/renderer/src/components/task-page/linear/task-page-linear-creation-lifetime.test.tsx b/src/renderer/src/components/task-page/linear/task-page-linear-creation-lifetime.test.tsx deleted file mode 100644 index f2459b45568..00000000000 --- a/src/renderer/src/components/task-page/linear/task-page-linear-creation-lifetime.test.tsx +++ /dev/null @@ -1,187 +0,0 @@ -// @vitest-environment happy-dom -import { - reads, - task, - store, - source, - useRoutingFixture -} from './task-page-linear-refresh-test-fixtures' -import { reads as issueReadRegistry } from '@/store/slices/linear/linear-issue-read-lifecycle' -import { pendingLinearIssueWrites } from '@/store/slices/linear/linear-issue-publication' -import { useLinearIssueCreationForm } from './use-task-page-linear-creation-state' -import { useTaskPageLinearIssueCreation } from './use-task-page-linear-issue-creation' - -import { useTaskPageJiraCreationStatePrelude } from '../jira/use-task-page-jira-creation-state' - -import { useLinearIssueWorkspaceDetail } from '../../linear-issue-workspace-detail-state' -import { useAppStore } from '@/store' - -import { writeLinearIssue } from '@/lib/work-items/linear/linear-issue-write' -import { - getProviderRuntimeContextKey, - bumpProviderRuntimeSessionGeneration -} from '@/runtime/hosts/observations/provider-runtime-context' -import type { LinearIssue } from '../../../../../shared/linear/issue-types' -import { expect, it, vi } from 'vitest' -import { act, renderHook, waitFor } from '@testing-library/react' -import { deferred } from '../../../store/slices/linear/linear-slice-test-harness' - -function useCreateFixture( - context: ReturnType, - initial: LinearIssue | null = null, - initialTitle = 'Created', - initialOpen = true, - runtime = { current: 'runtime' } -) { - const draft = useAppStore.getState().newLinearIssueDraft - const noop = vi.fn() - const form = useLinearIssueCreationForm(runtime.current, { - open: initialOpen, - title: draft?.title ?? initialTitle, - body: draft?.body ?? (initialTitle ? 'Body' : '') - }) - const route = useRoutingFixture(context, initial) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture supplies the real consumer's exercised fields and actions; unrelated full-page/provider services are intentionally absent. - const creation = useTaskPageLinearIssueCreation({ - ...route, - settings: null, - providerRuntimeContextKey: runtime.current, - providerRuntimeContextKeyRef: runtime, - linearTaskSourceContext: context, - setLinearRefreshNonce: noop, - selectedLinearProject: null, - ...form, - newLinearIssueTargetTeam: { id: 'team-1', workspaceId: 'w' } - } as never) - return { - ...creation, - submitting: form.newLinearIssueSubmitting, - title: form.newLinearIssueTitle, - body: form.newLinearIssueBody, - open: form.newLinearIssueOpen - } -} - -it('create selects N before pending A settles, without waiting for N follow-up hydration', async () => { - const s = store(), - context = source('local') - s.setState({ recordFeatureInteraction: vi.fn(), jiraIssueCache: {}, jiraSearchCache: {} }) - const pending = deferred<{ ok: boolean }>(), - held = deferred() - const created = { - ...task('Created N'), - id: 'N', - identifier: 'ENG-2', - title: 'Created title', - priority: 2 - } - reads.create.mockResolvedValue({ ok: true, id: 'N', identifier: 'ENG-2' }) - reads.detail.mockImplementation((_context, id) => - id === 'N' && reads.detail.mock.calls.filter((call) => call[1] === 'N').length === 1 - ? Promise.resolve(created) - : held.promise - ) - const hook = renderHook(() => { - const creation = useCreateFixture(context, task()) - const detail = useLinearIssueWorkspaceDetail({ - issue: creation.selectedLinearIssue ?? task(), - providerSettings: context, - requestKey: creation.selectedLinearIssue?.id ?? 'A' - }) - return { ...creation, detail } - }) - let saving!: Promise<{ ok: boolean }> - act(() => { - saving = writeLinearIssue(task(), { priority: 4 }, context, () => pending.promise) - }) - await act(async () => { - await hook.result.current.handleCreateNewLinearIssue() - }) - await waitFor(() => expect(hook.result.current.selectedLinearIssue?.id).toBe('N')) - expect(hook.result.current.detail.displayed).toMatchObject({ - id: 'N', - title: 'Created title', - priority: 2, - workspaceId: 'w' - }) - await act(async () => { - pending.resolve({ ok: false }) - await saving - }) - expect(hook.result.current.detail.displayed).toMatchObject({ - id: 'N', - title: 'Created title', - priority: 2, - workspaceId: 'w' - }) - expect(hook.result.current.detail.editState.priority).toBe(2) - expect(hook.result.current.detail.issueLoading).toBe(true) - hook.unmount() - held.resolve(null) - await held.promise - expect(pendingLinearIssueWrites.size).toBe(0) - expect(issueReadRegistry.size).toBe(0) -}) - -it('actual runtime replacement and new create outlive old success and own finally without revival', async () => { - const s = store(), - context = source('local'), - runtime = { current: getProviderRuntimeContextKey(null) } - s.setState({ recordFeatureInteraction: vi.fn(), jiraIssueCache: {}, jiraSearchCache: {} }) - const old = deferred<{ ok: boolean; id: string; identifier: string }>(), - next = deferred<{ ok: boolean; id: string; identifier: string }>() - reads.create.mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise) - const hook = renderHook(() => { - const model = useCreateFixture(context, null, 'Old', true, runtime) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the actual runtime reset prelude uses these Linear fields; unrelated Jira/metadata services are inert. - useTaskPageJiraCreationStatePrelude({ - ...model, - setNewLinearIssueTeamId: vi.fn(), - setNewLinearIssueProjects: vi.fn(), - setNewLinearIssueProjectsLoading: vi.fn() - } as never) - return model - }) - let a!: Promise, b!: Promise - act(() => { - a = hook.result.current.handleCreateNewLinearIssue() - }) - act(() => { - bumpProviderRuntimeSessionGeneration() - runtime.current = getProviderRuntimeContextKey(null) - hook.rerender() - }) - expect(hook.result.current.submitting).toBe(false) - act(() => { - hook.result.current.setNewLinearIssueTitle('Replacement') - hook.result.current.setNewLinearIssueBody('New body') - hook.result.current.setNewLinearIssueOpen(true) - }) - act(() => { - b = hook.result.current.handleCreateNewLinearIssue() - }) - expect(hook.result.current.submitting).toBe(true) - await act(async () => { - old.resolve({ ok: true, id: 'Old', identifier: 'W-1' }) - await a - }) - expect(hook.result.current).toMatchObject({ - title: 'Replacement', - body: 'New body', - open: true, - submitting: true - }) - expect(reads.detail).not.toHaveBeenCalled() - await act(async () => { - next.resolve({ ok: false, id: 'New', identifier: 'W-2' }) - await b - }) - expect(hook.result.current.submitting).toBe(false) - act(() => hook.result.current.setNewLinearIssueOpen(false)) - expect(s.getState().newLinearIssueDraft).toEqual({ title: 'Replacement', body: 'New body' }) - hook.unmount() - expect(pendingLinearIssueWrites.size).toBe(0) - expect(issueReadRegistry.size).toBe(0) - act(() => s.getState().patchLinearIssue('Old', { priority: 4 }, { sourceContext: context })) - expect(reads.detail).not.toHaveBeenCalled() -}) diff --git a/src/renderer/src/components/task-page/task-page-cache-selectors.test.ts b/src/renderer/src/components/task-page/task-page-cache-selectors.test.ts index 8c944776823..4ab79151235 100644 --- a/src/renderer/src/components/task-page/task-page-cache-selectors.test.ts +++ b/src/renderer/src/components/task-page/task-page-cache-selectors.test.ts @@ -1,10 +1,7 @@ import { describe, expect, it } from 'vitest' import type { CacheEntry } from '@/store/github/cache/cache-model' import type { GitHubWorkItem } from '../../../../shared/github/work-item-types' -import { - reconcileTaskPagePagesAfterLandingRefresh, - reconcileTaskPagePagesWithWorkItemsCache -} from './task-page-cache-selectors' +import { reconcileTaskPagePagesWithWorkItemsCache } from './task-page-cache-selectors' function entry(data: T): CacheEntry { return { data, fetchedAt: 1 } @@ -28,18 +25,4 @@ describe('task page cache selectors', () => { expect(nextPages[0]?.map((item) => item.repoHostId)).toEqual(['local', 'ssh:builder']) expect(nextPages[0]?.[1]).toBe(remote) }) - - it('replaces GitHub landing refresh rows when membership changes', () => { - const first = workItem('issue-1', 'repo-1') - const second = workItem('issue-2', 'repo-1') - const third = workItem('issue-3', 'repo-1') - const older = workItem('issue-4', 'repo-1') - - const nextPages = reconcileTaskPagePagesAfterLandingRefresh( - [[first, second], [older]], - [third, first] - ) - - expect(nextPages).toEqual([[third, first]]) - }) }) diff --git a/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts b/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts deleted file mode 100644 index 7a42728f677..00000000000 --- a/src/renderer/src/components/terminal-pane/links/files/terminal-path-exists-cache.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - readTerminalPathExistence, - startTerminalPathExistsProbe, - writeTerminalPathExistence, - type TerminalPathExistsCache -} from './terminal-path-exists-cache' - -describe('terminal path-exists cache', () => { - it('keeps expired negatives as ordering guards for older in-flight probes', () => { - const cache: TerminalPathExistsCache = new Map() - const older = startTerminalPathExistsProbe(1000) - const newer = startTerminalPathExistsProbe(2000) - writeTerminalPathExistence(cache, 'k', false, newer) - - expect(readTerminalPathExistence(cache, 'k', 12_000)).toBeUndefined() - writeTerminalPathExistence(cache, 'k', true, older) - expect(cache.get('k')).toEqual({ exists: false, ...newer }) - - const latest = startTerminalPathExistsProbe(12_000) - writeTerminalPathExistence(cache, 'k', true, latest) - expect(readTerminalPathExistence(cache, 'k', 12_000)).toBe(true) - }) - - it('ignores an older probe result that lands after a newer one', () => { - const cache: TerminalPathExistsCache = new Map() - const older = startTerminalPathExistsProbe(1000) - const newer = startTerminalPathExistsProbe(2000) - writeTerminalPathExistence(cache, 'k', true, newer) - writeTerminalPathExistence(cache, 'k', false, older) - expect(cache.get('k')).toEqual({ exists: true, ...newer }) - const latest = startTerminalPathExistsProbe(3000) - writeTerminalPathExistence(cache, 'k', false, latest) - expect(cache.get('k')).toEqual({ exists: false, ...latest }) - }) - - it('orders overlapping probes that start in the same millisecond', () => { - const cache: TerminalPathExistsCache = new Map() - const older = startTerminalPathExistsProbe(1000) - const newer = startTerminalPathExistsProbe(1000) - writeTerminalPathExistence(cache, 'newer-first', false, newer) - writeTerminalPathExistence(cache, 'newer-first', true, older) - expect(cache.get('newer-first')).toEqual({ exists: false, ...newer }) - writeTerminalPathExistence(cache, 'older-first', false, older) - writeTerminalPathExistence(cache, 'older-first', true, newer) - expect(cache.get('older-first')).toEqual({ exists: true, ...newer }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts index 491bb2dd2ba..d464fa40703 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-main-side-effect-authority.spec.ts @@ -16,10 +16,7 @@ import { type PtyConnectionAgentTitleMocks, bindPaneAgentTitleMocks } from '../test-fixtures/pty-connection-test-deps' -import { - createInitialStoreState, - buildActiveRuntimeEnvironmentState -} from '../test-fixtures/pty-connection-test-store-fixtures' +import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures' import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' import { installTerminalTestGlobals, @@ -36,11 +33,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void { return buildPaneConnectionDeps(() => mockStoreState, overrides) } - // Why: activeRuntimeEnvironmentId exercises the remote-runtime path where the renderer still owns OSC 9999 status. - function enableActiveRuntimeEnvironment(environmentId = 'env-1'): void { - mockStoreState = buildActiveRuntimeEnvironmentState(mockStoreState, environmentId) - } - function notifyStoreSubscribers(): void { for (const listener of storeSubscribers.slice()) { listener(mockStoreState) @@ -86,101 +78,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void { } } - it('omits byte-parser callbacks from the local transport options', async () => { - enableMainAuthority() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks) - ) - - expect(createdTransportOptions[0]).toBeDefined() - for (const callback of SIDE_EFFECT_PARSER_CALLBACKS) { - expect(createdTransportOptions[0]?.[callback]).toBeUndefined() - } - // Lifecycle callbacks stay on the transport; only side-effect parsing moves to the fact consumer. - expect(createdTransportOptions[0]?.onPtySpawn).toBeTypeOf('function') - expect(createdTransportOptions[0]?.onPtyExit).toBeTypeOf('function') - }) - - it('keeps byte-parser callbacks on remote-runtime transports', async () => { - enableMainAuthority() - enableActiveRuntimeEnvironment() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = - await vi.importMock('@/lib/agent-status') - const { createRemoteRuntimePtyTransport } = - await import('../../pty-transport/remote-runtime/remote-runtime-pty-transport') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks2) - ) - - expect(createRemoteRuntimePtyTransport).toHaveBeenCalledWith('env-1', expect.any(Object)) - for (const callback of SIDE_EFFECT_PARSER_CALLBACKS) { - expect(createdTransportOptions[0]?.[callback]).toBeTypeOf('function') - } - }) - - it('consumes pty:sideEffect facts with the live-path policy after spawn', async () => { - enableMainAuthority() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks3 = - await vi.importMock('@/lib/agent-status') - const handler = - await import('../../pty-transport/output/terminal-side-effect-facts-handler') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - vi.useFakeTimers() - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks3) - ) - - const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void - onPtySpawn('pty-fact-1') - - handler._dispatchTerminalSideEffectBatchForTest({ - ptyId: 'pty-fact-1', - seq: 10, - facts: [ - { kind: 'title', normalizedTitle: 'Codex working', rawTitle: 'Codex working' }, - { kind: 'bell' } - ] - }) - - expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Codex working') - expect(deps.markTerminalBell).toHaveBeenCalledTimes(1) - expect(deps.markTerminalBell).toHaveBeenCalledWith({ - worktreeId: 'wt-1', - tabId: 'tab-1', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - vi.advanceTimersByTime(250) - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'terminal-bell', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - }) - it('stops consuming facts after the pane binding is disposed', async () => { enableMainAuthority() const { connectPanePty } = await import('../connect-pane-pty') @@ -210,49 +107,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void { expect(deps.markTerminalBell).not.toHaveBeenCalled() }) - it('schedules the completion notification for genuine working→idle facts', async () => { - enableMainAuthority() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks5 = - await vi.importMock('@/lib/agent-status') - const handler = - await import('../../pty-transport/output/terminal-side-effect-facts-handler') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - vi.useFakeTimers() - - const deps = createDeps() - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks5) - ) - const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void - onPtySpawn('pty-fact-genuine') - - handler._dispatchTerminalSideEffectBatchForTest({ - ptyId: 'pty-fact-genuine', - seq: 1, - facts: [ - { kind: 'title', normalizedTitle: '⠋ Codex working', rawTitle: '⠋ Codex working' }, - { kind: 'agent-working' } - ] - }) - handler._dispatchTerminalSideEffectBatchForTest({ - ptyId: 'pty-fact-genuine', - seq: 2, - facts: [ - { kind: 'title', normalizedTitle: '* Codex done', rawTitle: '* Codex done' }, - { kind: 'agent-idle', title: '* Codex done' } - ] - }) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ source: 'agent-task-complete' }) - ) - }) - it('clears state without completion attention for stale-derived facts', async () => { enableMainAuthority() const { connectPanePty } = await import('../connect-pane-pty') @@ -306,82 +160,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void { expect(deps.markTerminalBell).not.toHaveBeenCalled() }) - it('drops the agent status from a command-finished fact like the byte path did', async () => { - enableMainAuthority() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks7 = - await vi.importMock('@/lib/agent-status') - const handler = - await import('../../pty-transport/output/terminal-side-effect-facts-handler') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - const paneKey = makePaneKey('tab-1', LEAF_1) - mockStoreState.agentStatusByPaneKey = { - [paneKey]: { - paneKey, - state: 'done', - prompt: 'hi', - updatedAt: 1000, - stateStartedAt: 1000, - agentType: 'codex', - stateHistory: [] - } - } - - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks7) - ) - const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void - onPtySpawn('pty-fact-133') - - handler._dispatchTerminalSideEffectBatchForTest({ - ptyId: 'pty-fact-133', - seq: 1, - facts: [{ kind: 'command-finished', exitCode: 130 }] - }) - - expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey) - expect(mockStoreState.removeAgentStatus).not.toHaveBeenCalled() - }) - - it('routes pr-link facts to the worktree PR observer', async () => { - enableMainAuthority() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks8 = - await vi.importMock('@/lib/agent-status') - const handler = - await import('../../pty-transport/output/terminal-side-effect-facts-handler') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks8) - ) - const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void - onPtySpawn('pty-fact-pr') - - const link = { - url: 'https://github.com/acme/orca/pull/42', - slug: { owner: 'acme', repo: 'orca' }, - number: 42 - } - handler._dispatchTerminalSideEffectBatchForTest({ - ptyId: 'pty-fact-pr', - seq: 1, - facts: [{ kind: 'pr-link', link }] - }) - - expect(mockStoreState.observeTerminalGitHubPullRequestLink).toHaveBeenCalledWith( - 'wt-1', - link, - expect.objectContaining({ tabId: 'tab-1', ptyId: 'tab-pty' }) - ) - }) - it('does not byte-scan PR links or OSC 133 — facts are the only consumer', async () => { enableMainAuthority() const { connectPanePty } = await import('../connect-pane-pty') @@ -424,53 +202,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void { expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled() }) - it('seeds and settles Command Code status from command-code facts', async () => { - enableMainAuthority() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks10 = - await vi.importMock('@/lib/agent-status') - const handler = - await import('../../pty-transport/output/terminal-side-effect-facts-handler') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - vi.useFakeTimers() - const paneKey = makePaneKey('tab-1', LEAF_1) - - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks10) - ) - const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void - onPtySpawn('pty-fact-cc') - - handler._dispatchTerminalSideEffectBatchForTest({ - ptyId: 'pty-fact-cc', - seq: 1, - facts: [{ kind: 'command-code-working', prompt: 'say hi' }] - }) - expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ - state: 'working', - prompt: 'say hi', - agentType: 'command-code' - }) - - // Done facts are hints; pane policy owns settling so it can consult the live row before completion. - handler._dispatchTerminalSideEffectBatchForTest({ - ptyId: 'pty-fact-cc', - seq: 2, - facts: [{ kind: 'command-code-done', prompt: 'say hi' }] - }) - vi.advanceTimersByTime(1499) - expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ state: 'working' }) - vi.advanceTimersByTime(1) - expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ - state: 'done', - prompt: 'say hi', - agentType: 'command-code' - }) - }) - it('rejects Command Code facts when Claude owns the pane', async () => { enableMainAuthority() const { connectPanePty } = await import('../connect-pane-pty') @@ -614,38 +345,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void { }) }) - it('does not byte-scan Command Code output — facts are the only consumer', async () => { - enableMainAuthority() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks14 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-authority-cc-bytes' - } - ) - transportFactoryQueue.push(transport) - - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks( - createDeps({ startup: { command: 'command-code --trust' } }) as never, - agentTitleMocks14 - ) - ) - await flushAsyncTicks() - expect(capturedDataCallback.current).not.toBeNull() - - capturedDataCallback.current?.('# Command Code v0.27.2\r\n') - capturedDataCallback.current?.('❯ Fix the spinner\r\n\x1b[35m✻ Thinking...\x1b[0m') - - expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled() - }) - it('honors the persisted kill switch for panes bound before settings hydrate', async () => { // Pre-hydration: settings not loaded but kill switch persisted off — pane registers byte parsers, not a fact consumer. mockStoreState.settings = null diff --git a/src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts deleted file mode 100644 index 3de96233b40..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-bell-query-reply-and-stale-input.spec.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' -import { - LEAF_1, - createMockTransport, - createPane, - createManager, - type MockTransport -} from '../test-fixtures/pty-connection-test-pane-fixtures' -import { - buildPaneConnectionDeps, - type PtyConnectionAgentTitleMocks, - bindPaneAgentTitleMocks -} from '../test-fixtures/pty-connection-test-deps' -import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures' -import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' -import { - installTerminalTestGlobals, - restoreTerminalTestGlobals -} from '../test-fixtures/pty-connection-test-environment' - -export function registerPtyConnectionBellQueryReplyAndStaleInputTests(): void { - let mockStoreState: StoreState - let transportFactoryQueue: MockTransport[] = [] - let createdTransportOptions: Record[] = [] - let storeSubscribers: ((state: StoreState) => void)[] = [] - - function createDeps(overrides: Record = {}) { - return buildPaneConnectionDeps(() => mockStoreState, overrides) - } - describe('connectPanePty', () => { - beforeEach(async () => { - vi.clearAllMocks() - transportFactoryQueue = [] - createdTransportOptions = [] - storeSubscribers = [] - mockStoreState = createInitialStoreState(() => mockStoreState) - bindPtyConnectionTestMocks({ - getState: () => mockStoreState, - getTransportQueue: () => transportFactoryQueue, - getTransportOptions: () => createdTransportOptions, - getStoreSubscribers: () => storeSubscribers, - setStoreSubscribers: (subscribers) => { - storeSubscribers = subscribers - } - }) - await installTerminalTestGlobals() - }) - - afterEach(async () => { - await restoreTerminalTestGlobals() - }) - - it('forwards raw onData after a bell as a query reply', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks7 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - const pane = createPane(1) - let onDataHandler: ((data: string) => void) | null = null - pane.terminal.onData = vi.fn(((handler: (data: string) => void) => { - onDataHandler = handler - return { dispose: vi.fn() } - }) as typeof pane.terminal.onData) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks7) - ) - - const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined - if (!bellHandler || !onDataHandler) { - throw new Error('expected bell and onData handlers to be registered') - } - - bellHandler() - ;(onDataHandler as (data: string) => void)('a') - - expect(deps.markTerminalBell).toHaveBeenCalledWith({ - worktreeId: 'wt-1', - - tabId: 'tab-1', - - paneKey: makePaneKey('tab-1', LEAF_1) - }) - expect(transport.sendInput).toHaveBeenCalledWith('a', 'query-reply') - }) - - // Why: on a stale-codex pane (pending account-switch restart), production blocks sendInput. - it('blocks onData on a stale codex pane', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks8 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex-stale') - transportFactoryQueue.push(transport) - // isCodexPaneStale reads codexRestartNoticeByPtyId; seed a restart notice to trigger the stale branch. - mockStoreState = { - ...mockStoreState, - tabsByWorktree: { - 'wt-1': [{ id: 'tab-1', ptyId: 'pty-codex-stale' }] - }, - ptyIdsByTabId: { - 'tab-1': ['pty-codex-stale'] - }, - codexRestartNoticeByPtyId: { - 'pty-codex-stale': { previousAccountLabel: 'A', nextAccountLabel: 'B' } - } - } - - const pane = createPane(1) - let onDataHandler: ((data: string) => void) | null = null - pane.terminal.onData = vi.fn(((handler: (data: string) => void) => { - onDataHandler = handler - return { dispose: vi.fn() } - }) as typeof pane.terminal.onData) - - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks8) - ) - - if (!onDataHandler) { - throw new Error('expected onData handler to be registered') - } - ;(onDataHandler as (data: string) => void)('a') - - // Stale-codex input is also blocked from reaching the transport. - expect(transport.sendInput).not.toHaveBeenCalled() - }) - }) -} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-command-finished-interrupt-arbitration.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-command-finished-interrupt-arbitration.spec.ts index 95d12b02a70..eee12960498 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-command-finished-interrupt-arbitration.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/input/pty-connection-command-finished-interrupt-arbitration.spec.ts @@ -165,69 +165,5 @@ export function registerPtyConnectionCommandFinishedInterruptArbitrationTests(): } } ) - - it('drops the command-finished status when pending interrupt inference is rejected', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks15 = - await vi.importMock('@/lib/agent-status') - - vi.mocked(window.api.agentStatus.inferInterrupt).mockResolvedValue(false) - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - const transport = createMockTransport() - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return { id: 'tab-pty' } - } - ) - transportFactoryQueue.push(transport) - vi.useFakeTimers() - vi.setSystemTime(1_100) - const paneKey = makePaneKey('tab-1', LEAF_1) - mockStoreState = { - ...mockStoreState, - agentStatusByPaneKey: { - [paneKey]: { - paneKey, - state: 'working', - prompt: 'stop quickly', - updatedAt: 1_000, - stateStartedAt: 900, - agentType: 'custom-agent', - terminalTitle: 'Codex', - stateHistory: [] - } - } - } - const terminalTarget = createKeyboardEventTarget() - const pane = createPane(1) - ;(pane.terminal as { element?: unknown }).element = terminalTarget.target - let onDataHandler: ((data: string) => void) | null = null - pane.terminal.onData = vi.fn(((handler: (data: string) => void) => { - onDataHandler = handler - return { dispose: vi.fn() } - }) as typeof pane.terminal.onData) - - connectPanePty( - ...mockPanePtyArgs( - pane, - createManager(1), - bindPaneAgentTitleMocks(createDeps(), agentTitleMocks15) - ) - ) - vi.advanceTimersByTime(1_000) - await flushAsyncTicks() - if (!onDataHandler) { - throw new Error('expected onData handler to be registered') - } - terminalTarget.dispatch(keyEvent({ key: 'c', ctrlKey: true })) - ;(onDataHandler as unknown as (data: string) => void)('\x03') - - capturedDataCallback.current?.('\x1b]133;D;130\x07thebr ~/repo $ ') - await flushAsyncTicks() - - expect(window.api.agentStatus.inferInterrupt).toHaveBeenCalled() - expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey) - }) }) } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts index 85b68256634..079130b0947 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts @@ -125,33 +125,6 @@ export function registerPtyConnectionNotificationSettingsGatingTests(): void { ) }) - it('shares one raw store subscriber for agent-complete notification settings across panes', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks4 = - await vi.importMock('@/lib/agent-status') - transportFactoryQueue.push(createMockTransport('pty-1'), createMockTransport('pty-2')) - - vi.useFakeTimers() - const firstBinding = connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks4) - ) - const secondBinding = connectPanePty( - createPane(2) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks4) - ) - await flushAsyncTicks() - - expect(storeSubscribers).toHaveLength(1) - - firstBinding.dispose() - expect(storeSubscribers).toHaveLength(1) - secondBinding.dispose() - expect(storeSubscribers).toHaveLength(0) - }) - it('keeps an in-flight generic completion when desktop completion banners are enabled', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks6 = diff --git a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts index aa5980cba17..09c14093eaf 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts @@ -18,10 +18,7 @@ import { type PtyConnectionAgentTitleMocks, bindPaneAgentTitleMocks } from '../test-fixtures/pty-connection-test-deps' -import { - createInitialStoreState, - buildActiveRuntimeEnvironmentState -} from '../test-fixtures/pty-connection-test-store-fixtures' +import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures' import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' import { installTerminalTestGlobals, @@ -39,11 +36,6 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { return buildPaneConnectionDeps(() => mockStoreState, overrides) } - // Why: activeRuntimeEnvironmentId exercises the remote-runtime path where the renderer still owns OSC 9999 status. - function enableActiveRuntimeEnvironment(environmentId = 'env-1'): void { - mockStoreState = buildActiveRuntimeEnvironmentState(mockStoreState, environmentId) - } - describe('connectPanePty', () => { beforeEach(async () => { vi.clearAllMocks() @@ -67,50 +59,6 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { await restoreTerminalTestGlobals() }) - it('dispatches agent-task-complete for generic Codex spinner titles after process identity is confirmed', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex') - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - const api = ( - globalThis as unknown as { - window: { api: { pty: { getForegroundProcess: ReturnType } } } - } - ).window.api - api.pty.getForegroundProcess.mockResolvedValue('codex') - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks)) - ) - - const titleHandler = createdTransportOptions[0]?.onTitleChange as - | ((title: string, rawTitle: string) => void) - | undefined - if (!titleHandler) { - throw new Error('Expected onTitleChange to be registered') - } - - titleHandler('⠋ experimental-agent-observability', '⠋ experimental-agent-observability') - titleHandler('experimental-agent-observability', 'experimental-agent-observability') - await flushAsyncTicks() - - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - - expect(deps.dispatchNotification).toHaveBeenCalledWith({ - source: 'agent-task-complete', - terminalTitle: 'experimental-agent-observability', - ptyId: 'tab-pty', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - expect(window.api.pty.inspectProcess).toHaveBeenCalledWith('pty-codex') - }) - it('does not dispatch generic spinner completions when process inspection finds no agent', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks2 = @@ -151,89 +99,6 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { ) }) - it('normalizes Pi-compatible remote titles to authoritative OMP launch identity', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks5 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-omp') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - mockStoreState.tabsByWorktree = { - 'wt-1': [{ id: 'tab-1', ptyId: 'tab-pty', launchAgent: 'omp' }] - } - mockStoreState.runtimePaneTitlesByTabId = { 'tab-1': { 1: '\u280b Pi' } } - - const pane = createPane(1) - const manager = createManager(1) - manager.getActivePane.mockReturnValue({ id: 1 }) - const deps = createDeps() - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks5)) - ) - - const titleHandler = createdTransportOptions[0]?.onTitleChange as - | ((title: string, rawTitle: string) => void) - | undefined - if (!titleHandler) { - throw new Error('Expected onTitleChange to be registered') - } - titleHandler('\u280b Pi', '\u280b Pi') - expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, '\u280b OMP') - expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', '\u280b OMP') - titleHandler('π: tmp', 'π: tmp') - expect(deps.setRuntimePaneTitle).toHaveBeenLastCalledWith('tab-1', 1, 'OMP: tmp') - expect(deps.updateTabTitle).toHaveBeenLastCalledWith('tab-1', 'OMP: tmp') - - const statusHandler = createdTransportOptions[0]?.onAgentStatus as - | ((payload: { state: 'working'; prompt: string; agentType: 'pi' }) => void) - | undefined - if (!statusHandler) { - throw new Error('Expected onAgentStatus to be registered') - } - - statusHandler({ - state: 'working', - prompt: 'fix the remote title', - agentType: 'pi' - }) - - expect(mockStoreState.setAgentStatus).toHaveBeenCalledWith( - makePaneKey('tab-1', LEAF_1), - { - state: 'working', - prompt: 'fix the remote title', - agentType: 'omp', - observation: expect.objectContaining({ origin: 'osc', kind: 'snapshot' }) - }, - '\u280b OMP', - undefined, - { connectionId: null } - ) - - mockStoreState.tabsByWorktree = { - 'wt-1': [{ id: 'tab-1', ptyId: 'tab-pty' }] - } - statusHandler({ - state: 'working', - prompt: 'keep the remote title', - agentType: 'pi' - }) - - expect(mockStoreState.setAgentStatus).toHaveBeenLastCalledWith( - makePaneKey('tab-1', LEAF_1), - { - state: 'working', - prompt: 'keep the remote title', - agentType: 'omp', - observation: expect.objectContaining({ origin: 'osc', kind: 'snapshot' }) - }, - '\u280b OMP', - undefined, - { connectionId: null } - ) - }) - it('queues the idle cursor reset behind hidden agent output', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks8 = diff --git a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts index 0f56921a577..abad8333a68 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts @@ -1,7 +1,6 @@ import { describe } from 'vitest' import { registerPtyConnectionCommandFinishedCleanupTests } from '../agent-identity/pty-connection-command-finished-cleanup.spec' import { registerPtyConnectionCommandFinishedInterruptArbitrationTests } from '../input/pty-connection-command-finished-interrupt-arbitration.spec' -import { registerPtyConnectionBellQueryReplyAndStaleInputTests } from '../input/pty-connection-bell-query-reply-and-stale-input.spec' import { registerPtyConnectionHookCompletionSideEffectsTests } from '../notifications/pty-connection-hook-completion-side-effects.spec' import { registerPtyConnectionMainSideEffectAuthorityTests } from '../emulation/pty-connection-main-side-effect-authority.spec' import { registerPtyConnectionNotificationSettingsGatingTests } from '../notifications/pty-connection-notification-settings-gating.spec' @@ -11,9 +10,6 @@ describe('pty-connection-command-finished-cleanup', () => { registerPtyConnectionCommandFinishedCleanupTests() registerPtyConnectionCommandFinishedInterruptArbitrationTests() }) -describe('pty-connection-hook-completion-bell-arbitration', () => { - registerPtyConnectionBellQueryReplyAndStaleInputTests() -}) describe( 'pty-connection-hook-completion-side-effects', registerPtyConnectionHookCompletionSideEffectsTests diff --git a/src/renderer/src/hooks/ipc-events/ssh-managed-server-state-effects.test.ts b/src/renderer/src/hooks/ipc-events/ssh-managed-server-state-effects.test.ts deleted file mode 100644 index 6f01bdc3ab9..00000000000 --- a/src/renderer/src/hooks/ipc-events/ssh-managed-server-state-effects.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - toast: Object.assign(vi.fn(), { - error: vi.fn(), - success: vi.fn(), - loading: vi.fn(() => 'progress'), - dismiss: vi.fn() - }), - fetchReposForAllHosts: vi.fn(async () => undefined), - remountTerminalTabForRecovery: vi.fn() -})) -vi.mock('sonner', () => ({ toast: mocks.toast })) -vi.mock('../../store', () => ({ - useAppStore: { - getState: () => ({ - fetchReposForAllHosts: mocks.fetchReposForAllHosts, - remountTerminalTabForRecovery: mocks.remountTerminalTabForRecovery, - sshTargetLabels: new Map([['ssh-1', 'Box']]), - tabsByWorktree: {}, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {} - }) - } -})) - -vi.mock( - '../../components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-panes', - () => ({ - legacyRelayBridgedTabIds: (targetId: string) => (targetId === 'ssh-1' ? ['tab-1', 'tab-2'] : []) - }) -) - -beforeEach(() => { - vi.clearAllMocks() -}) -afterEach(() => { - Reflect.deleteProperty(window, 'api') -}) - -describe('a host kept connected for the relay bridge', () => { - it('never loads the bridge panes module, which subscribes on load, just by being imported', async () => { - vi.resetModules() - vi.doUnmock( - '../../components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-panes' - ) - const listPanes = vi.fn(() => undefined) - Object.assign(window, { api: { ssh: {}, legacyRelayBridge: { listPanes, onPanes: vi.fn() } } }) - await import('./ssh-managed-server-state-effects') - expect(listPanes).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/hooks/ipc-events/wsl-host-ipc-bridge-capability.test.ts b/src/renderer/src/hooks/ipc-events/wsl-host-ipc-bridge-capability.test.ts deleted file mode 100644 index c557aaf7287..00000000000 --- a/src/renderer/src/hooks/ipc-events/wsl-host-ipc-bridge-capability.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import type { WslHostCapability } from '../../../../shared/wsl-host-types' -import { seedStore } from '../../store/testing/app-store-test-fixture' - -vi.mock('../../store', async () => { - const { createTestStore } = await import('../../store/testing/app-store-test-fixture') - return { useAppStore: createTestStore() } -}) - -const { useAppStore } = await import('../../store') -const { registerWslHostIpcBridge } = await import('./wsl-host-ipc-bridge') -const { readWslHostOfferGate, wslHostOfferFor } = - await import('../../components/sidebar/wsl-host-offer') - -let pushCapability: (capability: WslHostCapability) => void = () => {} -const api = { - onStatusChanged: vi.fn(() => () => {}), - getStatuses: vi.fn(async () => []), - getCapability: vi.fn(async () => ({ serverFiles: true, acceptsNewWork: true })), - onCapabilityChanged: vi.fn((callback: (capability: WslHostCapability) => void) => { - pushCapability = callback - return () => {} - }) -} - -beforeEach(() => { - vi.clearAllMocks() - Object.assign(globalThis, { window: { api: { runtimeEnvironments: { wslHosts: api } } } }) - seedStore(useAppStore, { - settings: { ...getDefaultSettings('/tmp'), experimentalWslHosts: false } - }) -}) - -describe('WSL host capability pushed mid-run', () => { - it('hides the in-context offer as soon as main stops new work, without a relaunch', async () => { - const unsubs: (() => void)[] = [] - registerWslHostIpcBridge(unsubs) - await vi.waitFor(() => expect(useAppStore.getState().wslHostsAcceptNewWork).toBe(true)) - const uncPath = '\\\\wsl.localhost\\Ubuntu\\home\\me\\app' - expect(wslHostOfferFor(uncPath, readWslHostOfferGate(useAppStore.getState()))).toBe('Ubuntu') - - pushCapability({ serverFiles: true, acceptsNewWork: false }) - - expect(useAppStore.getState().wslHostsAcceptNewWork).toBe(false) - expect(wslHostOfferFor(uncPath, readWslHostOfferGate(useAppStore.getState()))).toBeNull() - unsubs.forEach((unsub) => unsub()) - }) -}) diff --git a/src/renderer/src/hooks/shortcut-label-cache.test.tsx b/src/renderer/src/hooks/shortcut-label-cache.test.tsx index f273005acc7..50c6adb79eb 100644 --- a/src/renderer/src/hooks/shortcut-label-cache.test.tsx +++ b/src/renderer/src/hooks/shortcut-label-cache.test.tsx @@ -1,46 +1,17 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, render, screen } from '@testing-library/react' -import type * as KeybindingsModule from '../../../shared/keybindings' import type { KeybindingOverrides } from '../../../shared/keybindings' -const counters = vi.hoisted(() => ({ effective: 0, formatList: 0, formatBinding: 0 })) const platformRef = vi.hoisted(() => ({ current: 'darwin' as NodeJS.Platform })) vi.mock('../lib/shortcut-platform', () => ({ getShortcutPlatform: () => platformRef.current })) -vi.mock('../../../shared/keybindings', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - getEffectiveKeybindingsForAction: ( - ...args: Parameters - ) => { - counters.effective++ - return actual.getEffectiveKeybindingsForAction(...args) - }, - formatKeybindingList: (...args: Parameters) => { - counters.formatList++ - return actual.formatKeybindingList(...args) - }, - formatKeybinding: (...args: Parameters) => { - counters.formatBinding++ - return actual.formatKeybinding(...args) - } - } -}) - const { formatShortcutLabel, useShortcutLabel } = await import('./useShortcutLabel') const { useAppStore } = await import('@/store') -function resetCounters(): void { - counters.effective = 0 - counters.formatList = 0 - counters.formatBinding = 0 -} - // A fresh overrides object per test keeps each case on its own cache entry, exactly as a real edit does. function overridesFor(binding: string): KeybindingOverrides { return { 'tab.close': [binding] } @@ -49,7 +20,6 @@ function overridesFor(binding: string): KeybindingOverrides { describe('shortcut label memoization', () => { beforeEach(() => { platformRef.current = 'darwin' - resetCounters() }) it('keys the cache by platform so Mac and Windows glyphs never cross', () => { @@ -69,7 +39,6 @@ function CloseLabel(): React.JSX.Element { describe('useShortcutLabel', () => { beforeEach(() => { platformRef.current = 'darwin' - resetCounters() }) afterEach(() => { @@ -77,19 +46,6 @@ describe('useShortcutLabel', () => { useAppStore.setState({ keybindings: {} }) }) - it('does not recompute the label on re-render', () => { - useAppStore.setState({ keybindings: overridesFor('Mod+Shift+K') }) - const { rerender } = render() - expect(screen.getByTestId('close-label').textContent).toBe('⌘⇧K') - resetCounters() - for (let index = 0; index < 25; index++) { - rerender() - } - expect(screen.getByTestId('close-label').textContent).toBe('⌘⇧K') - expect(counters.effective).toBe(0) - expect(counters.formatList).toBe(0) - }) - it('shows an edited keybinding immediately, with no stale-cache window', () => { useAppStore.setState({ keybindings: overridesFor('Mod+Shift+K') }) render() diff --git a/src/renderer/src/i18n/I18nProvider.test.tsx b/src/renderer/src/i18n/I18nProvider.test.tsx index 8e8b3f9ee8d..638b3d6aa44 100644 --- a/src/renderer/src/i18n/I18nProvider.test.tsx +++ b/src/renderer/src/i18n/I18nProvider.test.tsx @@ -16,7 +16,6 @@ import * as rendererI18n from './i18n' import { useLanguageReadiness } from './language-readiness' import * as languageReadiness from './language-readiness' import { usePluginLanguagePackStore } from '../store/plugins/localization/plugin-language-packs' -import { pluginLanguageResourceId } from '../../../shared/plugins/artifacts/plugin-language-pack-artifact' import { I18nProvider } from './I18nProvider' // Wait for async settings before selecting the OS locale, or an in-flight load can override the persisted preference. @@ -203,38 +202,3 @@ it('continues in English while plugin discovery is pending without changing the expect(usePluginLanguagePackStore.getState().loaded).toBe(false) expect(useAppStore.getState().settings?.uiLanguage).toBe('plugin:example.missing/de') }) - -it("re-applies a plugin language only when the selected pack's content changes", async () => { - const id = 'plugin:example.german/de-DE' as const - const pack = (save: string) => ({ - id, - resourceLanguage: pluginLanguageResourceId(id), - pluginKey: 'example.german', - coverage: 100, - locale: 'de-DE', - catalog: { common: { save } } - }) - let listed = [pack('Speichern')] - Object.defineProperty(window, 'api', { - configurable: true, - value: { plugins: { listLanguagePacks: async () => structuredClone(listed) } } - }) - usePluginLanguagePackStore.setState({ entries: [], loaded: false }) - useAppStore.setState({ settings: { ...getDefaultSettings('/tmp'), uiLanguage: id } }) - await renderProvider() - await act(() => usePluginLanguagePackStore.getState().fetchEntries()) - await vi.waitFor(() => expect(i18n.language).toBe(pluginLanguageResourceId(id))) - const changeLanguage = vi.spyOn(i18n, 'changeLanguage') - const removeBundle = vi.spyOn(i18n, 'removeResourceBundle') - - // Plugin-change refreshes rebuild every registration over IPC, even when nothing changed. - await act(() => usePluginLanguagePackStore.getState().fetchEntries()) - await vi.waitFor(() => expect(useLanguageReadiness.getState().loading).toBe(false)) - expect(changeLanguage).not.toHaveBeenCalled() - expect(removeBundle).not.toHaveBeenCalled() - - listed = [pack('Sichern')] - await act(() => usePluginLanguagePackStore.getState().fetchEntries()) - await vi.waitFor(() => expect(changeLanguage).toHaveBeenCalledWith(pluginLanguageResourceId(id))) - expect(rendererI18n.translate('common.save', 'Save')).toBe('Sichern') -}) diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 090345f268b..21f10a7612b 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -16974,7 +16974,8 @@ "micFallback": "Ausgewähltes Mikrofon nicht verfügbar. Systemstandard wird verwendet.", "micDisconnected": "Mikrofon getrennt. Diktat gestoppt.", "cloudLimitReached": "Diktat am 10-Minuten-Limit der Cloud gestoppt.", - "stoppedAfterSilence": "Nach einer Minute Stille beendet" + "stoppedAfterSilence": "Nach einer Minute Stille beendet", + "retryUnmatched": "Beim erneuten Versuch war nicht erkennbar, welche Wörter schon eingegeben waren, daher wurden alle eingefügt." }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "Das Diktat konnte nicht eingefügt werden und wurde in die Zwischenablage kopiert.", @@ -16982,7 +16983,21 @@ "lost": "Das Diktat konnte weder eingefügt noch kopiert werden." }, "DictationIndicator": { - "4977162383": "Zu laut" + "4977162383": "Zu laut", + "finishing": "Wird abgeschlossen…", + "listening": "Hört zu…", + "cancel": "Abbrechen", + "finish": "Fertig", + "oneMinuteLeft": "Noch eine Minute.", + "sendsWhenLanded": "Sendet, sobald der Text da ist", + "entersWhenLanded": "Drückt Enter, sobald der Text da ist" + }, + "DictationPillFailure": { + "discard": "Aufnahme verwerfen", + "modelFailed": "Modell nicht geladen.", + "transcribeFailed": "Nicht erkannt. Aufnahme behalten.", + "openSettings": "Einstellungen", + "retry": "Wiederholen" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index e7c433aa147..24007e63f01 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -16700,7 +16700,8 @@ "micFallback": "Micrófono seleccionado no disponible. Se usará el predeterminado del sistema.", "micDisconnected": "Micrófono desconectado. Dictado detenido.", "cloudLimitReached": "Dictado detenido al llegar al límite de 10 minutos en la nube.", - "stoppedAfterSilence": "Se detuvo tras un minuto de silencio" + "stoppedAfterSilence": "Se detuvo tras un minuto de silencio", + "retryUnmatched": "Al reintentar no se pudo saber qué palabras ya estaban escritas, así que se insertaron todas." }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "No se pudo insertar el dictado, así que se copió al portapapeles.", @@ -16708,7 +16709,21 @@ "lost": "No se pudo insertar ni copiar el dictado." }, "DictationIndicator": { - "4977162383": "Volumen demasiado alto" + "4977162383": "Volumen demasiado alto", + "finishing": "Terminando…", + "listening": "Escuchando…", + "cancel": "Cancelar", + "finish": "Terminar", + "oneMinuteLeft": "Queda un minuto.", + "sendsWhenLanded": "Se enviará cuando llegue el texto", + "entersWhenLanded": "Pulsará Enter cuando llegue el texto" + }, + "DictationPillFailure": { + "discard": "Descartar grabación", + "modelFailed": "El modelo no cargó.", + "transcribeFailed": "No se transcribió. Grabación guardada.", + "openSettings": "Configuración", + "retry": "Reintentar" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 2b8b042c3ed..fc72f89f67c 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -16925,7 +16925,8 @@ "micFallback": "Micro sélectionné indisponible. Utilisation du micro par défaut du système.", "micDisconnected": "Micro déconnecté. Dictée arrêtée.", "cloudLimitReached": "Dictée arrêtée à la limite cloud de 10 minutes.", - "stoppedAfterSilence": "Arrêt après une minute de silence" + "stoppedAfterSilence": "Arrêt après une minute de silence", + "retryUnmatched": "La nouvelle tentative n'a pas pu repérer les mots déjà saisis, ils ont donc tous été insérés." }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "La dictée n'a pas pu être insérée, elle a donc été copiée dans le presse-papiers.", @@ -16933,7 +16934,21 @@ "lost": "La dictée n'a pu être ni insérée ni copiée." }, "DictationIndicator": { - "4977162383": "Trop fort" + "4977162383": "Trop fort", + "finishing": "Finalisation…", + "listening": "Écoute…", + "cancel": "Annuler", + "finish": "Terminer", + "oneMinuteLeft": "Plus qu’une minute.", + "sendsWhenLanded": "Envoi dès que le texte arrive", + "entersWhenLanded": "Entrée dès que le texte arrive" + }, + "DictationPillFailure": { + "discard": "Supprimer l'enregistrement", + "modelFailed": "Modèle non chargé.", + "transcribeFailed": "Échec. Enregistrement conservé.", + "openSettings": "Paramètres", + "retry": "Réessayer" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 0b518832052..a161f789437 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -16298,7 +16298,8 @@ "micFallback": "選択したマイクが使用できません。システムのデフォルトを使用します。", "micDisconnected": "マイクが接続されていません。ディクテーションが停止しました。", "cloudLimitReached": "クラウドの10分の上限に達したため、ディクテーションが停止しました。", - "stoppedAfterSilence": "1分間音声がなかったため停止しました。" + "stoppedAfterSilence": "1分間音声がなかったため停止しました。", + "retryUnmatched": "再試行で入力済みの語句を特定できなかったため、すべて挿入しました。" }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "音声入力を挿入できなかったため、クリップボードにコピーしました。", @@ -16306,7 +16307,21 @@ "lost": "音声入力を挿入もコピーもできませんでした。" }, "DictationIndicator": { - "4977162383": "音量が大きすぎます" + "4977162383": "音量が大きすぎます", + "finishing": "仕上げ中…", + "listening": "聞き取り中…", + "cancel": "キャンセル", + "finish": "完了", + "oneMinuteLeft": "残り1分です。", + "sendsWhenLanded": "テキストの入力後に送信します", + "entersWhenLanded": "テキストの入力後に Enter を押します" + }, + "DictationPillFailure": { + "discard": "録音を破棄", + "modelFailed": "音声モデルを読み込めません。", + "transcribeFailed": "文字起こしに失敗。録音は保持しました。", + "openSettings": "設定を開く", + "retry": "再試行" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 0180fd9d8bd..75e6a229e7a 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -16298,7 +16298,8 @@ "micFallback": "선택한 마이크를 사용할 수 없습니다. 시스템 기본값을 사용합니다.", "micDisconnected": "마이크 연결이 끊어졌습니다. 받아쓰기가 중지되었습니다.", "cloudLimitReached": "클라우드 10분 제한에 도달해 받아쓰기가 중지되었습니다.", - "stoppedAfterSilence": "1분 동안 말소리가 없어 중지했습니다." + "stoppedAfterSilence": "1분 동안 말소리가 없어 중지했습니다.", + "retryUnmatched": "다시 시도할 때 이미 입력된 단어를 찾지 못해 전부 삽입했습니다." }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "받아쓰기를 삽입할 수 없어 클립보드에 복사했습니다.", @@ -16306,7 +16307,21 @@ "lost": "받아쓰기를 삽입하거나 복사할 수 없습니다." }, "DictationIndicator": { - "4977162383": "음량이 너무 큽니다" + "4977162383": "음량이 너무 큽니다", + "finishing": "마무리 중…", + "listening": "듣는 중…", + "cancel": "취소", + "finish": "완료", + "oneMinuteLeft": "1분 남았습니다.", + "sendsWhenLanded": "텍스트가 입력되면 전송합니다", + "entersWhenLanded": "텍스트가 입력되면 Enter를 누릅니다" + }, + "DictationPillFailure": { + "discard": "녹음 삭제", + "modelFailed": "음성 모델을 불러오지 못했습니다.", + "transcribeFailed": "받아쓰기에 실패했습니다. 녹음은 보관됩니다.", + "openSettings": "설정 열기", + "retry": "다시 시도" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 720b00f8403..fe78ad3d3de 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -19259,7 +19259,8 @@ "micFallback": "O microfone selecionado não está disponível. Usando o padrão do sistema.", "micDisconnected": "Microfone desconectado. O ditado foi interrompido.", "cloudLimitReached": "O ditado foi interrompido no limite de 10 minutos da nuvem.", - "stoppedAfterSilence": "Parou após um minuto de silêncio" + "stoppedAfterSilence": "Parou após um minuto de silêncio", + "retryUnmatched": "Ao tentar de novo, não foi possível saber quais palavras já estavam digitadas, então todas foram inseridas." }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "Não foi possível inserir o ditado, então ele foi copiado para a área de transferência.", @@ -19267,7 +19268,21 @@ "lost": "Não foi possível inserir nem copiar o ditado." }, "DictationIndicator": { - "4977162383": "Muito alto" + "4977162383": "Muito alto", + "finishing": "Finalizando…", + "listening": "Ouvindo…", + "cancel": "Cancelar", + "finish": "Concluir", + "oneMinuteLeft": "Falta um minuto.", + "sendsWhenLanded": "Envia quando o texto chegar", + "entersWhenLanded": "Pressiona Enter quando o texto chegar" + }, + "DictationPillFailure": { + "discard": "Descartar gravação", + "modelFailed": "Modelo não carregou.", + "transcribeFailed": "Não transcrito. Gravação mantida.", + "openSettings": "Configurações", + "retry": "Repetir" } }, "link": { diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 774868e30fb..cc61948d8e0 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -17470,7 +17470,8 @@ "micFallback": "Выбранный микрофон недоступен. Используется системный микрофон по умолчанию.", "micDisconnected": "Микрофон отключён. Диктовка остановлена.", "cloudLimitReached": "Диктовка остановлена: достигнут 10-минутный облачный лимит.", - "stoppedAfterSilence": "Остановлено после минуты тишины" + "stoppedAfterSilence": "Остановлено после минуты тишины", + "retryUnmatched": "При повторе не удалось понять, какие слова уже введены, поэтому вставлено всё." }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "Не удалось вставить диктовку, поэтому она скопирована в буфер обмена.", @@ -17478,7 +17479,21 @@ "lost": "Не удалось ни вставить, ни скопировать диктовку." }, "DictationIndicator": { - "4977162383": "Слишком громко" + "4977162383": "Слишком громко", + "finishing": "Завершение…", + "listening": "Слушаю…", + "cancel": "Отмена", + "finish": "Готово", + "oneMinuteLeft": "Осталась минута.", + "sendsWhenLanded": "Отправится, когда текст появится", + "entersWhenLanded": "Нажмёт Enter, когда текст появится" + }, + "DictationPillFailure": { + "discard": "Удалить запись", + "modelFailed": "Модель не загружена.", + "transcribeFailed": "Не удалось распознать. Запись сохранена.", + "openSettings": "Настройки", + "retry": "Повторить" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 47a5314415e..b1d069b3554 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -16958,7 +16958,8 @@ "micFallback": "Seçili mikrofon kullanılamıyor. Sistem varsayılanı kullanılıyor.", "micDisconnected": "Mikrofon bağlantısı kesildi. Dikte durduruldu.", "cloudLimitReached": "Dikte, 10 dakikalık bulut sınırında durduruldu.", - "stoppedAfterSilence": "Bir dakika sessizlikten sonra durduruldu" + "stoppedAfterSilence": "Bir dakika sessizlikten sonra durduruldu", + "retryUnmatched": "Yeniden deneme hangi kelimelerin zaten yazıldığını anlayamadı, bu yüzden hepsini ekledi." }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "Dikte eklenemedi, bu yüzden panoya kopyalandı.", @@ -16966,7 +16967,21 @@ "lost": "Dikte eklenemedi ve kopyalanamadı." }, "DictationIndicator": { - "4977162383": "Çok yüksek sesli" + "4977162383": "Çok yüksek sesli", + "finishing": "Tamamlanıyor…", + "listening": "Dinleniyor…", + "cancel": "İptal", + "finish": "Bitir", + "oneMinuteLeft": "Bir dakika kaldı.", + "sendsWhenLanded": "Metin gelince gönderilecek", + "entersWhenLanded": "Metin gelince Enter'a basılacak" + }, + "DictationPillFailure": { + "discard": "Kaydı sil", + "modelFailed": "Model yüklenemedi.", + "transcribeFailed": "Yazıya dökülemedi. Kayıt saklandı.", + "openSettings": "Ayarlar", + "retry": "Yeniden dene" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 0d6da58cb87..abaa5ff49a0 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -16747,7 +16747,8 @@ "micFallback": "所選麥克風不可用。使用系統預設值。", "micDisconnected": "麥克風已中斷連線。聽寫已停止。", "cloudLimitReached": "已達 10 分鐘雲端上限。聽寫已停止。", - "stoppedAfterSilence": "靜音一分鐘後已停止" + "stoppedAfterSilence": "靜音一分鐘後已停止", + "retryUnmatched": "重試時無法判斷哪些字詞已輸入,因此已全部插入。" }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "無法插入聽寫內容,已複製到剪貼簿。", @@ -16755,7 +16756,21 @@ "lost": "無法插入或複製聽寫內容。" }, "DictationIndicator": { - "4977162383": "聲音太大" + "4977162383": "聲音太大", + "finishing": "正在完成…", + "listening": "正在聆聽…", + "cancel": "取消", + "finish": "完成", + "oneMinuteLeft": "剩下 1 分鐘。", + "sendsWhenLanded": "文字送達後自動傳送", + "entersWhenLanded": "文字送達後自動按 Enter" + }, + "DictationPillFailure": { + "discard": "捨棄錄音", + "modelFailed": "無法載入語音模型。", + "transcribeFailed": "無法轉錄。已保留錄音。", + "openSettings": "開啟設定", + "retry": "重試" } }, "dashboard": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 602f52d1124..4f7595734eb 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -16298,7 +16298,8 @@ "micFallback": "所选麦克风不可用。使用系统默认值。", "micDisconnected": "麦克风已断开。听写停止了。", "cloudLimitReached": "已达 10 分钟云端上限。听写已停止。", - "stoppedAfterSilence": "静音一分钟后已停止" + "stoppedAfterSilence": "静音一分钟后已停止", + "retryUnmatched": "重试时无法判断哪些字词已输入,因此已全部插入。" }, "dictation-transcript-delivery": { "copiedAfterFailedInsert": "无法插入听写内容,已复制到剪贴板。", @@ -16306,7 +16307,21 @@ "lost": "无法插入或复制听写内容。" }, "DictationIndicator": { - "4977162383": "音量过大" + "4977162383": "音量过大", + "finishing": "正在完成…", + "listening": "正在聆听…", + "cancel": "取消", + "finish": "完成", + "oneMinuteLeft": "还剩 1 分钟。", + "sendsWhenLanded": "文字送达后自动发送", + "entersWhenLanded": "文字送达后自动按 Enter" + }, + "DictationPillFailure": { + "discard": "舍弃录音", + "modelFailed": "无法加载语音模型。", + "transcribeFailed": "无法转录。已保留录音。", + "openSettings": "打开设置", + "retry": "重试" } }, "dashboard": { diff --git a/src/renderer/src/i18n/relative-time-format.test.ts b/src/renderer/src/i18n/relative-time-format.test.ts deleted file mode 100644 index dcef475ee7d..00000000000 --- a/src/renderer/src/i18n/relative-time-format.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { mockIntlLocale } = vi.hoisted(() => ({ mockIntlLocale: { value: 'en' } })) - -vi.mock('./i18n', () => ({ getIntlLocale: () => mockIntlLocale.value })) - -import { getUiRelativeTimeFormatter } from './relative-time-format' - -beforeEach(() => { - mockIntlLocale.value = 'en' -}) - -describe('getUiRelativeTimeFormatter', () => { - it('rebuilds the formatter after a runtime language switch', () => { - const english = getUiRelativeTimeFormatter() - mockIntlLocale.value = 'ko' - const korean = getUiRelativeTimeFormatter() - expect(korean).not.toBe(english) - expect(korean.format(-1, 'day')).toBe('어제') - }) -}) diff --git a/src/renderer/src/i18n/ui-intl-formatters.test.ts b/src/renderer/src/i18n/ui-intl-formatters.test.ts deleted file mode 100644 index 49432d51222..00000000000 --- a/src/renderer/src/i18n/ui-intl-formatters.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { afterEach, expect, it } from 'vitest' -import { i18n, loadRendererUiLanguage } from './i18n' -import { uiNumberFormat } from './ui-intl-formatters' - -const GROUPED: Intl.NumberFormatOptions = {} - -afterEach(async () => { - await i18n.changeLanguage('en') -}) - -it('rebuilds a shared formatter when the UI language changes', async () => { - expect(uiNumberFormat(GROUPED).format(1234.5)).toBe('1,234.5') - await i18n.changeLanguage(await loadRendererUiLanguage('de')) - expect(uiNumberFormat(GROUPED).format(1234.5)).toBe('1.234,5') -}) diff --git a/src/renderer/src/lib/agent-session/launch/agent-settings-update-queue.test.ts b/src/renderer/src/lib/agent-session/launch/agent-settings-update-queue.test.ts deleted file mode 100644 index ec15942fc1a..00000000000 --- a/src/renderer/src/lib/agent-session/launch/agent-settings-update-queue.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../../shared/constants' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' -import { useAppStore } from '../../../store/index' -import { createAgentAvailabilityUpdateQueue } from './agent-settings-update-queue' - -describe('agent availability settings', () => { - it('continues serializing requests after a rejected write', async () => { - const settings: GlobalSettings = { - ...getDefaultSettings('/tmp'), - defaultTuiAgent: null, - disabledTuiAgents: [] - } - let latest = settings - const updateSettings = vi - .fn<(update: Partial) => Promise>() - .mockRejectedValueOnce(new Error('write failed')) - .mockImplementationOnce(async (update) => { - latest = { ...latest, ...update } - }) - const enqueue = createAgentAvailabilityUpdateQueue() - - await expect( - enqueue({ - getSettings: () => latest, - fallbackSettings: settings, - updateSettings, - agentId: 'claude', - enabled: false - }) - ).rejects.toThrow('write failed') - await enqueue({ - getSettings: () => latest, - fallbackSettings: settings, - updateSettings, - agentId: 'codex', - enabled: false - }) - - expect(updateSettings).toHaveBeenCalledTimes(2) - expect(updateSettings.mock.calls[1][0]).toMatchObject({ disabledTuiAgents: ['codex'] }) - }) -}) - -type Deferred = { - promise: Promise - resolve: () => void -} - -function createDeferred(): Deferred { - let resolve!: () => void - const promise = new Promise((next) => { - resolve = next - }) - return { promise, resolve } -} - -async function flushPromiseQueue(): Promise { - await Promise.resolve() - await Promise.resolve() -} - -describe('AgentsPane', () => { - it('serializes rapid availability writes against the latest settings snapshot', async () => { - const queueAvailabilityUpdate = createAgentAvailabilityUpdateQueue() - const settings: GlobalSettings = { - ...getDefaultSettings('/tmp'), - defaultTuiAgent: null, - disabledTuiAgents: [] - } - const writes: Deferred[] = [] - const updates: Partial[] = [] - - useAppStore.setState({ settings }) - const updateSettings = vi.fn((update: Partial) => { - updates.push(update) - const nextSettings = { - ...(useAppStore.getState().settings ?? settings), - ...update - } - const write = createDeferred() - writes.push(write) - return write.promise.then(() => { - useAppStore.setState({ settings: nextSettings }) - }) - }) - - const firstWrite = queueAvailabilityUpdate({ - getSettings: () => useAppStore.getState().settings, - fallbackSettings: settings, - updateSettings, - agentId: 'claude', - enabled: false - }) - const secondWrite = queueAvailabilityUpdate({ - getSettings: () => useAppStore.getState().settings, - fallbackSettings: settings, - updateSettings, - agentId: 'codex', - enabled: false - }) - - await flushPromiseQueue() - expect(updateSettings).toHaveBeenCalledTimes(1) - expect(updates[0]).toMatchObject({ disabledTuiAgents: ['claude'] }) - - writes[0].resolve() - await firstWrite - await flushPromiseQueue() - - expect(updateSettings).toHaveBeenCalledTimes(2) - expect(updates[1]).toMatchObject({ disabledTuiAgents: ['claude', 'codex'] }) - - writes[1].resolve() - await secondWrite - }) -}) diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-record.test.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-record.test.ts deleted file mode 100644 index e9a386ed041..00000000000 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-record.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { validRecord } from './structured-agent-session-launch-record' - -const record = { - sessionId: 'codex_11111111_2222_3333_4444_555555555555', - executionHostId: 'local', - agent: 'codex', - lifecycle: 'visibility-unknown', - clientOperationId: 'create-operation', - payloadFingerprint: 'a'.repeat(64), - expectedRuntimeFence: null, - createMessageSupport: true, - firstMessage: { - clientMessageId: 'opening-message', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'opening π text' }] } - } -} - -afterEach(() => vi.unstubAllGlobals()) - -describe('a persisted create opening message', () => { - it('loads the frozen user message in a browser without Node Buffer', () => { - vi.stubGlobal('Buffer', undefined) - expect(() => validRecord(record)).not.toThrow() - expect(validRecord(record)).toBe(true) - }) -}) diff --git a/src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-stranded-sleep.test.ts b/src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-stranded-sleep.test.ts deleted file mode 100644 index 6970ba51419..00000000000 --- a/src/renderer/src/lib/agent-session/resume/resume-sleeping-agent-session-stranded-sleep.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume' -import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' -import { useAppStore } from '@/store/index' -import { resumeSleepingAgentSessionsForWorktree } from './resume-sleeping-agent-session' - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) - -const initialAppStoreState = useAppStore.getState() - -afterEach(() => { - vi.unstubAllGlobals() - useAppStore.setState(initialAppStoreState, true) -}) - -// #22657: deleting or ignoring it would leave the session with no resume handle at all. -it('reopens a slept agent whose tab is gone in a fresh tab and retires main’s record', async () => { - const retireStrandedSleepRecord = vi.fn().mockResolvedValue(undefined) - vi.stubGlobal('window', { api: { worktrees: { retireStrandedSleepRecord } } }) - const record: SleepingAgentSessionRecord = { - paneKey: makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111'), - tabId: 'tab-1', - worktreeId: 'wt-1', - agent: 'claude', - providerSession: { key: 'session_id', id: 'sess-1' }, - prompt: '', - state: 'done', - capturedAt: 1, - updatedAt: 1, - origin: 'worktree-sleep', - restoreOnTabOpenOnly: true - } - useAppStore.setState({ - tabsByWorktree: { 'wt-1': [] }, - sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } - } as never) - - expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) - const state = useAppStore.getState() - const resumedTab = state.tabsByWorktree['wt-1']?.[0] - expect(state.pendingStartupByTabId[resumedTab!.id]?.resumeProviderSession).toEqual( - record.providerSession - ) - expect(state.sleepingAgentSessionsByPaneKey[record.paneKey]).toBeUndefined() - await vi.waitFor(() => - expect(retireStrandedSleepRecord).toHaveBeenCalledWith({ - worktreeId: 'wt-1', - paneKey: record.paneKey - }) - ) -}) diff --git a/src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts b/src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts deleted file mode 100644 index d15daee5e3d..00000000000 --- a/src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import type * as BrowserFocusModule from '@/components/browser-pane/host-guest/browser-focus' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { createStoreCascadesMockApi } from '@/store/testing/app-store-cascade-api.test-fixture' -import type { BrowserSessionProfile } from '../../../../../shared/browser-workspace-types' -import { getDefaultSettings } from '../../../../../shared/constants' -import { openFileInBrowserTab } from '../../file-preview' -import { openWorkspaceBrowserTabForLink } from '../workspace/workspace-browser-tab-open' -import { captureLinkOpenIntent } from '../../link-open-intent' -import type { BrowserOpenOutcome } from './browser-link-destination' -import { - createBrowserLinkTestStore, - WORKSPACE, - URL_TO_OPEN, - type BrowserLinkTestStore -} from './browser-link-open.test-fixture' - -const mocks = vi.hoisted(() => ({ getState: vi.fn(), ensureProfile: vi.fn() })) -vi.mock('@/store/index', () => ({ useAppStore: { getState: () => mocks.getState() } })) -vi.mock('@/components/browser-pane/host-guest/browser-focus', async (importOriginal) => ({ - ...(await importOriginal()), - requestBrowserFocus: vi.fn() -})) -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), info: vi.fn(), success: vi.fn(), warning: vi.fn() } -})) - -let store: BrowserLinkTestStore -beforeEach(() => { - createStoreCascadesMockApi() - Object.defineProperty(window.api, 'browser', { - value: { - sessionEnsureManagedProfile: mocks.ensureProfile, - notifyActiveTabChanged: vi.fn().mockResolvedValue(undefined) - }, - configurable: true - }) - mocks.ensureProfile.mockReset() - store = createBrowserLinkTestStore() - mocks.getState.mockImplementation(() => store.getState()) - store.setState({ - browserSessionProfilesByHostId: { - local: [ - { - id: 'default', - scope: 'default', - partition: 'persist:shared', - label: 'Default', - source: null - } - ] - } - }) -}) - -function open(surface: 'http' | 'html'): Promise { - const linkContext = { - linkIntent: captureLinkOpenIntent(store.getState(), WORKSPACE, 'source') - } - if (surface === 'http') { - return openWorkspaceBrowserTabForLink({ - workspaceId: WORKSPACE, - url: URL_TO_OPEN, - intent: { kind: 'url' }, - linkContext - }) - } - return new Promise((resolve) => - openFileInBrowserTab({ - filePath: '/repo/report.html', - worktreeId: WORKSPACE, - linkContext, - onLinkOutcome: resolve - }) - ) -} - -describe.each(['repo', 'worktree'] as const)('%s browser profile isolation', (scope) => { - it.each(['http', 'html'] as const)( - 'opens %s links in the managed profile and only reuses pages in that profile', - async (surface) => { - const profile: BrowserSessionProfile = { - id: 'managed', - scope: 'isolated', - partition: 'persist:managed', - label: 'Workspace login', - source: null, - owner: { kind: scope, id: scope === 'repo' ? 'repo1' : WORKSPACE } - } - mocks.ensureProfile.mockResolvedValue(profile) - store.setState((state) => ({ - settings: { ...getDefaultSettings('/home/test'), browserProfileScope: scope }, - browserSessionProfilesByHostId: { - local: [...state.browserSessionProfilesByHostId.local!, profile] - } - })) - const shared = store - .getState() - .createBrowserTab( - WORKSPACE, - surface === 'http' ? URL_TO_OPEN : 'file:///repo/report.html', - { - targetGroupId: 'b', - executionHostId: 'local', - browserRuntimeEnvironmentId: null, - sessionProfileId: 'default', - activate: false - } - ) - - const opened = await open(surface) - expect(opened.status).toBe('opened') - if (opened.status !== 'opened') { - throw new Error('Expected scoped browser page') - } - expect(opened.result.browserWorkspaceId).not.toBe(shared.id) - expect( - store - .getState() - .browserTabsByWorktree[WORKSPACE]?.find( - (workspace) => workspace.id === opened.result.browserWorkspaceId - ) - ).toMatchObject({ sessionProfileId: profile.id, sessionPartition: profile.partition }) - const reopened = await open(surface) - if (surface === 'html') { - expect(reopened).toEqual(opened) - } else { - expect(reopened.status).toBe('opened') - if (reopened.status !== 'opened') { - throw new Error('Expected opened link') - } - expect(reopened.result.browserWorkspaceId).not.toBe(opened.result.browserWorkspaceId) - } - expect(store.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength( - surface === 'http' ? 3 : 2 - ) - } - ) -}) - -it('holds a link in an isolated partition until its workspace profile is minted', async () => { - let mintProfile: ((profile: BrowserSessionProfile) => void) | undefined - mocks.ensureProfile.mockImplementation( - () => new Promise((resolve) => (mintProfile = resolve)) - ) - store.setState({ - settings: { ...getDefaultSettings('/home/test'), browserProfileScope: 'worktree' } - }) - const opened = await open('http') - if (opened.status !== 'opened') { - throw new Error('Expected pending browser page') - } - const pending = store - .getState() - .browserTabsByWorktree[WORKSPACE]?.find( - (workspace) => workspace.id === opened.result.browserWorkspaceId - ) - expect(pending?.sessionProfileId).toBeTruthy() - expect(pending?.sessionProfileId).not.toBe('default') - expect(pending?.sessionPartition).toBe( - `persist:orca-browser-unminted-${pending?.sessionProfileId}` - ) - expect(store.getState().managedBrowserProfileStatusById[pending?.sessionProfileId ?? '']).toBe( - 'pending' - ) - - mintProfile?.({ - id: 'minted', - scope: 'isolated', - partition: 'persist:minted', - label: 'Workspace login', - source: null, - owner: { kind: 'worktree', id: WORKSPACE } - }) - await vi.waitFor(() => - expect( - store - .getState() - .browserTabsByWorktree[WORKSPACE]?.find( - (workspace) => workspace.id === opened.result.browserWorkspaceId - ) - ).toMatchObject({ sessionProfileId: 'minted', sessionPartition: null }) - ) -}) diff --git a/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts b/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts index b7e481258ed..1078fd125cd 100644 --- a/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts +++ b/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts @@ -247,38 +247,6 @@ it.each(['workspace', 'view'] as const)( } ) -it.each([false, true])( - 'reveals the tab layout for a foreground source-aware HTTP link (already open: %s)', - async (reuse) => { - if (reuse) { - useAppStore.getState().createBrowserTab(WORKSPACE, URL_TO_OPEN, { - targetGroupId: 'b', - activate: false, - browserRuntimeEnvironmentId: null, - sessionProfileId: null - }) - } - const opening = vi.spyOn(workspaceBrowserTabOpen, 'openWorkspaceBrowserTabForLink') - openHttpLink(URL_TO_OPEN, { - worktreeId: WORKSPACE, - sourceOwner: { kind: 'local' }, - linkContext: { - linkIntent: captureLinkOpenIntent(useAppStore.getState(), WORKSPACE, 'source') - } - }) - await vi.waitFor(() => expect(opening).toHaveBeenCalledOnce()) - const outcome = await opening.mock.results[0]!.value - - expect(outcome).toMatchObject({ status: 'opened' }) - if (outcome.status !== 'opened') { - throw new Error('Expected opened link') - } - expect(useAppStore.getState().activeView).toBe('terminal') - expect(useAppStore.getState().activeGroupIdByWorktree[WORKSPACE]).toBe(outcome.result.groupId) - expect(useAppStore.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(reuse ? 2 : 1) - } -) - it('keeps the Activity view and current pane selected for background source-aware HTTP links', async () => { useAppStore.setState({ settings: { @@ -340,21 +308,3 @@ it('keeps the main view and workspace selected when revealing a floating HTTP li expect(useAppStore.getState().activeGroupIdByWorktree[floating]).toBe('b') expect(useAppStore.getState().groupsByWorktree[floating]).toHaveLength(3) }) - -it('opens a new page for an HTTP link without source context', async () => { - const browser = useAppStore.getState().createBrowserTab(WORKSPACE, URL_TO_OPEN, { - targetGroupId: 'b', - browserRuntimeEnvironmentId: null, - sessionProfileId: null, - activate: false - }) - const completed = observeBrowserLinkOpen() - openHttpLink(URL_TO_OPEN, { worktreeId: WORKSPACE, sourceOwner: { kind: 'local' } }) - const outcome = await completed - expect(outcome.status).toBe('opened') - if (outcome.status !== 'opened') { - throw new Error('Expected opened link') - } - expect(outcome.result.browserWorkspaceId).not.toBe(browser.id) - expect(useAppStore.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(2) -}) diff --git a/src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts b/src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts index 8cacc1dcb90..3ccabf528a7 100644 --- a/src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts +++ b/src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts @@ -2,12 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { BrowserPage, BrowserWorkspace } from '../../../../../shared/browser-workspace-types' -import type { FolderWorkspace } from '../../../../../shared/folder-workspaces/folder-workspace-types' import type { Tab, TabGroup } from '../../../../../shared/tab-types' import type { Worktree } from '../../../../../shared/worktree/types' import '../../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' -import { folderWorkspaceKey } from '../../../../../shared/workspace-scope' import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' @@ -44,25 +42,6 @@ function makeWorktree(overrides: Partial = {}): Worktree { } } -function makeFolderWorkspace(overrides: Partial = {}): FolderWorkspace { - return { - id: 'folder-1', - projectGroupId: 'project-1', - name: 'Remote folder', - folderPath: '/workspace/folder-1', - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0, - ...overrides - } -} - function makeWorkspace(overrides: Partial = {}): BrowserWorkspace { return { id: 'ws-1', @@ -150,26 +129,6 @@ describe('activateBrowserPagePaletteResult', () => { seedStore() }) - it('activates an SSH worktree through its paired-runtime owner alias', () => { - seedStore({ - worktreesByRepo: { - 'repo-1': [ - makeWorktree({ - hostId: 'ssh:private-target', - runtimeOwnerEnvironmentId: 'paired-host' - }) - ] - } - }) - - expect( - activateBrowserPagePaletteResult({ ...target, executionHostId: 'runtime:paired-host' }).status - ).toBe('activated') - expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('wt-1', { - executionHostId: 'runtime:paired-host' - }) - }) - it('rejects colliding child ids before mutating either host', () => { seedStore({ worktreesByRepo: { @@ -196,41 +155,6 @@ describe('activateBrowserPagePaletteResult', () => { expect(mocks.activateAndRevealWorkspace).not.toHaveBeenCalled() }) - it('keeps browser workspaces with distinct unified tabs in multiple groups activatable', () => { - seedStore({ - unifiedTabsByWorktree: { - 'wt-1': [makeBrowserTab(), makeBrowserTab({ id: 'second-view', groupId: 'group-2' })] - }, - groupsByWorktree: { - 'wt-1': [ - makeGroup(), - makeGroup({ id: 'group-2', activeTabId: 'second-view', tabOrder: ['second-view'] }) - ] - } - }) - expect(activateBrowserPagePaletteResult(target).status).toBe('activated') - }) - - it('activates pages in remote folder workspaces', () => { - const worktreeId = folderWorkspaceKey('folder-1') - seedStore({ - worktreesByRepo: {}, - folderWorkspaces: [makeFolderWorkspace({ executionHostId: 'ssh:host-1' })], - browserTabsByWorktree: { [worktreeId]: [makeWorkspace({ worktreeId })] }, - browserPagesByWorkspace: { 'ws-1': [makePage({ worktreeId })] }, - unifiedTabsByWorktree: { [worktreeId]: [makeBrowserTab({ worktreeId })] }, - groupsByWorktree: { [worktreeId]: [makeGroup({ worktreeId })] }, - activeGroupIdByWorktree: { [worktreeId]: 'group-1' } - }) - - expect( - activateBrowserPagePaletteResult({ pageId: 'page-1', workspaceId: 'ws-1', worktreeId }) - ).toMatchObject({ status: 'activated' }) - expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith(worktreeId, { - executionHostId: 'ssh:host-1' - }) - }) - it('derives the focus target from the page url captured before worktree activation', () => { seedStore({ browserPagesByWorkspace: { diff --git a/src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts b/src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts index b5f7d5b5839..d6c1fdbbf2d 100644 --- a/src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts +++ b/src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts @@ -64,12 +64,6 @@ function makePage(overrides: Partial = {}): BrowserPage { } } -const worktreeA = makeWorktree() -const worktreeB = makeWorktree({ - id: 'wt-2', - repoId: 'repo-2', - displayName: 'Other Worktree' -}) const repoMap = new Map([ ['repo-1', { displayName: 'repo/one' }], ['repo-2', { displayName: 'repo/two' }] @@ -79,56 +73,6 @@ const worktreeOrder = new Map([ ['wt-2', 1] ]) -function buildFixture( - overrides: Partial[0]> = {} -): ReturnType { - return buildSearchableBrowserPages({ - worktrees: [worktreeA, worktreeB], - repoMap, - worktreeOrder, - browserTabsByWorktree: { - 'wt-1': [ - makeWorkspace({ - id: 'ws-1', - activePageId: 'page-1', - pageIds: ['page-1', 'page-2'] - }), - makeWorkspace({ - id: 'ws-2', - activePageId: 'page-3', - pageIds: ['page-3'] - }) - ], - 'wt-2': [ - makeWorkspace({ - id: 'ws-3', - worktreeId: 'wt-2', - activePageId: 'page-4' - }) - ] - }, - browserPagesByWorkspace: { - 'ws-1': [ - makePage({ id: 'page-1', title: 'Docs' }), - makePage({ id: 'page-2', title: 'Changelog' }) - ], - 'ws-2': [makePage({ id: 'page-3', workspaceId: 'ws-2', title: 'Issues' })], - 'ws-3': [ - makePage({ - id: 'page-4', - workspaceId: 'ws-3', - worktreeId: 'wt-2', - title: 'Other Docs' - }) - ] - }, - activeBrowserTabId: 'ws-1', - activeWorktreeId: 'wt-1', - activeTabType: 'browser', - ...overrides - }) -} - describe('buildSearchableBrowserPages', () => { it('keeps same-id browser tabs isolated by execution host', () => { const sharedId = 'repo-shared::/workspace' @@ -245,50 +189,6 @@ describe('buildSearchableBrowserPages', () => { }) ).toEqual([]) }) - - it('omits a browser row whose backing tab id is duplicated', () => { - const browserTab = browserUnifiedTab('shared-tab', 'ws-1', 'wt-1') - expect( - buildSearchableBrowserPages({ - worktrees: [worktreeA], - repoMap, - worktreeOrder, - browserTabsByWorktree: { 'wt-1': [makeWorkspace()] }, - browserPagesByWorkspace: { 'ws-1': [makePage()] }, - unifiedTabsByWorktree: { - 'wt-1': [browserTab, { ...browserTab, contentType: 'terminal' }] - }, - activeBrowserTabId: null, - activeWorktreeId: null, - activeTabType: 'terminal' - }) - ).toEqual([]) - }) - - // The index keeps the first tab per workspace ID; prevent duplicates from hiding a later owned tab. - it('omits a workspace claimed by more than one unified browser tab', () => { - const entries = buildFixture({ - unifiedTabsByWorktree: { - 'wt-1': [ - browserUnifiedTab('tab-foreign', 'ws-1', 'wt-2'), - browserUnifiedTab('tab-owned', 'ws-1', 'wt-1') - ] - } - }) - - expect(entries.some((entry) => entry.workspace.id === 'ws-1')).toBe(false) - expect(entries.map((entry) => entry.workspace.id)).toEqual(['ws-2', 'ws-3']) - }) - - // Why: a workspace whose only unified tab belongs to another worktree must stay hidden here. - it('omits a workspace whose single unified browser tab is not owned by this worktree', () => { - const entries = buildFixture({ - unifiedTabsByWorktree: { 'wt-1': [browserUnifiedTab('tab-foreign', 'ws-1', 'wt-2')] } - }) - - expect(entries.some((entry) => entry.workspace.id === 'ws-1')).toBe(false) - expect(entries.some((entry) => entry.workspace.id === 'ws-2')).toBe(true) - }) }) function browserUnifiedTab( @@ -311,41 +211,3 @@ function browserUnifiedTab( createdAt: 0 } } - -it('indexes workspace tabs when building a large browser palette', () => { - let reads = 0 - const workspaces = Array.from({ length: 1000 }, (_, i) => - makeWorkspace({ id: `workspace-${i}`, activePageId: `page-${i}` }) - ) - const tabs: Tab[] = workspaces.map((workspace, i) => ({ - id: `tab-${i}`, - get entityId() { - reads++ - return workspace.id - }, - groupId: 'group-1', - worktreeId: 'wt-1', - contentType: 'browser', - label: 'Example', - customLabel: null, - color: null, - sortOrder: i, - createdAt: 0 - })) - const pages = Object.fromEntries( - workspaces.map((workspace, i) => [ - workspace.id, - [makePage({ id: `page-${i}`, workspaceId: workspace.id })] - ]) - ) - const entries = buildFixture({ - worktrees: [worktreeA], - browserTabsByWorktree: { 'wt-1': workspaces }, - browserPagesByWorkspace: pages, - unifiedTabsByWorktree: { 'wt-1': tabs } - }) - expect(reads).toBeLessThan(6000) - expect(entries.map((entry) => entry.workspace.id)).toEqual( - workspaces.map((workspace) => workspace.id) - ) -}) diff --git a/src/renderer/src/lib/code-host-error-copy.test.ts b/src/renderer/src/lib/code-host-error-copy.test.ts deleted file mode 100644 index 93ba9e7da9f..00000000000 --- a/src/renderer/src/lib/code-host-error-copy.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { i18n } from '@/i18n/i18n' -import es from '@/i18n/locales/es.json' -import { codeHostFailure } from '../../../shared/code-host-failure-copy' -import { reviewStartPointFailure } from '../../../shared/review-start-point-failure-copy' -import { codeHostErrorText, reviewStartPointErrorText } from './code-host-error-copy' - -const originalLanguage = i18n.language - -afterEach(async () => { - await i18n.changeLanguage(originalLanguage) -}) - -describe('codeHostErrorText', () => { - it('localizes a coded failure and keeps the gh/glab detail verbatim', async () => { - i18n.addResourceBundle('es', 'translation', es) - await i18n.changeLanguage('es') - const unresolved = codeHostFailure('github.repoUnresolved') - expect(unresolved.error).toBe('Could not resolve GitHub owner/repo for this repository') - expect(codeHostErrorText(unresolved)).toBe(es.codeHost.errors.github.repoUnresolved) - - const detail = 'HTTP 422: {{detail}} $& rejected' - const failed = codeHostFailure('github.rerunFailed', detail) - expect(failed.error).toBe(`Failed to rerun checks: ${detail}`) - expect(codeHostErrorText(failed)).toBe( - es.codeHost.errors.github.rerunFailed.replace('{{detail}}', () => detail) - ) - }) - - it('localizes PR/MR start-point failures with their number, ref, and git detail', async () => { - i18n.addResourceBundle('es', 'translation', es) - await i18n.changeLanguage('es') - const missing = reviewStartPointFailure('gitlab.mrNotFound', { number: 7 }) - expect(missing.error).toBe('MR !7 not found.') - expect(reviewStartPointErrorText(missing)).toBe( - es.codeHost.startPoint.gitlab.mrNotFound.replace('{{number}}', '7') - ) - const fetch = reviewStartPointFailure('fetchFailed', { - ref: 'origin/{{detail}}', - detail: 'fatal: no route' - }) - expect(fetch.error).toBe('Failed to fetch origin/{{detail}}: fatal: no route') - expect(reviewStartPointErrorText(fetch)).toBe( - es.codeHost.startPoint.fetchFailed.replace(/\{\{(ref|detail)\}\}/g, (_slot, slot) => - slot === 'ref' ? 'origin/{{detail}}' : 'fatal: no route' - ) - ) - expect(reviewStartPointErrorText({ error: 'English', errorCode: 'gitlab.mrNotFound' })).toBe( - 'English' - ) - }) -}) diff --git a/src/renderer/src/lib/composer-submit-cancellation.test.ts b/src/renderer/src/lib/composer-submit-cancellation.test.ts deleted file mode 100644 index 497b0d0495b..00000000000 --- a/src/renderer/src/lib/composer-submit-cancellation.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { settleComposerSubmit } from './composer-submit-cancellation' - -describe('settleComposerSubmit', () => { - it('drops a resolved preflight result after cancellation', async () => { - let cancelled = false - let resolvePreflight: (value: string) => void = () => undefined - const preflight = new Promise((resolve) => { - resolvePreflight = resolve - }) - const settlement = settleComposerSubmit(preflight, () => cancelled) - - cancelled = true - resolvePreflight('stale result') - - await expect(settlement).resolves.toEqual({ status: 'cancelled' }) - }) - - it('suppresses a rejected preflight after cancellation', async () => { - let cancelled = false - let rejectPreflight: (error: Error) => void = () => undefined - const preflight = new Promise((_resolve, reject) => { - rejectPreflight = reject - }) - const settlement = settleComposerSubmit(preflight, () => cancelled) - - cancelled = true - rejectPreflight(new Error('late failure')) - - await expect(settlement).resolves.toEqual({ status: 'cancelled' }) - }) -}) diff --git a/src/renderer/src/lib/create-untitled-markdown.test.ts b/src/renderer/src/lib/create-untitled-markdown.test.ts deleted file mode 100644 index 22b5db8e170..00000000000 --- a/src/renderer/src/lib/create-untitled-markdown.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createUntitledMarkdownFile } from './create-untitled-markdown' - -import type { RuntimeClientTarget } from '../../../shared/runtime-client-target' - -const LOCAL: RuntimeClientTarget = { kind: 'local' } - -describe('createUntitledMarkdownFile', () => { - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('rejects captured ownership without a current-generation assertion', async () => { - await expect( - createUntitledMarkdownFile('/repo', 'wt-1', undefined, LOCAL, { - operationProvenance: {} as never - }) - ).rejects.toThrow("Couldn't verify which host owns this file") - }) -}) diff --git a/src/renderer/src/lib/emulator-error-copy.test.ts b/src/renderer/src/lib/emulator-error-copy.test.ts deleted file mode 100644 index 348ea6be05c..00000000000 --- a/src/renderer/src/lib/emulator-error-copy.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { i18n } from '@/i18n/i18n' -import es from '@/i18n/locales/es.json' -import { emulatorFailureText } from '../../../shared/emulator-failure-copy' -import { emulatorErrorText } from './emulator-error-copy' - -const originalLanguage = i18n.language - -afterEach(async () => { - await i18n.changeLanguage(originalLanguage) -}) - -function rpcError(code: string, message: string): Error { - return Object.assign(new Error(message), { code }) -} - -describe('emulator error copy', () => { - it('translates a thrown error by its operational code and keeps device names verbatim', async () => { - i18n.addResourceBundle('es', 'translation', es) - await i18n.changeLanguage('es') - const message = emulatorFailureText('androidDeviceNotRunning', { device: 'Pixel 7 "Pro"' }) - expect(emulatorErrorText(rpcError('emulator_device_not_found', message), 'fallback')).toBe( - es.emulator.errors.androidDeviceNotRunning.replace('{{device}}', 'Pixel 7 "Pro"') - ) - expect(emulatorErrorText(rpcError('emulator_disabled', message), 'fallback')).toBe(message) - expect(emulatorErrorText(rpcError('emulator_error', 'adb: device offline'), 'x')).toBe( - 'adb: device offline' - ) - expect(emulatorErrorText('not an error', 'fallback')).toBe('fallback') - }) -}) diff --git a/src/renderer/src/lib/new-workspace-composer-repo.test.ts b/src/renderer/src/lib/new-workspace-composer-repo.test.ts deleted file mode 100644 index 9e3eb7fe63a..00000000000 --- a/src/renderer/src/lib/new-workspace-composer-repo.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { Repo } from '../../../shared/repo-types' -import { resolveComposerActiveRepoId } from './new-workspace-composer-repo' - -function repo(id: string, executionHostId: ExecutionHostId, path: string): Repo { - return { - id, - path, - displayName: 'app', - badgeColor: '#000000', - addedAt: 0, - executionHostId, - connectionId: null, - gitRemoteIdentity: { - canonicalKey: 'github.com/acme/app', - remoteName: 'origin', - remoteUrl: 'git@github.com:acme/app.git' - } - } -} - -describe('resolveComposerActiveRepoId', () => { - it('seeds from the visible checkout when the active workspace is on a per-workspace VM', () => { - const vmRepo = repo('vm-repo', 'runtime:vm-1', '/home/orca/app') - const macRepo = repo('mac-repo', 'local', '/Users/me/app') - const repos = [vmRepo, macRepo] - - expect( - resolveComposerActiveRepoId(repos, repos, 'vm-repo', [{ id: 'vm-1', source: 'ephemeral-vm' }]) - ).toBe('mac-repo') - }) -}) diff --git a/src/renderer/src/lib/provider-accounts/claude-account-switch-sessions.test.ts b/src/renderer/src/lib/provider-accounts/claude-account-switch-sessions.test.ts deleted file mode 100644 index dd0eb354623..00000000000 --- a/src/renderer/src/lib/provider-accounts/claude-account-switch-sessions.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { ClaudeAccountSwitchRunningSessions } from '../../../../shared/claude-account-switch-settings' -import type { ClaudeManagedAccountSummary } from '../../../../shared/managed-account-types' -import { findClaudeSwitchSessions } from '../agent-session/accounts/claude/claude-session-account-move' -import type * as AccountMove from '../agent-session/accounts/claude/claude-session-account-move' -import type { ClaudeSwitchSessions } from '../agent-session/accounts/claude/claude-session-account-move' -import { - answerClaudeAccountSwitchPrompt, - getClaudeAccountSwitchPrompt, - handleRunningClaudeSessionsAfterSwitch, - resetClaudeAccountSwitchSessionsForTests -} from './claude-account-switch-sessions' - -type SwitchSettings = { claudeAccountSwitchRunningSessions?: ClaudeAccountSwitchRunningSessions } - -type StoreStub = { - settings: SwitchSettings - updateSettings: (updates: SwitchSettings) => Promise - terminalLayoutsByTabId: Record }> - queuePaneAccountRestarts: (ptyIds: string[], agent: string) => void - consumePendingPaneAccountRestart: (ptyId: string) => void -} - -const store = vi.hoisted((): StoreStub => ({ - settings: {}, - terminalLayoutsByTabId: {}, - updateSettings: vi.fn(async () => {}), - queuePaneAccountRestarts: vi.fn(), - consumePendingPaneAccountRestart: vi.fn() -})) -const toastSuccess = vi.hoisted(() => vi.fn()) -const toastWarning = vi.hoisted(() => vi.fn()) - -vi.mock('@/store/index', () => ({ useAppStore: { getState: () => store } })) -vi.mock('sonner', () => ({ toast: { success: toastSuccess, warning: toastWarning } })) -vi.mock('../agent-session/accounts/claude/claude-session-account-move', async (importOriginal) => ({ - ...(await importOriginal()), - findClaudeSwitchSessions: vi.fn(), - findQueuedClaudeRestartsOnAccount: vi.fn(() => []) -})) - -const candidate = (n: number) => ({ - ptyId: `pty-${n}`, - worktreeId: 'wt-1', - tabId: `tab-${n}`, - leafId: `leaf-${n}` -}) -const scan = ( - onAccount: ReturnType[], - others: Partial = {} -): ClaudeSwitchSessions => ({ onAccount, elsewhere: [], cantMove: [], ...others }) -const row = (id: string, extra: Partial = {}) => ({ - id, - email: `${id}@example.com`, - managedAuthRuntime: 'host' as const, - wslDistro: null, - authMethod: 'subscription-oauth' as const, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1, - ...extra -}) -const ROSTER = { accounts: [row('account-a'), row('account-b')] } -const SWITCH = { - owner: { kind: 'local' } as const, - target: { runtime: 'host' } as const, - before: { state: ROSTER, accountId: 'account-a' }, - after: { state: ROSTER, accountId: 'account-b' } -} - -describe('handleRunningClaudeSessionsAfterSwitch', () => { - beforeEach(() => { - vi.clearAllMocks() - resetClaudeAccountSwitchSessionsForTests() - store.settings = {} - store.terminalLayoutsByTabId = Object.fromEntries( - [1, 2, 3].map((n) => [`tab-${n}`, { ptyIdsByLeafId: { [`leaf-${n}`]: `pty-${n}` } }]) - ) - }) - - it('restarts a pane on the PTY it has now, and skips a pane that closed', async () => { - vi.mocked(findClaudeSwitchSessions).mockResolvedValue(scan([candidate(1), candidate(2)])) - await handleRunningClaudeSessionsAfterSwitch(SWITCH) - store.terminalLayoutsByTabId = { 'tab-1': { ptyIdsByLeafId: { 'leaf-1': 'pty-1-reattached' } } } - - answerClaudeAccountSwitchPrompt('restart') - - expect(store.queuePaneAccountRestarts).toHaveBeenLastCalledWith(['pty-1-reattached'], 'claude') - }) - - it('applies Never restart chosen while the scan runs', async () => { - vi.mocked(findClaudeSwitchSessions).mockImplementation(async () => { - store.settings = { claudeAccountSwitchRunningSessions: 'keep' } - return scan([candidate(1)]) - }) - - expect(await handleRunningClaudeSessionsAfterSwitch(SWITCH)).toBe('show-confirmation') - expect(getClaudeAccountSwitchPrompt()).toBeNull() - }) - - it('keeps only the newer question when an older scan resolves last', async () => { - const older = Promise.withResolvers() - const newer = Promise.withResolvers() - vi.mocked(findClaudeSwitchSessions) - .mockReturnValueOnce(older.promise) - .mockReturnValueOnce(newer.promise) - const first = handleRunningClaudeSessionsAfterSwitch(SWITCH) - const second = handleRunningClaudeSessionsAfterSwitch({ - ...SWITCH, - before: SWITCH.after, - after: SWITCH.before - }) - - newer.resolve(scan([candidate(2)])) - expect(await second).toBe('handled') - older.resolve(scan([candidate(1)])) - expect(await first).toBe('handled') - - expect(getClaudeAccountSwitchPrompt()).toMatchObject({ - sessions: { onAccount: [expect.objectContaining({ ptyId: 'pty-2' })] }, - nextAccountLabel: 'account-a@example.com' - }) - }) -}) diff --git a/src/renderer/src/lib/renderer-app-platform.test.ts b/src/renderer/src/lib/renderer-app-platform.test.ts index 5a46beb2888..dea5fe06408 100644 --- a/src/renderer/src/lib/renderer-app-platform.test.ts +++ b/src/renderer/src/lib/renderer-app-platform.test.ts @@ -1,5 +1,5 @@ // @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { getRendererAppPlatform, resetRendererAppPlatformCacheForTests @@ -19,17 +19,6 @@ describe('getRendererAppPlatform', () => { resetRendererAppPlatformCacheForTests() }) - it('crosses the preload bridge once no matter how many renders ask', () => { - const get = vi.fn(() => ({ platform: 'darwin' as NodeJS.Platform })) - stubPlatformApi(get) - - for (let index = 0; index < 500; index += 1) { - expect(getRendererAppPlatform()).toBe('darwin') - } - - expect(get).toHaveBeenCalledTimes(1) - }) - // The web platform bridge arrives after boot; early user-agent guesses must not become session-long cache entries. it('does not cache the user-agent fallback', () => { // 'freebsd' is never a user-agent fallback answer, so the swap is unambiguous. diff --git a/src/renderer/src/lib/resume-stale-structured-agent-session.test.ts b/src/renderer/src/lib/resume-stale-structured-agent-session.test.ts deleted file mode 100644 index 8737dd554f3..00000000000 --- a/src/renderer/src/lib/resume-stale-structured-agent-session.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { useAppStore } from '@/store' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { structuredAgentSessionTabId } from '../../../shared/agent-session/view/structured-agent-session-projection' -import { resumeSleepingAgentSessionsForWorktree } from './agent-session/resume/resume-sleeping-agent-session' - -const initialAppStoreState = useAppStore.getState() -const WORKTREE_ID = 'stale-structured-worktree' -const SESSION_ID = 'structured-session-stale' -const LEAF_ID = '11111111-1111-4111-8111-111111111111' - -afterEach(() => { - useAppStore.setState(initialAppStoreState, true) -}) - -describe('stale structured sleeping session', () => { - it('clears the synthetic terminal projection without spawning', () => { - const tabId = structuredAgentSessionTabId(SESSION_ID) - const paneKey = makePaneKey(tabId, LEAF_ID) - const record: SleepingAgentSessionRecord = { - paneKey, - tabId, - worktreeId: WORKTREE_ID, - agent: 'codex', - providerSession: { key: 'session_id', id: SESSION_ID }, - prompt: 'continue', - state: 'working', - capturedAt: 1, - updatedAt: 1 - } - useAppStore.setState({ - tabsByWorktree: { [WORKTREE_ID]: [] }, - sleepingAgentSessionsByPaneKey: { [paneKey]: record } - } as never) - - expect(resumeSleepingAgentSessionsForWorktree(WORKTREE_ID)).toBe(0) - expect(useAppStore.getState().sleepingAgentSessionsByPaneKey[paneKey]).toBeUndefined() - expect(useAppStore.getState().pendingStartupByTabId).toEqual({}) - }) -}) diff --git a/src/renderer/src/lib/review-owner.test.ts b/src/renderer/src/lib/review-owner.test.ts deleted file mode 100644 index 8202756ff47..00000000000 --- a/src/renderer/src/lib/review-owner.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Repo } from '../../../shared/repo-types' -import { resolveReviewRepository } from './review-owner' -import { resolveExactWorktreeRoute } from './worktree-owner-route' -import '../runtime/source-control/forge/forge-credential-target' -import '../store/github/repositories/repository-routing' - -const proxy: Repo = { - id: 'project', - path: '/project', - displayName: 'Project', - badgeColor: 'blue', - addedAt: 1, - executionHostId: 'runtime:server', - connectionId: 'builder' -} -const row = { id: 'project::/worktree', repoId: 'project', hostId: 'ssh:builder' as const } - -describe('review repository evidence', () => { - it.each(['distinct', 'competing'] as const)( - 'does not re-enumerate a warmed %s repository snapshot as workspace count increases', - (mode) => { - let reads = 0 - const repos = Array.from({ length: 300 }, (_, i) => ({ - ...proxy, - executionHostId: `runtime:server-${i}` as const, - get id() { - reads++ - return mode === 'distinct' ? `project-${i}` : 'project-299' - } - })) - const workspace = { ...row, repoId: 'project-299' } - resolveReviewRepository(repos, workspace) - resolveExactWorktreeRoute({ repos }, workspace) - reads = 0 - for (let i = 0; i < 400; i++) { - expect(resolveReviewRepository(repos, workspace)).toBe( - mode === 'distinct' ? repos[299] : null - ) - expect(resolveExactWorktreeRoute({ repos }, workspace).kind).toBe( - mode === 'distinct' ? 'resolved' : 'ambiguous' - ) - } - expect(reads).toBeLessThan(400 * 4) - } - ) -}) diff --git a/src/renderer/src/lib/run-target-host-visibility.test.ts b/src/renderer/src/lib/run-target-host-visibility.test.ts deleted file mode 100644 index 4886256d938..00000000000 --- a/src/renderer/src/lib/run-target-host-visibility.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ExecutionHostRegistryEntry } from '../../../shared/execution-host/execution-host-registry-entry' -import { needsVisibleRunTargetHost } from './run-target-host-visibility' - -const hosts: ExecutionHostRegistryEntry[] = [ - { id: 'local', kind: 'local', label: 'Local Mac', detail: 'This computer', health: 'local' }, - { - id: 'runtime:vm-1', - kind: 'runtime', - label: 'app VM', - detail: 'Orca server', - health: 'available', - source: 'ephemeral-vm' - }, - { - id: 'runtime:build-box', - kind: 'runtime', - label: 'Build box', - detail: 'Orca server', - health: 'available', - source: 'manual' - } -] - -describe('needsVisibleRunTargetHost', () => { - it('holds Create only for a per-workspace VM target, which Run on never lists', () => { - const on = (hostId: 'local' | `runtime:${string}`) => ({ - status: 'ready' as const, - target: { hostId } - }) - expect(needsVisibleRunTargetHost(on('runtime:vm-1'), hosts, null)).toBe(true) - expect(needsVisibleRunTargetHost(on('runtime:build-box'), hosts, null)).toBe(false) - expect(needsVisibleRunTargetHost(on('local'), hosts, null)).toBe(false) - }) -}) diff --git a/src/renderer/src/lib/runtime-host-copy.test.ts b/src/renderer/src/lib/runtime-host-copy.test.ts deleted file mode 100644 index 0521132d144..00000000000 --- a/src/renderer/src/lib/runtime-host-copy.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { i18n } from '@/i18n/i18n' -import es from '@/i18n/locales/es.json' -import { describeRuntimeCompatBlock, getExecutionHostHealthLabel } from './runtime-host-copy' -import { describeRuntimeCompatBlock as describeRuntimeCompatBlockEnglish } from '../../../shared/protocol-compat' - -const originalLanguage = i18n.language - -afterEach(async () => { - await i18n.changeLanguage(originalLanguage) -}) - -describe('runtime host copy', () => { - it('resolves live labels and compatibility values in the renderer locale', async () => { - i18n.addResourceBundle('es', 'translation', es) - await i18n.changeLanguage('es') - expect(getExecutionHostHealthLabel('blocked', 'access-revoked')).toBe(es.runtime.health.repair) - expect(getExecutionHostHealthLabel('blocked')).toBe(es.runtime.health.update) - const verdict = { - kind: 'blocked', - reason: 'client-too-old', - clientProtocolVersion: 2, - serverProtocolVersion: 4, - requiredClientProtocolVersion: 3 - } as const - expect(describeRuntimeCompatBlock(verdict)).toBe( - es.runtime.compat.clientTooOld - .replace('{{clientProtocol}}', '2') - .replace('{{requiredProtocol}}', '3') - ) - expect(describeRuntimeCompatBlockEnglish(verdict)).toContain('Client protocol 2') - await i18n.changeLanguage('en') - expect(getExecutionHostHealthLabel('blocked', 'access-revoked')).toBe('Re-pair needed') - }) -}) diff --git a/src/renderer/src/lib/source-control/ai/source-control-agent-launch-picker.test.ts b/src/renderer/src/lib/source-control/ai/source-control-agent-launch-picker.test.ts index d19a09bc566..38def191301 100644 --- a/src/renderer/src/lib/source-control/ai/source-control-agent-launch-picker.test.ts +++ b/src/renderer/src/lib/source-control/ai/source-control-agent-launch-picker.test.ts @@ -608,32 +608,3 @@ it('replaces the full unaccepted extent, accepts once, and preserves promoted ch expect(reopened.delegated).toEqual(expect.arrayContaining(['model', 'effort'])) expect(agentPickerEffectiveChoices(entry, reopened).model).toBeUndefined() }) - -it('orders raw and control picks once and gives one-shot and sparse consumers the same choices', () => { - const selection = canonicalSourceControlActionSelection({ agentId: 'claude', agentArgs: '' }) - for (const edits of [ - [ - { kind: 'arguments', text: '--model sonnet --effort high --debug' }, - { kind: 'choice', patch: { model: 'opus' } } - ], - [ - { kind: 'choice', patch: { model: 'opus' } }, - { kind: 'arguments', text: '--model sonnet --effort high --debug' } - ] - ] satisfies AgentPickerEdit[][]) { - const draft = acceptAgentPickerArguments( - entry, - edits.reduce( - (value, edit) => applyAgentPickerEdit(entry, value, edit), - sourceControlPickerDraft(selection, entry, 'terminal') - ) - ) - const saved = project(applySourceControlPickerDraft(selection, entry, draft)) - const chat = agentPickerLaunchInputs({ ...draft, surface: 'chat' }, entry) - expect(saved.sessionOptions?.model).toBe(chat.sessionOptions?.model) - expect(saved.sessionOptions?.effort).toBe(chat.sessionOptions?.effort) - expect(saved.agentArgs).toBe('--debug') - expect(agentPickerLaunchInputs(draft, entry).agentArgs).toContain('--debug') - expect(draft.pendingArguments).toBeUndefined() - } -}) diff --git a/src/renderer/src/lib/text-generation-error-copy.test.ts b/src/renderer/src/lib/text-generation-error-copy.test.ts deleted file mode 100644 index 4655d4aa8b3..00000000000 --- a/src/renderer/src/lib/text-generation-error-copy.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { i18n } from '@/i18n/i18n' -import es from '@/i18n/locales/es.json' -import { textGenerationFailure } from '../../../shared/text-generation-failure-copy' -import { localizeTextGenerationResult, textGenerationErrorText } from './text-generation-error-copy' - -const originalLanguage = i18n.language -const errors = es.sourceControl.textGeneration.errors - -afterEach(async () => { - await i18n.changeLanguage(originalLanguage) -}) - -describe('textGenerationErrorText', () => { - it('localizes a coded failure and keeps the agent label and CLI output verbatim', async () => { - i18n.addResourceBundle('es', 'translation', es) - await i18n.changeLanguage('es') - const failed = textGenerationFailure('cliFailedWithDetail', { - label: 'Codex', - exitCode: 2, - detail: 'unauthorized {{label}}' - }) - expect(failed.error).toBe('Codex CLI command failed with code 2: unauthorized {{label}}') - expect(textGenerationErrorText(failed)).toBe( - errors.cliFailedWithDetail - .replace('{{label}}', 'Codex') - .replace('{{exitCode}}', '2') - .replace('{{detail}}', 'unauthorized {{label}}') - ) - expect( - localizeTextGenerationResult({ success: false, ...textGenerationFailure('noStagedChanges') }) - ).toEqual({ success: false, error: errors.noStagedChanges, errorCode: 'noStagedChanges' }) - }) -}) diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts b/src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts deleted file mode 100644 index a361afa410c..00000000000 --- a/src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import '../../../../../shared/constants' -import { useAppStore } from '@/store/index' - -import { activateAndRevealWorktree } from './worktree-activation' -import '../../web-runtime-worktree-terminal-after-wake' -import { resetWebSessionTabsSnapshotFreshnessForTests } from '@/runtime/web-session-tabs-sync/tracking-lifecycle' -import { resetWebRuntimeWakeTerminalRespawnForTests } from '@/runtime/hosted-terminals/restoration/web-runtime-wake-terminal-respawn' -import '@/runtime/web-session-tabs-sync/host-terminal-count-fixture' -import { - makeCreatedAgentWorktree as makeWorktree, - seedEmptyActivatableWorktree -} from '@/lib/workspace/activation/worktree-activation-created-agent.test-fixture' -import '../../../runtime/rpc/testing/runtime-environment-bridge-fixture' - -// Main's answer to the window's layout commands, as a switch-on build sends them. -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) - -const initialAppStoreState = useAppStore.getState() - -/** Activates and asserts a focusable tab appeared with no queued startup, returning its id. */ - -afterEach(() => { - delete (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ - vi.unstubAllGlobals() - resetWebSessionTabsSnapshotFreshnessForTests() - resetWebRuntimeWakeTerminalRespawnForTests() - useAppStore.setState(initialAppStoreState, true) -}) - -describe('activateAndRevealWorktree', () => { - it('does not relaunch the creation-time agent when reopening an empty worktree', () => { - const worktree = makeWorktree() - const { revealWorktreeInSidebar } = seedEmptyActivatableWorktree(worktree) - - const result = activateAndRevealWorktree(worktree.id) - const state = useAppStore.getState() - const reopenedTab = state.tabsByWorktree[worktree.id]?.[0] - - // A focusable surface still appears — it is just a plain shell, with no queued agent launch. - expect(result).toEqual({ primaryTabId: reopenedTab?.id }) - expect(reopenedTab).toBeDefined() - expect(state.pendingStartupByTabId[reopenedTab!.id]).toBeUndefined() - expect(revealWorktreeInSidebar).toHaveBeenCalledWith(worktree.id) - }) -}) diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts b/src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts deleted file mode 100644 index b71099c4435..00000000000 --- a/src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import { activateAndRevealWorktree } from './worktree-activation' - -import { - makeCreatedAgentWorktree as makeWorktree, - seedEmptyActivatableWorktree -} from '@/lib/workspace/activation/worktree-activation-created-agent.test-fixture' -import { registerWorktreeActivationReset } from './worktree-activation.test-fixture' - -// Main's answer to the window's layout commands, as a switch-on build sends them. -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) - -const initialAppStoreState = useAppStore.getState() - -registerWorktreeActivationReset() - -afterEach(() => { - vi.restoreAllMocks() - useAppStore.setState(initialAppStoreState, true) -}) - -const setup = { - runnerScriptPath: '/tmp/repo/.git/orca/setup-runner.sh', - envVars: { ORCA_WORKTREE_PATH: '/tmp/worktrees/wt-1' } -} - -// Returned setup scripts must not force Terminal 1 beside a new native chat. -describe('seeding beside a caller-provided chat surface', () => { - it('does not enqueue setup again when its consumed tab is reactivated', () => { - const worktree = makeWorktree() - seedEmptyActivatableWorktree(worktree) - activateAndRevealWorktree(worktree.id, { - providesInitialSurface: true, - notifyHostRuntime: false, - setup - }) - const state = useAppStore.getState() - const setupTab = state.tabsByWorktree[worktree.id]?.[0] - if (!setupTab) { - throw new Error('missing Setup tab') - } - expect(state.consumeTabStartupCommand(setupTab.id)?.command).toContain('setup-runner.sh') - activateAndRevealWorktree(worktree.id, { notifyHostRuntime: false }) - expect(useAppStore.getState().tabsByWorktree[worktree.id]).toHaveLength(1) - expect(useAppStore.getState().pendingStartupByTabId).toEqual({}) - }) -}) diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-comment-snippet.test.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-comment-snippet.test.ts deleted file mode 100644 index 6b0db05e48f..00000000000 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-comment-snippet.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { extractWorktreePaletteCommentSnippet } from './worktree-palette-comment-snippet' - -const EMOJI = '\u{1F680}' - -// isWellFormed alone also accepts deleted emoji; require a contiguous source span to catch dropped characters. -function expectContiguousSlice(text: string, comment: string): void { - const core = text.replace(/^\u2026/, '').replace(/\u2026$/, '') - expect(comment).toContain(core) -} - -describe('extractWorktreePaletteCommentSnippet', () => { - // CJK exhausts both 10-step whitespace scans; sweep emoji across cuts to cover either split surrogate half. - it('never splits a surrogate pair at the leading edge', () => { - let keptEmoji = 0 - for (let offset = 0; offset < 40; offset += 1) { - const comment = `${'词'.repeat(offset)}${EMOJI}${'词'.repeat(80 - offset)}目标${'词'.repeat(20)}` - const matchStart = comment.indexOf('目标') - const { text, matchRange } = extractWorktreePaletteCommentSnippet( - comment, - matchStart, - matchStart + '目标'.length - ) - expect(text.isWellFormed()).toBe(true) - expect(text.slice(matchRange.start, matchRange.end)).toBe('目标') - expectContiguousSlice(text, comment) - if (text.includes(EMOJI)) { - keptEmoji += 1 - } - } - // Require boundary iterations or dropping emoji every time would still pass the assertions above. - expect(keptEmoji).toBeGreaterThan(0) - }) - - it('never splits a surrogate pair at the trailing edge', () => { - let keptEmoji = 0 - for (let offset = 0; offset < 70; offset += 1) { - const comment = `${'词'.repeat(20)}目标${'词'.repeat(offset)}${EMOJI}${'词'.repeat(90 - offset)}` - const matchStart = comment.indexOf('目标') - const { text, matchRange } = extractWorktreePaletteCommentSnippet( - comment, - matchStart, - matchStart + '目标'.length - ) - expect(text.isWellFormed()).toBe(true) - expect(text.slice(matchRange.start, matchRange.end)).toBe('目标') - expectContiguousSlice(text, comment) - if (text.includes(EMOJI)) { - keptEmoji += 1 - } - } - expect(keptEmoji).toBeGreaterThan(0) - }) -}) diff --git a/src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-workspace-publication.test.ts b/src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-workspace-publication.test.ts deleted file mode 100644 index c76c08fbfc4..00000000000 --- a/src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-workspace-publication.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildMobileSessionTabSnapshots } from './mobile-session-snapshots' -import { makeState } from './testing/sync-runtime-graph-test-harness' -import type { AppState } from '../../store/types' - -describe('buildMobileSessionTabSnapshots', () => { - it('evicts a removed folder workspace from the snapshot cache', () => { - const folderWorkspaceId = 'cache-eviction-folder' - const folderKey = `folder:${folderWorkspaceId}` - const liveState = makeState({ - folderWorkspaces: [{ id: folderWorkspaceId } as AppState['folderWorkspaces'][number]], - tabsByWorktree: { - [folderKey]: [{ id: 'term-1', title: 'Terminal 1' }] - } as unknown as AppState['tabsByWorktree'] - }) - const removedState = makeState({ - folderWorkspaces: [], - tabsByWorktree: liveState.tabsByWorktree - }) - - const initial = buildMobileSessionTabSnapshots(liveState)[0]! - expect(buildMobileSessionTabSnapshots(removedState)).toEqual([]) - const restored = buildMobileSessionTabSnapshots(liveState)[0]! - - expect(restored.snapshotVersion).toBeGreaterThan(initial.snapshotVersion) - }) - - it('publishes a new instance identity when unchanged content is recreated', () => { - const worktree = { - id: 'wt-1', - instanceId: 'old-instance', - repoId: 'repo-1' - } - const base = makeState({ - worktreesByRepo: { 'repo-1': [worktree] } as unknown as AppState['worktreesByRepo'], - tabsByWorktree: { - 'wt-1': [{ id: 'term-1', title: 'Terminal 1' }] - } as unknown as AppState['tabsByWorktree'] - }) - const initial = buildMobileSessionTabSnapshots(base)[0]! - const recreated = { - ...base, - worktreesByRepo: { - 'repo-1': [{ ...worktree, instanceId: 'new-instance' }] - } as unknown as AppState['worktreesByRepo'] - } - - const next = buildMobileSessionTabSnapshots(recreated)[0]! - - expect(initial.worktreeInstanceId).toBe('old-instance') - expect(next.worktreeInstanceId).toBe('new-instance') - expect(next.snapshotVersion).toBeGreaterThan(initial.snapshotVersion) - }) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-drop-ipc.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-drop-ipc.test.ts deleted file mode 100644 index cb5bdde1d86..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-status-drop-ipc.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import './agent-status' -import { RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX } from './agent-status-pane-keyed-records' -import { createTestStore } from '../../testing/app-store-test-fixture' - -// Propagate renderer dismissal to main’s persisted hook cache or restart resurrects dismissed paneKeys. - -const originalWindow = (globalThis as { window?: unknown }).window - -beforeEach(() => { - vi.useFakeTimers() -}) - -afterEach(() => { - vi.useRealTimers() - if (originalWindow === undefined) { - delete (globalThis as { window?: unknown }).window - } else { - ;(globalThis as { window?: unknown }).window = originalWindow - } -}) - -function stubWindowApi(): { - drop: ReturnType - dropByTabPrefix: ReturnType -} { - const drop = vi.fn() - const dropByTabPrefix = vi.fn() - ;(globalThis as { window?: unknown }).window = { - api: { agentStatus: { drop, dropByTabPrefix } } - } - return { drop, dropByTabPrefix } -} - -describe('dropAgentStatusByTabPrefix -> IPC fan-out', () => { - it('FIFO-caps recentlyClosedAgentStatusTabIds so it cannot grow unbounded', () => { - stubWindowApi() - const store = createTestStore() - const cap = RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX - - for (let i = 0; i < cap + 5; i++) { - store.getState().dropAgentStatusByTabPrefix(`tab-${i}`) - } - - const closed = store.getState().recentlyClosedAgentStatusTabIds - expect(Object.keys(closed)).toHaveLength(cap) - // Evict oldest closed-tab markers; events beyond the cap cannot still arrive. - expect(closed['tab-0']).toBeUndefined() - expect(closed['tab-4']).toBeUndefined() - expect(closed[`tab-${cap + 4}`]).toBe(true) - }) -}) diff --git a/src/renderer/src/store/slices/tabs/tabs-close-dangling-group.test.ts b/src/renderer/src/store/slices/tabs/tabs-close-dangling-group.test.ts deleted file mode 100644 index 67a7c0e5d19..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-close-dangling-group.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createTabsSliceMockApi } from './tabs-slice-test-harness' -import { createTestStore } from '../../testing/app-store-test-fixture' -import { drawTabsFromMain, type TabsDrawnFromMain } from './tabs-drawn-from-main.test-fixture' - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -createTabsSliceMockApi() - -const WT = 'repo1::/tmp/feature' -const NO_MAIN: TabsDrawnFromMain = { settle: async () => {}, close: () => {} } - -describe('closeUnifiedTab with a missing group record (#11308)', () => { - let store: ReturnType - let main: TabsDrawnFromMain - - beforeEach(() => { - store = createTestStore() - }) - - afterEach(() => main.close()) - - it.each(['terminal', 'editor'] as const)('still removes a %s tab', async (contentType) => { - const kept = store.getState().createUnifiedTab(WT, contentType, { id: `${contentType}-kept` }) - const closing = store.getState().createUnifiedTab(WT, contentType, { id: `${contentType}-x` }) - // Only an editor tab's close goes to main first; a terminal's (rowless here) closes as today. - main = contentType === 'editor' ? await drawTabsFromMain(store) : NO_MAIN - store.setState({ groupsByWorktree: { [WT]: [] } }) - - const result = store.getState().closeUnifiedTab(closing.id) - // A layout-owner build closes an editor tab in main; its frame drops it. - await main.settle() - - expect(result).toEqual({ closedTabId: closing.id, wasLastTab: false, worktreeId: WT }) - expect(store.getState().unifiedTabsByWorktree[WT]?.map((tab) => tab.id)).toEqual([kept.id]) - }) -}) diff --git a/src/renderer/src/store/terminals/degraded-repo-hydration.test.ts b/src/renderer/src/store/terminals/degraded-repo-hydration.test.ts deleted file mode 100644 index 676ac16aa9d..00000000000 --- a/src/renderer/src/store/terminals/degraded-repo-hydration.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { expect, it, vi } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status' -import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('@/lib/agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } -}) - -// @ts-expect-error -- mocked browser preload API -globalThis.window = { api: {} } - -import { - buildWorkspaceSessionPayload, - shouldPersistWorkspaceSession -} from '@/lib/workspace/persistence/workspace-session' -import { createTestStore } from '../testing/app-store-test-fixture' -import { makeTab } from './terminal-tab.test-fixture' -import { makeWorktree } from '../slices/worktrees/worktree.test-fixture' - -const WORKTREE_ID = 'repo1::/path/degraded' -const TERMINAL_ID = 'terminal-degraded' -const EDITOR_FILE_ID = '/path/degraded/src/App.tsx' -const BROWSER_ID = 'browser-degraded' -const GROUP_ID = 'group-degraded' - -function makeBrowserTab(): BrowserWorkspace { - return { - id: BROWSER_ID, - worktreeId: WORKTREE_ID, - url: 'https://example.com', - title: 'Example', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 3 - } -} - -function makeDegradedRepoSession(): WorkspaceSessionState { - return { - ...getDefaultWorkspaceSession(), - activeRepoId: 'repo1', - activeWorktreeId: WORKTREE_ID, - activeTabId: TERMINAL_ID, - tabsByWorktree: { - [WORKTREE_ID]: [makeTab({ id: TERMINAL_ID, worktreeId: WORKTREE_ID })] - }, - openFilesByWorktree: { - [WORKTREE_ID]: [ - { - filePath: EDITOR_FILE_ID, - relativePath: 'src/App.tsx', - worktreeId: WORKTREE_ID, - language: 'typescript' - } - ] - }, - activeFileIdByWorktree: { [WORKTREE_ID]: EDITOR_FILE_ID }, - browserTabsByWorktree: { [WORKTREE_ID]: [makeBrowserTab()] }, - activeBrowserTabIdByWorktree: { [WORKTREE_ID]: BROWSER_ID }, - activeTabTypeByWorktree: { [WORKTREE_ID]: 'browser' }, - unifiedTabs: { - [WORKTREE_ID]: [ - { - id: TERMINAL_ID, - entityId: TERMINAL_ID, - groupId: GROUP_ID, - worktreeId: WORKTREE_ID, - contentType: 'terminal', - label: 'Terminal', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }, - { - id: EDITOR_FILE_ID, - entityId: EDITOR_FILE_ID, - groupId: GROUP_ID, - worktreeId: WORKTREE_ID, - contentType: 'editor', - label: 'App.tsx', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - }, - { - id: BROWSER_ID, - entityId: BROWSER_ID, - groupId: GROUP_ID, - worktreeId: WORKTREE_ID, - contentType: 'browser', - label: 'Example', - customLabel: null, - color: null, - sortOrder: 2, - createdAt: 3 - } - ] - }, - tabGroups: { - [WORKTREE_ID]: [ - { - id: GROUP_ID, - worktreeId: WORKTREE_ID, - activeTabId: BROWSER_ID, - tabOrder: [TERMINAL_ID, EDITOR_FILE_ID, BROWSER_ID], - recentTabIds: [TERMINAL_ID, EDITOR_FILE_ID, BROWSER_ID] - } - ] - }, - activeGroupIdByWorktree: { [WORKTREE_ID]: GROUP_ID } - } -} - -function makeTerminalFreeDegradedRepoSession(): WorkspaceSessionState { - const session = makeDegradedRepoSession() - session.activeTabId = null - session.tabsByWorktree = {} - session.unifiedTabs![WORKTREE_ID] = session.unifiedTabs![WORKTREE_ID].filter( - (tab) => tab.contentType !== 'terminal' - ) - session.tabGroups![WORKTREE_ID] = session.tabGroups![WORKTREE_ID].map((group) => ({ - ...group, - tabOrder: [EDITOR_FILE_ID, BROWSER_ID], - recentTabIds: [EDITOR_FILE_ID, BROWSER_ID] - })) - return session -} - -function hydrateWithRepoScan( - store: ReturnType, - session: WorkspaceSessionState, - authoritative = false -): void { - store.setState({ - repos: [{ id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }], - worktreesByRepo: { repo1: [] }, - detectedWorktreesByRepo: { - repo1: { - repoId: 'repo1', - authoritative, - source: authoritative ? 'git' : 'metadata-fallback', - worktrees: [] - } - } - }) - store.getState().hydrateWorkspaceSession(session) - store.getState().hydrateTabsSession(session) - store.getState().hydrateEditorSession(session) - store.getState().hydrateBrowserSession(session) -} - -it('keeps tab, editor, and browser chrome through degraded hydration and persistence', () => { - const firstStore = createTestStore() - hydrateWithRepoScan(firstStore, makeDegradedRepoSession()) - firstStore.setState({ workspaceSessionReady: true }) - firstStore.getState().setHydrationSucceeded(true) - expect(shouldPersistWorkspaceSession(firstStore.getState())).toBe(true) - - const persisted = buildWorkspaceSessionPayload(firstStore.getState()) - const restoredStore = createTestStore() - hydrateWithRepoScan(restoredStore, persisted) - - const restored = restoredStore.getState() - expect(restored.unifiedTabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - TERMINAL_ID, - EDITOR_FILE_ID, - BROWSER_ID - ]) - expect(restored.openFiles.map((file) => file.id)).toEqual([EDITOR_FILE_ID]) - expect(restored.browserTabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([BROWSER_ID]) -}) - -it('keeps a terminal-free degraded workspace selected through hydration and persistence', () => { - const firstStore = createTestStore() - hydrateWithRepoScan(firstStore, makeTerminalFreeDegradedRepoSession()) - - const first = firstStore.getState() - expect(first.activeWorktreeId).toBe(WORKTREE_ID) - expect(first.activeTabType).toBe('browser') - - firstStore.setState({ workspaceSessionReady: true }) - firstStore.getState().setHydrationSucceeded(true) - const persisted = buildWorkspaceSessionPayload(firstStore.getState()) - const restoredStore = createTestStore() - hydrateWithRepoScan(restoredStore, persisted) - - const restored = restoredStore.getState() - expect(restored.activeWorktreeId).toBe(WORKTREE_ID) - expect(restored.unifiedTabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([ - EDITOR_FILE_ID, - BROWSER_ID - ]) - expect(restored.activeTabType).toBe('browser') -}) - -it('keeps chrome when a non-authoritative fallback lists only some of the repo worktrees', () => { - const store = createTestStore() - // Nonempty SSH metadata fallback can still omit ambiguous/hidden rows; partial lists prove no deletion. - const sibling = makeWorktree({ - id: 'repo1::/path/sibling', - repoId: 'repo1', - path: '/path/sibling' - }) - store.setState({ - repos: [{ id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }], - worktreesByRepo: { repo1: [sibling] }, - detectedWorktreesByRepo: { - repo1: { - repoId: 'repo1', - authoritative: false, - source: 'metadata-fallback', - worktrees: [] - } - } - }) - const session = makeDegradedRepoSession() - store.getState().hydrateWorkspaceSession(session) - store.getState().hydrateTabsSession(session) - store.getState().hydrateEditorSession(session) - store.getState().hydrateBrowserSession(session) - - const state = store.getState() - expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([TERMINAL_ID]) - expect(state.openFiles.map((file) => file.id)).toEqual([EDITOR_FILE_ID]) - expect(state.browserTabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([BROWSER_ID]) -}) - -it('drops terminal-free chrome when an authoritative scan proves deletion', () => { - const store = createTestStore() - hydrateWithRepoScan(store, makeTerminalFreeDegradedRepoSession(), true) - - const state = store.getState() - expect(state.activeWorktreeId).toBeNull() - expect(state.unifiedTabsByWorktree[WORKTREE_ID]).toBeUndefined() - expect(state.openFiles).toEqual([]) - expect(state.browserTabsByWorktree[WORKTREE_ID]).toBeUndefined() -}) diff --git a/src/renderer/src/store/terminals/terminal-no-op-subscriber.test.ts b/src/renderer/src/store/terminals/terminal-no-op-subscriber.test.ts deleted file mode 100644 index 74c3b25dc2e..00000000000 --- a/src/renderer/src/store/terminals/terminal-no-op-subscriber.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - flushTerminalInputActivity, - resetTerminalInputActivityCoalescingForTests -} from '@/lib/terminal-input-activity-coalescing' -import { createTestStore } from '../testing/app-store-test-fixture' - -afterEach(resetTerminalInputActivityCoalescingForTests) - -describe('terminal no-op subscriber budget', () => { - it('retains draft generations when stale resolutions arrive without notifying', () => { - const store = createTestStore() - const draft = { tabId: 'tab', agent: 'codex', text: 'new draft', createdAt: 2 } as const - store.getState().seedNativeChatLaunchDraft(draft) - const before = store.getState() - const listener = vi.fn() - store.subscribe(listener) - - store.getState().resolveNativeChatLaunchDraft('tab', { ...draft, createdAt: 1 }) - store.getState().resolveNativeChatLaunchDraft('tab', { ...draft, text: 'old draft' }) - - expect(listener).not.toHaveBeenCalled() - expect(store.getState()).toBe(before) - expect(store.getState().nativeChatLaunchDraftByTabId.tab).toBe(draft) - }) - - it('drops a trailing input flush after pane teardown without publishing', () => { - const store = createTestStore() - store.getState().recordTerminalInput('tab:leaf', 1000) - store.getState().recordTerminalInput('tab:leaf', 1001) - store.setState({ lastTerminalInputAtByPaneKey: {} }) - const before = store.getState() - const listener = vi.fn() - store.subscribe(listener) - - flushTerminalInputActivity() - - expect(listener).not.toHaveBeenCalled() - expect(store.getState()).toBe(before) - expect(store.getState().lastTerminalInputAtByPaneKey['tab:leaf']).toBeUndefined() - }) -}) diff --git a/src/renderer/src/store/terminals/terminal-startup-queue-restart.test.ts b/src/renderer/src/store/terminals/terminal-startup-queue-restart.test.ts deleted file mode 100644 index 48184a49c3c..00000000000 --- a/src/renderer/src/store/terminals/terminal-startup-queue-restart.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseWorkspaceSession } from '../../../../shared/workspace-session/workspace-session-schema' -import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session' -import { createTestStore, seedStore } from '@/store/testing/app-store-test-fixture' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' - -const WORKTREE_ID = 'repo1::/wt-1' -const STARTUP_COMMAND = "claude '--dangerously-skip-permissions'" - -function seededStore() { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/wt-1' })] - } - }) - return store -} - -// Pin baseline B6/C2 D-b: queued startup for never-mounted tab is not persisted; restart restores a plain shell without launch-record lookup. -describe('queued tab startup across an app restart on main', () => { - it('persists the agent tab but not its queued startup command', () => { - const before = seededStore() - const tab = before.getState().createTab(WORKTREE_ID, undefined, undefined, { - launchAgent: 'claude' - }) - before.getState().queueTabStartupCommand(tab.id, { - command: STARTUP_COMMAND, - launchConfig: { - agentCommand: STARTUP_COMMAND, - agentArgs: '--dangerously-skip-permissions', - agentEnv: {} - } - }) - expect(before.getState().pendingStartupByTabId[tab.id]?.command).toBe(STARTUP_COMMAND) - - const payload = buildWorkspaceSessionPayload(before.getState()) - const written = JSON.stringify(payload) - expect(written).not.toContain(STARTUP_COMMAND) - expect(written).not.toContain('pendingStartup') - - const parsed = parseWorkspaceSession(JSON.parse(written)) - expect(parsed.ok).toBe(true) - if (!parsed.ok) { - return - } - const after = seededStore() - after.getState().hydrateWorkspaceSession(parsed.value) - - // The tab comes back as the agent's tab with no PTY and nothing queued, so its pane spawns a shell. - expect(after.getState().pendingStartupByTabId).toEqual({}) - expect(after.getState().tabsByWorktree[WORKTREE_ID]).toEqual([ - expect.objectContaining({ id: tab.id, launchAgent: 'claude', ptyId: null }) - ]) - }) -}) diff --git a/src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts b/src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts deleted file mode 100644 index 7bbad57c06b..00000000000 --- a/src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createTerminalTabOwnerIndex } from './terminal-tab-owner-index' - -describe('terminal tab owner index', () => { - it('updates added, removed and moved ownership buckets', () => { - const stableBucket = [{ id: 'stable-tab' }] - const sourceBucket = [{ id: 'moving-tab' }] - const removedBucket = [{ id: 'removed-tab' }] - const index = createTerminalTabOwnerIndex() - - index.getOwners({ stable: stableBucket, source: sourceBucket, removed: removedBucket }) - const owners = index.getOwners({ - stable: stableBucket, - source: [], - destination: [{ id: 'moving-tab' }], - added: [{ id: 'added-tab' }] - }) - - expect(owners.get('stable-tab')).toBe('stable') - expect(owners.get('moving-tab')).toBe('destination') - expect(owners.get('added-tab')).toBe('added') - expect(owners.has('removed-tab')).toBe(false) - }) - - it('keeps owner lookup valid after a metadata-only bucket replacement', () => { - const initial = { - 'wt-0': [{ id: 'tab-0', title: 'Initial title' }], - 'wt-1': [{ id: 'tab-1', title: 'Initial title' }] - } - const index = createTerminalTabOwnerIndex() - index.getOwners(initial) - const next = { ...initial, 'wt-1': [{ id: 'tab-1', title: 'Changed title' }] } - index.adoptMetadataOnlyBucketReplacements(initial, next, ['wt-1']) - - const warmOwners = index.getOwners(next) - - expect(warmOwners.get('tab-1')).toBe('wt-1') - }) - - it('preserves last-wins object order for duplicate ids when only outer keys reorder', () => { - const firstBucket = [{ id: 'duplicate-tab' }, { id: 'duplicate-tab' }] - const secondBucket = [{ id: 'duplicate-tab' }] - const index = createTerminalTabOwnerIndex() - - expect(index.getOwner({ first: firstBucket, second: secondBucket }, 'duplicate-tab')).toBe( - 'second' - ) - - expect(index.getOwner({ second: secondBucket, first: firstBucket }, 'duplicate-tab')).toBe( - 'first' - ) - }) -}) diff --git a/src/renderer/src/store/terminals/worktree-sleep-intent-lifecycle.test.ts b/src/renderer/src/store/terminals/worktree-sleep-intent-lifecycle.test.ts deleted file mode 100644 index 91f6b9d87fd..00000000000 --- a/src/renderer/src/store/terminals/worktree-sleep-intent-lifecycle.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import * as intent from '@/lib/worktree-sleep-intent' -import '../slices/worktrees/teardown/worktree-purge-state' -import { createTestStore, seedStore } from '../testing/app-store-test-fixture' -import { makeWorktree } from '../slices/worktrees/worktree.test-fixture' -import { createStoreCascadesMockApi } from '../testing/app-store-cascade-api.test-fixture' -import { resetStructuredAgentSessionReadOwnersForTests } from '@/components/native-chat/session/structured/read/structured-agent-session-read-owner-registry' - -const { clearWorktreeSleepIntent, hasWorktreeSleepIntent, markWorktreeSleepIntent } = intent -const WORKTREE_ID = 'repo1::/path/wt1' -const FOLDER_KEY = 'folder:folder-1' - -createStoreCascadesMockApi() - -function seedWorktree(store: ReturnType): void { - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/path/wt1' })] - }, - refreshGitHubForWorktree: vi.fn(), - refreshGitHubForWorktreeIfStale: vi.fn() - }) -} - -// Sleep intent keeps mounted panes cold after teardown; every wake route must release it or PTYs stay cold and exits cease counting as activity (#10205). -describe('worktree sleep intent lifecycle', () => { - beforeEach(() => { - clearWorktreeSleepIntent(WORKTREE_ID) - clearWorktreeSleepIntent(FOLDER_KEY) - resetStructuredAgentSessionReadOwnersForTests() - }) - - it('ignores a PTY bind that lands while the sleep teardown is in flight', async () => { - const store = createTestStore() - seedWorktree(store) - const tab = store.getState().createTab(WORKTREE_ID, undefined, undefined, { activate: false }) - markWorktreeSleepIntent(WORKTREE_ID) - const woke = vi.fn() - intent.onWorktreeSleepIntentCleared(WORKTREE_ID, woke) - - await intent.withWorktreeSleepTeardown(WORKTREE_ID, async () => { - store.getState().updateTabPtyId(tab.id, 'pty-late-spawn') - }) - - expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(true) - expect(woke).not.toHaveBeenCalled() - store.getState().updateTabPtyId(tab.id, 'pty-after-teardown') - expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(false) - }) -}) diff --git a/src/renderer/src/web/preload-api/web-speech-api.ts b/src/renderer/src/web/preload-api/web-speech-api.ts index 2af2e654279..f90437d21ee 100644 --- a/src/renderer/src/web/preload-api/web-speech-api.ts +++ b/src/renderer/src/web/preload-api/web-speech-api.ts @@ -16,10 +16,9 @@ import { createNonSecureContextUuid } from '../../../../shared/non-secure-contex import { errorMessage } from '../../../../shared/error-message' import { callRuntimeResult } from './web-runtime-calls' import { withTimeout } from '../../../../shared/promise-timeout-fallback' +import { pairedDictationFinishTimeoutMs } from '../../../../shared/dictation-finish-deadlines' const MAX_CHUNK_SAMPLES = MAX_DICTATION_AUDIO_CHUNK_BYTES / PCM_BYTES_PER_SAMPLE -// Matches the phone: a long recording can take a while to transcribe on the host. -const FINISH_TIMEOUT_MS = 75_000 // A slow link can leave a backlog of chunks behind Stop; past this, keep the text so far instead. const STOP_DRAIN_TIMEOUT_MS = 10_000 @@ -28,6 +27,7 @@ type HostDictation = { dictationId: string seq: number sampleRate: number + sentAudioSeconds: number pending: Float32Array[] sending: Promise | null failed: boolean @@ -116,12 +116,14 @@ export function createWebSpeechApi(): Pick< const sendPendingAudio = async (dictation: HostDictation): Promise => { while (dictation.pending.length > 0 && !dictation.failed) { try { + const audio = takePendingAudio(dictation) + dictation.sentAudioSeconds += audio.length / dictation.sampleRate const reply = await callRuntimeResult<{ text?: string audioLimitReached?: boolean }>('speech.dictation.chunk', { dictationId: dictation.dictationId, - audioBase64: encodePcm16Base64(takePendingAudio(dictation)), + audioBase64: encodePcm16Base64(audio), sampleRate: dictation.sampleRate, seq: dictation.seq++ }) @@ -153,6 +155,7 @@ export function createWebSpeechApi(): Pick< dictationId: `web-${createNonSecureContextUuid()}`, seq: 0, sampleRate: 0, + sentAudioSeconds: 0, pending: [], sending: null, failed: false, @@ -216,7 +219,7 @@ export function createWebSpeechApi(): Pick< const { text } = await callRuntimeResult<{ text: string }>( 'speech.dictation.finish', { dictationId: dictation.dictationId }, - FINISH_TIMEOUT_MS + pairedDictationFinishTimeoutMs(dictation.sentAudioSeconds) ) if (text) { emit(finalListeners, { sessionId, text }) diff --git a/src/renderer/src/web/preload-api/web-ui-compact-notice.test.ts b/src/renderer/src/web/preload-api/web-ui-compact-notice.test.ts deleted file mode 100644 index ba462d6b708..00000000000 --- a/src/renderer/src/web/preload-api/web-ui-compact-notice.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { getDefaultUIState } from '../../../../shared/constants' -import { UiUpdateFields } from '../../../../shared/rpc-contract/client-ui-params' -import { createUIStore } from '../../store/slices/ui/ui-slice-test-harness' -import { createWebUiApi } from './web-ui-api' - -const runtime = vi.hoisted(() => ({ call: vi.fn(), id: 'new' })) -vi.mock('./web-runtime-calls', () => ({ callRuntimeResult: runtime.call })) -vi.mock('./web-runtime-session', () => ({ - webRuntimeState: { activeEnvironment: null }, - requireActiveEnvironmentOrNull: () => ({ id: runtime.id }) -})) - -beforeEach(() => { - localStorage.clear() - runtime.call.mockReset() - runtime.id = 'new' -}) -afterEach(() => vi.unstubAllGlobals()) - -it.each(['verbose', 'compact'] as const)( - 'saves %s to an older host after caching a pending notice from a newer host', - async (mode) => { - const ui = createWebUiApi() - runtime.call.mockResolvedValue({ - ui: { ...getDefaultUIState(), statusBarCompactChangeNoticeDismissed: false } - }) - expect((await ui.get()).statusBarCompactChangeNoticeDismissed).toBe(false) - - runtime.id = 'old' - const oldHostSchema = UiUpdateFields.omit({ statusBarCompactChangeNoticeDismissed: true }) - const olderUI = getDefaultUIState() - delete olderUI.statusBarCompactChangeNoticeDismissed - runtime.call.mockImplementation(async (method: string, params: unknown) => { - if (method === 'ui.set') { - Object.assign(olderUI, oldHostSchema.parse(params)) - } - return { ui: olderUI } - }) - const hydrated = await ui.get() - expect(hydrated.statusBarCompactChangeNoticeDismissed).toBe(true) - - const store = createUIStore() - vi.stubGlobal('window', { localStorage, api: { ui } }) - store.getState().hydratePersistedUI(hydrated) - store.getState().setStatusBarUsageMode(mode) - - expect(runtime.call).toHaveBeenLastCalledWith('ui.set', { statusBarUsageMode: mode }, 15_000) - expect(olderUI.statusBarUsageMode).toBe(mode) - expect((await ui.get()).statusBarUsageMode).toBe(mode) - } -) diff --git a/src/renderer/src/web/web-insecure-origin-pairing.test.ts b/src/renderer/src/web/web-insecure-origin-pairing.test.ts deleted file mode 100644 index ed336658743..00000000000 --- a/src/renderer/src/web/web-insecure-origin-pairing.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' - -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) - -const offer = { - v: PAIRING_OFFER_VERSION, - endpoint: 'ws://100.108.226.109:6768', - deviceToken: 'pairing-code', - publicKeyB64: 'host-key' -} as const - -// A fresh module graph is what a page reload gives the web bundle: no in-memory pairing survives. -async function loadWebClient() { - vi.resetModules() - const support = await import('./web-device-key-support') - support.setWebDeviceKeySupportForTests('token-insecure-origin') - return { - environment: await import('./web-runtime-environment'), - credentials: await import('./preload-api/web-runtime-credentials'), - guidance: await import('./web-pairing-security-guidance') - } -} - -describe('a plain-http page on another machine (LAN or Tailscale)', () => { - beforeEach(() => { - const items = new Map() - vi.stubGlobal('window', { - localStorage: { - getItem: (key: string) => items.get(key) ?? null, - setItem: (key: string, value: string) => items.set(key, value), - removeItem: (key: string) => items.delete(key) - } - }) - }) - afterEach(() => vi.unstubAllGlobals()) - - it('stays paired across a reload and signs in with the stored pairing code', async () => { - const before = await loadWebClient() - const paired = before.environment.createStoredWebRuntimeEnvironment({ name: 'Desk', offer }) - expect(paired.sessionOnly).toBeUndefined() - before.environment.saveStoredWebRuntimeEnvironment(paired) - - const after = await loadWebClient() - const restored = after.environment.readStoredWebRuntimeEnvironment() - expect(restored).toMatchObject({ id: paired.id, endpoints: [{ deviceToken: 'pairing-code' }] }) - const source = after.credentials.webRuntimeCredentialFor(restored!, { - forgetStoredToken: vi.fn(), - forgetPairing: vi.fn() - }) - expect(source.nextPlan(true)).toEqual({ kind: 'legacy-token', deviceToken: 'pairing-code' }) - }) -}) diff --git a/src/shared/dictation-finish-deadlines.ts b/src/shared/dictation-finish-deadlines.ts new file mode 100644 index 00000000000..e355e364d1b --- /dev/null +++ b/src/shared/dictation-finish-deadlines.ts @@ -0,0 +1,24 @@ +// Cloud uploads are one 16 kHz 16-bit mono WAV, capped at 10 minutes per dictation. +export const CLOUD_TRANSCRIPTION_SAMPLE_RATE = 16_000 +export const MAX_CLOUD_TRANSCRIPTION_SECONDS = 10 * 60 +const WAV_HEADER_BYTES = 44 +// Room to answer plus the upload time of the WAV at 1 Mbit/s (125 bytes per ms). +const CLOUD_RESPONSE_ALLOWANCE_MS = 30_000 +const UPLOAD_BYTES_PER_MS = 125 + +export const LOCAL_DICTATION_STOP_TIMEOUT_MS = 60_000 +// The host's answer still has to cross the network after its own deadline. +const PAIRED_CLIENT_REPLY_MARGIN_MS = 15_000 + +/** How long the host lets a cloud upload of this many 16 kHz samples run before failing it. */ +export function cloudTranscriptionTimeoutMs(audioSamples: number): number { + const wavBytes = WAV_HEADER_BYTES + audioSamples * 2 + return CLOUD_RESPONSE_ALLOWANCE_MS + Math.ceil(wavBytes / UPLOAD_BYTES_PER_MS) +} + +/** A paired phone or browser waits out whichever deadline the host applies to this much audio. */ +export function pairedDictationFinishTimeoutMs(audioSeconds: number): number { + const seconds = Math.min(audioSeconds, MAX_CLOUD_TRANSCRIPTION_SECONDS) + const cloudMs = cloudTranscriptionTimeoutMs(Math.ceil(seconds * CLOUD_TRANSCRIPTION_SAMPLE_RATE)) + return Math.max(LOCAL_DICTATION_STOP_TIMEOUT_MS, cloudMs) + PAIRED_CLIENT_REPLY_MARGIN_MS +} diff --git a/src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts b/src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts index cd1f769c108..70813875a34 100644 --- a/src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts +++ b/src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from 'vitest' import { pairToolBlocks, type NativeChatToolPair } from './native-chat-tool-pairs' -import type { - NativeChatBlock, - NativeChatToolCallBlock, - NativeChatToolResultBlock -} from '../native-chat-types' +import type { NativeChatToolCallBlock, NativeChatToolResultBlock } from '../native-chat-types' function call(callId?: string): NativeChatToolCallBlock { return { type: 'tool-call', name: 'Bash', input: {}, ...(callId !== undefined ? { callId } : {}) } @@ -25,157 +21,7 @@ function expectSameReferences( }) } -function countedCalls(count: number): { - calls: NativeChatToolCallBlock[] - reads: () => number -} { - let reads = 0 - const calls = Array.from({ length: count }, (_, index): NativeChatToolCallBlock => ({ - type: 'tool-call', - name: 'Bash', - input: {}, - get callId() { - reads += 1 - return `call-${index}` - } - })) - return { calls, reads: () => reads } -} - -function countQueueMovement(blocks: readonly NativeChatBlock[]): { - pairs: NativeChatToolPair[] - movedSlots: number -} { - const originalSplice = Array.prototype.splice - const originalShift = Array.prototype.shift - let movedSlots = 0 - Array.prototype.splice = function ( - this: unknown[], - requestedIndex: number, - deleteCount?: number, - ...items: unknown[] - ) { - if (arguments.length === 0) { - return originalSplice.call(this, 0, 0) - } - const requestedStart = Math.trunc(requestedIndex) || 0 - const start = - requestedStart < 0 - ? Math.max(0, this.length + requestedStart) - : Math.min(this.length, requestedStart) - const removed = - arguments.length < 2 - ? this.length - start - : Math.min(this.length - start, Math.max(0, Math.trunc(deleteCount ?? 0) || 0)) - if (removed !== items.length) { - movedSlots += this.length - start - removed - } - return originalSplice.call(this, requestedIndex, removed, ...items) - } - Array.prototype.shift = function (this: unknown[]) { - movedSlots += Math.max(0, this.length - 1) - return originalShift.call(this) - } - try { - return { pairs: pairToolBlocks(blocks), movedSlots } - } finally { - Array.prototype.shift = originalShift - Array.prototype.splice = originalSplice - } -} - -describe('tool pairing lookup budget', () => { - it.each(['positional', 'named', 'duplicate'] as const)( - 'removes %s completions without quadratic queue movement', - (kind) => { - const count = 2048 - const idOf = (index: number): string | undefined => - kind === 'positional' ? undefined : kind === 'duplicate' ? 'same' : `call-${index}` - const calls = Array.from({ length: count }, (_, index) => call(idOf(index))) - const results = Array.from({ length: count }, (_, index) => result(idOf(index))) - const blocks = [...calls, ...results] - const measured = countQueueMovement(blocks) - expectSameReferences( - measured.pairs, - calls.map((pending, index) => ({ call: pending, result: results[index] })) - ) - expect(measured.movedSlots).toBeLessThanOrEqual(count * 3) - } - ) - - it.each([64, 512, 2048])( - 'looks up named results in linear work for %i calls answered in reverse order', - (count) => { - const fixture = countedCalls(count) - const results = Array.from({ length: count }, (_, index) => result(`call-${index}`)) - const pairs = pairToolBlocks([...fixture.calls, ...results.toReversed()]) - const lookupReads = fixture.reads() - expect(pairs).toHaveLength(count) - pairs.forEach((pair, index) => { - expect(pair.call).toBe(fixture.calls[index]) - expect(pair.result).toBe(results[index]) - }) - expect(lookupReads).toBeLessThanOrEqual(count * 3) - } - ) - - it.each([64, 512, 2048])( - 'keeps later named completions linear behind %i calls that emitted no result', - (count) => { - const fixture = countedCalls(count) - const laterCalls = Array.from({ length: count }, (_, index) => call(`later-${index}`)) - const results = Array.from({ length: count }, (_, index) => result(`later-${index}`)) - const pairs = pairToolBlocks([ - ...fixture.calls, - ...laterCalls.flatMap((laterCall, index) => [laterCall, results[index]!]) - ]) - const lookupReads = fixture.reads() - expect(pairs).toHaveLength(count * 2) - fixture.calls.forEach((pendingCall, index) => { - expect(pairs[index]?.call).toBe(pendingCall) - expect(pairs[index]?.result).toBeUndefined() - expect(pairs[count + index]?.call).toBe(laterCalls[index]) - expect(pairs[count + index]?.result).toBe(results[index]) - }) - expect(lookupReads).toBeLessThanOrEqual(count * 3) - } - ) - - it.each([64, 512, 2048])( - 'keeps unmatched named results linear behind %i pending calls', - (count) => { - const fixture = countedCalls(count) - const results = Array.from({ length: count }, (_, index) => result(`missing-${index}`)) - const pairs = pairToolBlocks([...fixture.calls, ...results]) - const lookupReads = fixture.reads() - expect(pairs).toHaveLength(count * 2) - results.forEach((unmatched, index) => { - expect(pairs[count + index]?.call).toBeUndefined() - expect(pairs[count + index]?.result).toBe(unmatched) - }) - expect(lookupReads).toBeLessThanOrEqual(count * 3) - } - ) -}) - describe('tool pairing identity and ordering', () => { - it('indexes missing named answers only once when every pending call has no ID', () => { - let reads = 0 - const count = 2048 - const calls: NativeChatToolCallBlock[] = Array.from({ length: count }, () => ({ - type: 'tool-call', - name: 'Bash', - input: {}, - get callId() { - reads += 1 - return undefined - } - })) - const results = Array.from({ length: count }, () => result('missing')) - expect(pairToolBlocks([...calls, ...results])).toHaveLength(count * 2) - expect(reads).toBeLessThanOrEqual(count * 3) - }) - it('matches repeated and empty IDs FIFO while positional results consume the oldest call', () => { const calls = [call('same'), call(''), call('same'), call(), call('same')] const results = [result('same'), result(), result('same'), result(), result('same')] diff --git a/src/shared/remote-runtime/control/remote-runtime-shared-control-app-heartbeat.test.ts b/src/shared/remote-runtime/control/remote-runtime-shared-control-app-heartbeat.test.ts index b14b85878fc..196ef0a8a8f 100644 --- a/src/shared/remote-runtime/control/remote-runtime-shared-control-app-heartbeat.test.ts +++ b/src/shared/remote-runtime/control/remote-runtime-shared-control-app-heartbeat.test.ts @@ -13,7 +13,7 @@ const ok: RuntimeRpcResponse = { _meta: { runtimeId: 'r' } } -function setup(probe: Probe, shouldProbe: () => boolean = () => true) { +function setup(probe: Probe) { const onUnresponsive = vi.fn() const onRecovered = vi.fn() const probeSpy = vi.fn(probe) @@ -22,7 +22,7 @@ function setup(probe: Probe, shouldProbe: () => boolean = () => true) { { probe: probeSpy, isCurrent: () => true, - shouldProbe, + shouldProbe: () => true, onUnresponsive, onRecovered } @@ -129,16 +129,6 @@ describe('shared control app heartbeat', () => { heartbeat.stop() }) - it('does not probe an asleep host', async () => { - const { heartbeat, probe } = setup( - () => Promise.resolve(ok), - () => false - ) - await vi.advanceTimersByTimeAsync(5_000) - expect(probe).not.toHaveBeenCalled() - heartbeat.stop() - }) - it('restarts the silence window after this process stalls instead of blaming the host', async () => { let now = 0 const probe = vi.fn(() => Promise.resolve(ok))