From e799cb419e89e1aa52f49feec0e273f8f613d737 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 7 Nov 2026 18:53:24 -0800 Subject: [PATCH] test: remove 292 low-value tests (#39673) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/flaky-test-pattern-baseline.txt | 1 - config/reliability-gates.jsonc | 29 +- .../scripts/ci/sharding/ci-shard-timings.json | 15 - .../program-status-osc.spec.ts | 139 +------- .../linear/linear-agent-access.test.ts | 1 - .../linear-agent-project-access.spec.ts | 269 -------------- ...ktree-rm-id-selector-path-spelling.test.ts | 252 ------------- src/main/skills/skill-delete/recovery.test.ts | 125 +------ src/main/skills/skill-delete/service.test.ts | 10 - .../skill-placement-reconciliation.test.ts | 56 --- src/main/skills/skill-scan-coalescer.test.ts | 233 +----------- ...skill-transaction-startup-recovery.test.ts | 19 - .../ssh-connection-github-probe.test.ts | 294 ---------------- .../legacy-relay-bridge-relay-restart.test.ts | 142 +------- .../ssh/orcad-migration-source-fence.test.ts | 94 +---- src/main/ssh/orcad-stdio-bridge.test.ts | 120 +------ .../ssh/orcad-update-admission-fence.test.ts | 240 ------------- src/main/ssh/sftp-upload-pipeline.test.ts | 44 +-- src/main/ssh/ssh-host-key-verifier.test.ts | 144 -------- .../ssh/ssh-posix-command-wrapper.test.ts | 139 -------- .../star-nag/service-force-show-races.test.ts | 220 +----------- .../windows-install-dir-acl-probe.test.ts | 259 -------------- .../chat-ui-launch-tip-cohort.test.ts | 258 -------------- ...e-text-generation-local-subprocess.test.ts | 167 --------- .../source-control-read-only-policy.test.ts | 119 +------ ...updater.linux-root-package-install.test.ts | 267 -------------- src/main/usage/jsonl-file-reader.test.ts | 101 ------ .../clipboard-windows-image-file.test.ts | 194 +--------- ...MainWindow-renderer-launch-failure.test.ts | 243 ------------- .../window/native-chat-paste-files.test.ts | 66 +--- .../window/renderer-recovery-prompt.test.ts | 271 -------------- .../workspaces/catalog/repo-worktrees.test.ts | 333 ------------------ .../project-runtime-git-options.test.ts | 276 --------------- .../wsl-distro-holder-script.test.ts | 51 +-- .../wsl-orcad-failed-install-removal.test.ts | 270 -------------- ...e-native-chat-steer-chord-preview.test.tsx | 104 ------ .../use-native-chat-reader-return.test.ts | 79 ----- ...ection-startup-cwd-fallback-notice.spec.ts | 89 ----- .../pty-connection-spawn-and-startup.test.ts | 2 - .../pty-model-restore-channel.test.ts | 30 -- .../ipc/pty-transport-pi-coalesce.test.ts | 18 - .../ipc/pty-transport-pi-spinner.test.ts | 90 ----- ...utput-side-effect-queue-reentrancy.test.ts | 40 --- .../hooks/useMacosTccPromptNotice.test.tsx | 102 ------ ...ex-session-restart-account-recheck.test.ts | 102 ------ .../markdown-monaco-theme-rules.test.ts | 84 ----- ...initial-terminal-seeding-twin-host.test.ts | 84 ----- .../appearance/plugin-icon-themes.test.ts | 93 ----- .../opening/untitled-file-tab-order.test.ts | 113 ------ 49 files changed, 43 insertions(+), 6448 deletions(-) delete mode 100644 src/main/runtime/rpc/methods/integrations/linear/linear-agent-project-access.spec.ts delete mode 100644 src/main/runtime/workspaces/removal/worktree-rm-id-selector-path-spelling.test.ts delete mode 100644 src/main/ssh/connection/ssh-connection-github-probe.test.ts delete mode 100644 src/main/ssh/orcad-update-admission-fence.test.ts delete mode 100644 src/main/startup/windows-install-dir-acl-probe.test.ts delete mode 100644 src/main/telemetry/chat-ui-launch-tip-cohort.test.ts delete mode 100644 src/main/updater/updater.linux-root-package-install.test.ts delete mode 100644 src/main/window/createMainWindow-renderer-launch-failure.test.ts delete mode 100644 src/main/window/renderer-recovery-prompt.test.ts delete mode 100644 src/main/workspaces/catalog/repo-worktrees.test.ts delete mode 100644 src/main/workspaces/execution-host/project-runtime-git-options.test.ts delete mode 100644 src/main/wsl/orcad/wsl-orcad-failed-install-removal.test.ts delete mode 100644 src/renderer/src/components/native-chat/composer/controls/use-native-chat-steer-chord-preview.test.tsx delete mode 100644 src/renderer/src/components/native-chat/viewport/scroll/use-native-chat-reader-return.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts delete mode 100644 src/renderer/src/hooks/useMacosTccPromptNotice.test.tsx delete mode 100644 src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart-account-recheck.test.ts delete mode 100644 src/renderer/src/lib/monaco-languages/markdown-monaco-theme-rules.test.ts delete mode 100644 src/renderer/src/lib/worktree-initial-terminal-seeding-twin-host.test.ts delete mode 100644 src/renderer/src/store/plugins/appearance/plugin-icon-themes.test.ts delete mode 100644 src/renderer/src/store/slices/editor/opening/untitled-file-tab-order.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 0306edb0a31..d3d9e50b69d 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -679,7 +679,6 @@ 2 test-no-wall-clock:src/main/ssh/orcad-exited-own-lock-windows.test.ts 4 test-no-wall-clock:src/main/ssh/ssh-remote-commands.test.ts 2 test-no-wall-clock:src/main/star-nag/service-direct-star.test.ts -1 test-no-wall-clock:src/main/star-nag/service-force-show-races.test.ts 3 test-no-wall-clock:src/main/star-nag/service-threshold-prompt.test.ts 2 test-no-wall-clock:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts 1 test-no-wall-clock:src/main/startup/login-shell-environment.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 65179b77e49..d4229af7163 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2229,13 +2229,13 @@ "providers": ["local", "daemon", "wsl", "ssh", "remote-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": [], - "coverageNotes": "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": "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": "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": "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", @@ -2296,6 +2296,7 @@ "Exercise live SSH and paired-runtime snapshot adoption before claiming full provider coverage." ], "knownGaps": [ + "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.", "No new live SSH, Windows or WSL UI run; remote evidence is focused contract tests.", "Mixed-version snapshots without sequence proof intentionally retain legacy behavior.", @@ -4077,6 +4078,7 @@ "Add an Electron SSH promotion journey in addition to the deterministic identity-transfer unit contract." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1589 removes mock-only CLI forwarding, canned provisioning/catalog/error projections and private inventories without equivalent replacement coverage. Retained cases exercise actual local markdown/paste/reconciliation, stream framing/backpressure/output-drain, temporary directory cleanup and persisted handoff with injected host/provider/process boundaries. No real Jira, provisioning, remote launch, native pipe/process-tree authority or deployed provider catalog proof. Assertion references use the surviving handoff registration titles; changed-selector historical receipts are retired and unaffected receipts remain unchanged.", "The Electron journey uses an isolated development bundle rather than the installed application so it cannot disturb a real user session.", "The live ShipIt/LaunchAgent canary used a disposable minimal Electron bundle plus the compiled production supervisor; a full packaged Orca update has not yet been run.", @@ -4238,6 +4240,7 @@ "Add live SSH or WSL promotion evidence if provider-specific graph restoration diverges." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "The live journeys cover macOS and daemon-backed local terminals, not Linux desktop, Windows, WSL, or SSH promotion.", "The same-frame stale-document race is deterministic fault injection because Playwright cannot schedule an invoke precisely between did-start-loading and frame replacement.", @@ -5037,6 +5040,7 @@ "Collect 100 consecutive focused CI passes or 14 days without an unexplained flake." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded.", "Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", @@ -6242,6 +6246,7 @@ "Keep missing-proof mixed-version behavior identical to the incumbent client path." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded.", "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "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.", @@ -6858,6 +6863,7 @@ "Add restart/no-resurrection and repeated park-close soak coverage." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", @@ -7025,6 +7031,7 @@ "Add live Linux SSH-relay and Windows WSL reconnect artifacts without weakening keep-on-unknown." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "The strongest proof is Electron-as-Node over real daemon PTYs, not a packaged headed Orca host paired to a separate old client; that is the primary live E2E still required.", "Headless orca serve parity, live Linux, Linux SSH relay, and Windows WSL reconnect are not exercised; Docker SSH would cover only the SSH provider and cannot substitute for paired Orca-server evidence.", "A topology containing any pre-contract paired desktop viewer remains vulnerable to that viewer's stale reasonless close storm; preserving its intentional-close behavior makes this unavoidable until the viewer upgrades.", @@ -7146,6 +7153,7 @@ "Add WSL/mobile/API spawn provider-contract coverage or explicitly narrow their risk scope." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: 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(). 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. 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.", "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "No live Electron fixture seeds a persisted tab whose startupCwd directory was deleted.", @@ -7396,6 +7404,7 @@ "Keep disjoint provider inventories, refresh isolation, launch authority, and bounded in-flight state green." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: 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(). 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. 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.", "Live SSH and paired-runtime launch journeys are covered by existing authority contracts rather than this focused oracle.", "The test-value audit removes standalone WSL/provider argument inventories and basic supplied-result/cache-clear examples from detected-agents.test.ts. It retains shared in-flight detection, cached-context return, repair/retry, stale-response fencing, SSH refresh/pruning and old-server fallback behavior. These retained tests do not replace the removed route-argument alarms or execute a live WSL/remote probe. Historical commands, counts and results remain unchanged.", "The later test-value audit removes narrow refusal/reset ledgers, a settled-project eviction/reacquisition example, a simple stale-success variant and redundant plain-text draft cleanup examples. local-detected-agent-state retains independent inventory completion orders, preference-change fencing, full-refresh loading settlement, refresh failure/retry, native-versus-WSL separation, subscriber broadcast bounds and in-flight project eviction. The removed settled-context sibling-preservation/reacquisition alarm is intentionally lost; retained cases are not equivalent replacements and no live provider execution is claimed. Historical commands, counts and results remain unchanged.", @@ -7607,6 +7616,7 @@ "Record byte-identical latest-main, candidate, and candidate-revert Electron results." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1685 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", @@ -7870,6 +7880,7 @@ "Add live SSH/WSL provider evidence before claiming full provider coverage; Docker SSH proves only the SSH provider/relay path." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "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.", "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.", "The primary headed macOS desktop-server journey is automated locally but not yet run in CI; Windows and Linux window, ConPTY, update, sleep/wake, and firewall behavior remain uncollected.", @@ -9277,6 +9288,7 @@ "Keep the budget-off control, exact manager count, final bounded-tail flood marker, parked-time output, and post-reveal PTY input in both topology runs." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "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.", @@ -9631,6 +9643,7 @@ "Keep stress variants non-blocking until stable runtime history exists." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Local daemon/provider and prior-version daemon topologies were not executed.", @@ -10157,6 +10170,7 @@ "Include reconnect/polling artifacts that identify provider, connection id, and lease state." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: 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(). 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. 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.", "Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", "Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", @@ -10961,6 +10975,7 @@ "Retain mixed-version evidence that old hosts strip the optional intent and new hosts accept old clients without a protocol bump." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1586 removes mock-only terminal prompt forwarding and capability assertions without equivalent replacement coverage. Retained CLI tests cover unverified close failures and a missing prompt receipt after preflight using injected host responses; they do not establish actual PTY delivery, host restart or durable replay. Assertion references selecting removed alarms are retired; unaffected execution receipts remain unchanged.", "Live SSH/daemon/remote-runtime evidence is not yet attached.", "Only Claude and Codex opt into settlement; every other agent retains the legacy behavior until independently validated.", @@ -11099,6 +11114,7 @@ "Capture stable red/green intentional-break evidence in CI before blocking promotion." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Live harness command currently expects an already-running dev runtime and generated out/bin/orca-dev wrapper.", "No Windows ConPTY, Linux PTY, SSH, daemon, or remote-runtime live evidence yet.", "Push-on-idle orchestration message banners remain outside this dispatch-prompt gate.", @@ -11300,6 +11316,7 @@ "Accumulate stable soak runs before considering blocking promotion." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1734 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded.", "Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "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.", @@ -11587,6 +11604,7 @@ "Attach saved intentional-break artifacts for hidden local presentation and dropped stable-pane delivery." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "No distinct installed A/B headed or headless paired-runtime cutover is attached; the restart journey relaunches the same build while preserving the daemon and agent.", "No Docker SSH restart/reconnect, physical Windows WSL distro-authority, or git-independent folder-workspace cutover journey is attached.", "Packaged Windows updater and uninstaller continuity is owned by separate updater reliability work and is not claimed by this gate.", @@ -13786,6 +13804,7 @@ "Add a packaged orca serve pairing scenario that proves a connected client refreshes after child replacement." ], "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", @@ -15402,12 +15421,12 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local"], - "coverageNotes": "Provider-independent queue and mocked IPC output contracts run on macOS. Remote-runtime uses this processor but has no live session run. Native mobile uses another processor and is unaffected; host ownership, ACKs, wire, paths, folder/git identity, PTY lifecycle and output bytes are unchanged. Linux, Windows, WSL and live remote execution are gaps.", + "coverageNotes": "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts: keeps empty-tail coalescing observable during the apply callback; preserves thrown apply errors and their existing empty-tail coalescing. 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. The historical receipt/currentCommand selecting src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Provider-independent queue and mocked IPC output contracts run on macOS. Remote-runtime uses this processor but has no live session run. Native mobile uses another processor and is unaffected; host ownership, ACKs, wire, paths, folder/git identity, PTY lifecycle and output bytes are unchanged. Linux, Windows, WSL and live remote execution are gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/blob/main/src/renderer/src/components/terminal-pane/pty-output-side-effect-queue.ts" ], "invariant": "Release consumed title/payload objects after successful apply or overflow carry, preserving callback order, 64-effect drains, the 512-effect pending cap, bell and payload carry, empty-tail coalescing, reentrant clear/flush/enqueue, thrown-apply behavior and output delivery.", - "oracle": "Forced GC collects all 64 applied effects from a 100-effect bounded drain while the remaining 36 stay alive and deliver in order; it also collects the first evicted effect in a 513-effect burst while all 512 survivors remain alive. Clearing during apply immediately releases all 99 other pending effects, as the original queue did. Census reports 36 retained objects after the bounded drain. Explicit reentrant and error cases produce the same observations against the original queue.", + "oracle": "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts: keeps empty-tail coalescing observable during the apply callback; preserves thrown apply errors and their existing empty-tail coalescing. 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. The historical receipt/currentCommand selecting src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Forced GC collects all 64 applied effects from a 100-effect bounded drain while the remaining 36 stay alive and deliver in order; it also collects the first evicted effect in a 513-effect burst while all 512 survivors remain alive. Clearing during apply immediately releases all 99 other pending effects, as the original queue did. Census reports 36 retained objects after the bounded drain. Explicit reentrant and error cases produce the same observations against the original queue.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-retention.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-output-side-effects.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-eager-buffer-replay.test.ts" ], @@ -15466,6 +15485,7 @@ "evidence": "Retained objects fall from 100 to 36 after one bounded drain and from 513 to 512 after one overflow eviction before compaction. Release is constant work per consumed effect; no changed drain limit, timer, polling, batching, cache, transport call or subprocess. Existing compaction cadence remains; clear truncates then replaces its backing array to preserve immediate release and protect reentrant same-object requeue." }, "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts: keeps empty-tail coalescing observable during the apply callback; preserves thrown apply errors and their existing empty-tail coalescing. 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. The historical receipt/currentCommand selecting src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts remains historical and is not a passing result for the reduced current command.", "No real renderer heap-byte or input-latency measurement; references and complete delivery are the deterministic oracle.", "No live Linux, Windows, WSL, SSH or paired-runtime session run; these use provider-independent queue code.", "Thrown apply callbacks keep their consumed reference until the original compaction boundary to preserve exception/coalescing behavior." @@ -15579,6 +15599,7 @@ "evidence": "Audit1991: Remove one-inventory/100-candidate and per-pass workspace lookup-count aliases, foreign-provider timer-call counts, and the ten-minute settled-worker/empty-batch budget sample. Narrow broad inventory/incarnation/probe aliases to retained missing-membership, restarted-relay uncertainty and explicit owning-host absence-verdict callbacks. Remove rollback clone/snapshot-call budgets and supplied persistence microvariants; retain the held-write failure rollback callback that preserves concurrent in-place edits at an injected writer seam, without claiming actual disk durability. Retain late provider recovery and host timer cancellation callbacks. Preserve the independent six-journey Electron restart receipt exactly; its result does not validate these reduced runtime selectors. Historical performance and red/green observations remain historical rather than fresh measurements. 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): One startup SQL repair, one inventory query for 100 deleted-workspace candidates, one durable batch flush, and at most two full rollback snapshots per changed host. Timer passes query only still-deferred assignments through primary-key indexes with a stable parameterized SQL shape, perform zero foreground-process or foreground-agent probes, and skip empty persistence and release reconciliation. Explicit foreground status reads still work. Ten minutes of unchanged retries cause zero session writes and never revisit settled workers. Existing backoff remains capped at 30 seconds so late availability recovers automatically; timers stop on convergence or cancellation, and foreign identities never arm local timers. An additive partial index contains only the five potentially active worker states and is maintained by SQLite for old writers too. Repair queries avoid scanning finished history and return without a write transaction when no stale worker exists; actual repairs re-read under the writer lock and remain atomic. The index is built once per database and adds maintenance on worker-state changes. One recovery pass resolves each workspace once and keeps no lookup cache between passes. A same-machine 100,000-assignment before/after run observed repair 37.75ms to 17.89ms, no-op scan 25.62ms to 4.35ms with zero mutations, and subsequent database open 37.42ms to 17.11ms; The later partial-index/read-only revision observed no-op repair 0.016ms, complete healthy database open 12.44ms, and first index-build plus repair/open 63.14ms for 100,000 assignments and 1,000 stale workers. These local observations are not latency guarantees; index maintenance and fallback metadata work remain. Original customer latency and CI p95 remain unmeasured." }, "knownGaps": [ + "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts: retire six private facet/lifecycle-state and hook-order assertions; retained public OSC/wait cases do not replace those alarms. 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.", "Native Linux/Windows desktop and WSL worker journeys, active-worker SSH absence/deleted-folder recovery, and stranded old-relay process discovery remain untested locally.", "No latency claim against the original customer profile; deterministic counts and one synthetic scale measurement cover the identified work.", "Retired during audit1312 selector cleanup; original complete execution receipt (unchanged): {\"date\":\"2026-10-05\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/orchestration src/main/runtime/runtime-legacy-worker-terminal-recovery-persistence.test.ts src/main/runtime/runtime-legacy-worker-terminal-recovery-retry.test.ts src/main/runtime/runtime-legacy-worker-missing-workspace-recovery.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-migration.test.ts tests/e2e/cross-version-wire/orchestration-delivery-downgrade.unit.test.ts\",\"result\":\"passed\",\"durationSeconds\":27.41,\"summary\":\"2,587 tests passed across 151 files; seven tests and one file skipped. Includes all 45 state combinations, rollback, historical upgrade migrations, SQL downgrade compatibility, active-worker index query plans, old-writer reintroduction, and read-only repair with a competing writer. The 50 focused tests passed separately. Reverting the index and read-only preflight produces two failures.\"}", diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 6b52c88cc76..d654d60b2ac 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -3147,7 +3147,6 @@ "src/main/project-groups/nested-repo-discovery.test.ts": 394, "src/main/project-groups/nested-repo-import-target.test.ts": 58, "src/main/project-groups/nested-repo-import.test.ts": 55, - "src/main/workspaces/execution-host/project-runtime-git-options.test.ts": 172, "src/main/workspaces/execution-host/project-runtime-git-router-store.test.ts": 1818, "src/main/workspaces/execution-host/project-runtime-git-router.test.ts": 192, "src/main/credentials/protected-secret-persistence-concurrency.test.ts": 68, @@ -3247,7 +3246,6 @@ "src/main/workspaces/catalog/repo-git-username-enrichment.test.ts": 111, "src/main/repository-icons/repo-icon-autodetect.test.ts": 806, "src/main/repository-icons/repo-icon-file-detection.test.ts": 487, - "src/main/workspaces/catalog/repo-worktrees.test.ts": 414, "src/main/ripgrep/bundled-ripgrep-path.test.ts": 78, "src/main/ripgrep/bundled-ripgrep-real.test.ts": 242, "src/main/ripgrep/bundled-ripgrep-text-search.test.ts": 707, @@ -4169,7 +4167,6 @@ "src/main/runtime/workspaces/process-listing/worktree-ps-degraded-repo-scan.test.ts": 4596, "src/main/runtime/workspaces/process-listing/worktree-ps-host-scope.test.ts": 4104, "src/main/runtime/workspaces/process-listing/worktree-ps-unverifiable-terminals.test.ts": 4030, - "src/main/runtime/workspaces/removal/worktree-rm-id-selector-path-spelling.test.ts": 4352, "src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts": 4756, "src/main/runtime/workspaces/catalog/worktree-scan-repeated-path.test.ts": 3834, "src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts": 419, @@ -4330,7 +4327,6 @@ "src/main/ssh/connection/ssh-connection-file-transfer-session-lost.test.ts": 5247, "src/main/ssh/connection/ssh-connection-file-transfer.test.ts": 335, "src/main/ssh/connection/ssh-connection-generation.test.ts": 53, - "src/main/ssh/connection/ssh-connection-github-probe.test.ts": 435, "src/main/ssh/connection/ssh-connection-gssapi-fallback.test.ts": 420, "src/main/ssh/connection/ssh-connection-host-key-pin-race.test.ts": 462, "src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts": 776, @@ -4410,7 +4406,6 @@ "src/main/ssh/orcad-terminal-census-client.test.ts": 217, "src/main/ssh/orcad-tunneled-pairing.test.ts": 94, "src/main/ssh/orcad-unreachable-setup-release.test.ts": 2336, - "src/main/ssh/orcad-update-admission-fence.test.ts": 397, "src/main/ssh/orcad-update-plan.test.ts": 642, "src/main/ssh/pinned-runtime-host-target.test.ts": 45, "src/main/ssh/plain-ssh-terminal/plain-ssh-terminal-args.test.ts": 49, @@ -4543,7 +4538,6 @@ "src/main/startup/skill-share-deep-link-state.test.ts": 217, "src/main/startup/startup-diagnostics.test.ts": 39, "src/main/startup/windows-app-data-path.test.ts": 55, - "src/main/startup/windows-install-dir-acl-probe.test.ts": 111, "src/main/startup/windows-install-dir-acl-recovery.test.ts": 614, "src/main/startup/windows-install-dir-acl-repair.win32.test.ts": 132, "src/main/startup/windows-install-dir-package-acl-grant.test.ts": 88, @@ -4562,7 +4556,6 @@ "src/main/power/system-power-lifecycle.test.ts": 42, "src/main/power/system-resume-broadcast.test.ts": 67, "src/main/telemetry/burst-cap.test.ts": 177, - "src/main/telemetry/chat-ui-launch-tip-cohort.test.ts": 235, "src/main/telemetry/classify-error.test.ts": 43, "src/main/telemetry/client-agent-dashboard-snapshot.test.ts": 201, "src/main/telemetry/client-deferred-start.test.ts": 8659, @@ -4622,7 +4615,6 @@ "src/main/updater/updater.headless-serve-install.test.ts": 1744, "src/main/updater/updater.install-failure-cause.test.ts": 1595, "src/main/updater/updater.linux-externally-managed.test.ts": 1056, - "src/main/updater/updater.linux-root-package-install.test.ts": 1741, "src/main/updater/mac-install/updater.mac-install.test.ts": 879, "src/main/updater/updater.nudge-campaign.test.ts": 1658, "src/main/updater/updater.prerelease-fallback.test.ts": 2731, @@ -4672,7 +4664,6 @@ "src/main/window/createMainWindow-markdown-editor-focus.test.ts": 1084, "src/main/window/createMainWindow-recovery-reload-watchdog.test.ts": 1251, "src/main/window/createMainWindow-renderer-crash-recovery.test.ts": 1613, - "src/main/window/createMainWindow-renderer-launch-failure.test.ts": 1242, "src/main/window/createMainWindow-startup-reveal.test.ts": 1185, "src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts": 2628, "src/main/window/createMainWindow-tray-minimize-close.test.ts": 1140, @@ -4702,7 +4693,6 @@ "src/main/window/renderer-launch-failure-probe.test.ts": 60, "src/main/window/renderer-liveness-at-death.test.ts": 50, "src/main/window/renderer-publication-throttle.electron.test.ts": 5163, - "src/main/window/renderer-recovery-prompt.test.ts": 120, "src/main/window/renderer-recovery-reload-watchdog.test.ts": 69, "src/main/window/runtime-renderer-notification-sender.test.ts": 54, "src/main/window/runtime-window-lifecycle-terminal-reveal.test.ts": 100, @@ -6226,7 +6216,6 @@ "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts": 3927, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-output-side-effects.test.ts": 1128, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts": 683, - "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts": 724, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-reattach-admission.test.ts": 1636, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-recycled-pty-incarnation.test.ts": 787, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-errors.test.ts": 1218, @@ -6582,7 +6571,6 @@ "src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts": 1778, "src/renderer/src/hooks/useIssueMetadata.test.tsx": 344, "src/renderer/src/hooks/useMacTccAttributionSeveredNotice.test.tsx": 2358, - "src/renderer/src/hooks/useMacosTccPromptNotice.test.tsx": 1989, "src/renderer/src/hooks/useMetadataListRequest.test.tsx": 266, "src/renderer/src/hooks/useModalReturnFocus.test.tsx": 1938, "src/renderer/src/hooks/usePrimarySelectionPaste.terminal-native-paste.test.tsx": 388, @@ -6689,7 +6677,6 @@ "src/renderer/src/lib/code-editor-theme.test.ts": 101, "src/renderer/src/lib/code-host-error-copy.test.ts": 297, "src/renderer/src/lib/codex-pane-selection-lane.test.ts": 543, - "src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart-account-recheck.test.ts": 1758, "src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart-shell-flap.test.ts": 1745, "src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart.test.ts": 2039, "src/renderer/src/lib/codex-stale-pane-account-identity.test.ts": 1823, @@ -6960,7 +6947,6 @@ "src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts": 5258, "src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-lifecycle.test.ts": 2633, "src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-prompts.test.tsx": 4554, - "src/renderer/src/lib/worktree-initial-terminal-seeding-twin-host.test.ts": 1862, "src/renderer/src/lib/worktree-live-terminal-surface-owners.test.ts": 266, "src/renderer/src/lib/worktree-operation-route-index.test.ts": 262, "src/renderer/src/lib/worktree-operation-route.test.ts": 342, @@ -7115,7 +7101,6 @@ "src/renderer/src/store/github/repositories/wsl-stopped-distro-poll-refusal.test.ts": 696, "src/renderer/src/store/workspaces/host-isolation/host-twin-isolation.test.ts": 1889, "src/renderer/src/store/workspaces/host-isolation/host-twin-worktree-purge.test.ts": 1945, - "src/renderer/src/store/plugins/appearance/plugin-icon-themes.test.ts": 365, "src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts": 435, "src/renderer/src/store/plugins/localization/plugin-language-packs.test.ts": 377, "src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts": 5216, diff --git a/src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts b/src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts index 564e7d0b968..ebdc05c801b 100644 --- a/src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts +++ b/src/main/runtime/orca-runtime-tests/program-status-osc.spec.ts @@ -2,10 +2,9 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest' import { committingSpawn } from './bind-first-pane.test-fixture' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { createSideEffectRuntime } from './orca-runtime-test-scenario-builders.spec' +import './orca-runtime-test-scenario-builders.spec' import type { RuntimeTerminalAgentStatusEvent } from '../terminal/output/terminal-agent-status-events' import { - syncSinglePty, TEST_WORKTREE_PATH, expectStablePaneKeyEnv, store @@ -52,142 +51,6 @@ describe('OSC 7501 program status', () => { ]) }) - it("hands the store each chunk's facet before the rows that chunk publishes", async () => { - const order: string[] = [] - const spawn = vi.fn().mockResolvedValue({ id: 'pty-order' }) - const runtime = new OrcaRuntimeService(store, undefined, { - onTerminalAgentStatus: (event) => order.push(`status:${event.payload.state}`), - onTerminalProgramStatusFacet: (event) => order.push(`facet:${event.facet?.state ?? 'none'}`) - }) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { command: 'brew', title: 'w' }) - - runtime.onPtyData('pty-order', '\x1b]7501;state=working:app=brew:progress=10\x1b\\', 1) - runtime.onPtyData('pty-order', '\x1b]7501;state=done:app=brew\x1b\\', 2) - - // Readers between status updates must never see done with a live facet. - expect(order).toEqual(['facet:working', 'status:working', 'facet:done', 'status:done']) - }) - - it('clears a live facet when its PTY exits but keeps a finished one', async () => { - const facets: [string, string | null][] = [] - const spawn = vi - .fn() - .mockResolvedValueOnce({ id: 'pty-live' }) - .mockResolvedValueOnce({ id: 'pty-done' }) - const runtime = new OrcaRuntimeService(store, undefined, { - onTerminalProgramStatusFacet: (event) => - facets.push([event.ptyId, event.facet?.state ?? null]) - }) - runtime.setPtyController({ - spawn: committingSpawn(runtime, spawn), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { command: 'brew', title: 'a' }) - await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { command: 'brew', title: 'b' }) - - runtime.onPtyData('pty-live', '\x1b]7501;state=working:app=brew:progress=10\x1b\\', 1) - runtime.onPtyData('pty-done', '\x1b]7501;state=done:app=brew\x1b\\', 1) - await runtime.onPtyExit('pty-live', 0) - await runtime.onPtyExit('pty-done', 0) - - expect(facets).toEqual([ - ['pty-live', 'working'], - ['pty-done', 'done'], - ['pty-live', null] - ]) - }) - - it("drives agent edges and the PTY's status from Claude's OSC 7501, not its glyph-less titles", () => { - // Claude Code 2.1.302 drops title spinners after OSC 7501; only its program report distinguishes working from idle. - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - const osc7501 = (body: string) => `\x1b]7501;${body}\x1b\\` - type PtyRecords = { ptysById: Map } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own PTY record, which the public API does not expose. - const records = runtime as unknown as PtyRecords - const ptyStatus = () => records.ptysById.get('pty-1')?.lastAgentStatus - - runtime.onPtyData('pty-1', `${osc7501('state=idle:app=claude-code')}\x1b]0;Claude Code\x07`, 1) - expect(ptyStatus()).toBe('idle') - runtime.onPtyData('pty-1', osc7501('state=working:app=claude-code'), 2) - expect(ptyStatus()).toBe('working') - runtime.onPtyData('pty-1', '\x1b]0;Fix the parser\x07', 3) - expect(ptyStatus()).toBe('working') - runtime.onPtyData('pty-1', osc7501('state=done:app=claude-code'), 4) - expect(ptyStatus()).toBe('idle') - - const edges = batches.flatMap((batch) => - batch.facts.filter((fact) => fact.kind === 'agent-working' || fact.kind === 'agent-idle') - ) - expect(edges).toEqual([ - { kind: 'agent-working' }, - { kind: 'agent-idle', title: 'Fix the parser', status: 'idle' } - ]) - }) - - it("returns the PTY's status to its titles once the shell prompt follows a program's done", () => { - const { runtime } = createSideEffectRuntime() - syncSinglePty(runtime) - const osc7501 = (body: string) => `\x1b]7501;${body}\x1b\\` - type PtyRecords = { - ptysById: Map< - string, - { lastAgentStatus: string | null; lastExplicitAgentStatus?: { programAtRest?: boolean } } - > - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own PTY record, which the public API does not expose. - const records = runtime as unknown as PtyRecords - const pty = () => records.ptysById.get('pty-1') - - runtime.onPtyData('pty-1', `\x1b]0;tf\x07${osc7501('state=done:app=terraform')}`, 1) - expect(pty()?.lastAgentStatus).toBe('idle') - expect(pty()?.lastExplicitAgentStatus?.programAtRest).toBe(true) - runtime.onPtyData('pty-1', '\x1b]133;A\x07', 2) - expect(pty()?.lastAgentStatus).toBeNull() - expect(pty()?.lastExplicitAgentStatus?.programAtRest).toBeUndefined() - runtime.onPtyData('pty-1', '\x1b]0;⠋ Gemini working\x07', 3) - expect(pty()?.lastAgentStatus).toBe('working') - }) - - it('re-classifies on an activity change without restamping the last title', () => { - const { runtime } = createSideEffectRuntime() - syncSinglePty(runtime) - type PtyRecords = { - ptysById: Map - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own PTY record, which the public API does not expose. - const records = runtime as unknown as PtyRecords - const pty = () => records.ptysById.get('pty-1') - - runtime.onPtyData('pty-1', '\x1b]0;Fix the parser\x07', 1) - const titledAt = pty()?.lastOscTitleAt - runtime.onPtyData('pty-1', '\x1b]7501;state=working:app=claude-code\x1b\\', 2) - expect(pty()?.lastAgentStatus).toBe('working') - expect(pty()?.lastOscTitleAt).toBe(titledAt) - }) - - it("classifies a chunk's trailing glyph-less title by the program's activity for the prompt lifecycle", () => { - const { runtime } = createSideEffectRuntime() - syncSinglePty(runtime) - type Lifecycle = { agentPromptLifecycleByPtyId: Map } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the runtime's own lifecycle map, which the public API does not expose. - const lifecycle = runtime as unknown as Lifecycle - runtime.onPtyData( - 'pty-1', - '\x1b]7501;state=working:app=claude-code\x1b\\\x1b]0;Fix the parser\x07', - 1 - ) - expect(lifecycle.agentPromptLifecycleByPtyId.get('pty-1')?.status).toBe('working') - }) - it('reports a lasting sign-in block as blocked instead of waiting out tui-idle (#37056, #28348)', async () => { vi.useFakeTimers({ toFake: ['Date'] }) onTestFinished(() => { diff --git a/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.test.ts b/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.test.ts index ada9020e5df..67b8c2a78fc 100644 --- a/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.test.ts +++ b/src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.test.ts @@ -1,5 +1,4 @@ import '../../../unused-default-rpc-methods.test-fixture' -import './linear-agent-project-access.spec' import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../../../dispatcher' import type { RpcRequest } from '../../../core' diff --git a/src/main/runtime/rpc/methods/integrations/linear/linear-agent-project-access.spec.ts b/src/main/runtime/rpc/methods/integrations/linear/linear-agent-project-access.spec.ts deleted file mode 100644 index 48f84948f9b..00000000000 --- a/src/main/runtime/rpc/methods/integrations/linear/linear-agent-project-access.spec.ts +++ /dev/null @@ -1,269 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../../../orca-runtime' -import type * as LinearIssueMutationsModule from '../../../../../linear/linear-issue-mutations' - -const mocks = vi.hoisted(() => ({ createIssueForAgent: vi.fn() })) - -vi.mock('../../../../../linear/linear-issue-mutations', async (importOriginal) => ({ - ...(await importOriginal()), - createIssueForAgent: mocks.createIssueForAgent -})) - -type LinearProjectResolverTester = { - resolveLinearCreateProject( - input: string, - team: { id: string; workspaceId: string } - ): Promise<{ - id: string - name: string - }> - readLinearProjectByIdForCreate(id: string, workspaceId: string): Promise - readLinearProjectsForCreate(query: string, workspaceId: string): Promise - readLinearProjectsByExactNameForCreate(name: string, workspaceId: string): Promise -} - -type LinearCreateTester = LinearProjectResolverTester & { - resolveLinearCreateTeam( - teamInput: string | undefined, - workspaceId: string | undefined, - parent: unknown - ): Promise<{ id: string; key: string; name: string; workspaceId: string }> -} - -describe('Linear agent project access helpers', () => { - it('resolves Linear projects by UUID before searching names', async () => { - const runtime = new OrcaRuntimeService() - const tester = runtime as unknown as LinearProjectResolverTester - const readById = vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue({ - id: '11111111-1111-4111-8111-111111111111', - name: 'Launch', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - } as never) - const readByName = vi - .spyOn(tester, 'readLinearProjectsForCreate') - .mockResolvedValue([] as never) - - await expect( - tester.resolveLinearCreateProject('11111111-1111-4111-8111-111111111111', { - id: 'team-1', - workspaceId: 'workspace-1' - }) - ).resolves.toMatchObject({ id: '11111111-1111-4111-8111-111111111111' }) - expect(readById).toHaveBeenCalledWith( - '11111111-1111-4111-8111-111111111111', - 'workspace-1', - undefined - ) - expect(readByName).not.toHaveBeenCalled() - }) - - it('resolves Linear projects by trimmed case-insensitive exact name', async () => { - const runtime = new OrcaRuntimeService() - const tester = runtime as unknown as LinearProjectResolverTester - vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never) - const readByName = vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([ - { - id: 'project-1', - name: 'Launch', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - } - ] as never) - const readExactName = vi - .spyOn(tester, 'readLinearProjectsByExactNameForCreate') - .mockResolvedValue([ - { - id: 'project-1', - name: 'Launch', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - } - ] as never) - - await expect( - tester.resolveLinearCreateProject(' launch ', { id: 'team-1', workspaceId: 'workspace-1' }) - ).resolves.toMatchObject({ id: 'project-1' }) - expect(readByName).toHaveBeenCalledWith('launch', 'workspace-1', undefined) - expect(readExactName).toHaveBeenCalledWith('launch', 'workspace-1', undefined) - }) - - it('resolves Linear projects by URL slug without a paginated exact-name scan', async () => { - const runtime = new OrcaRuntimeService() - const tester = runtime as unknown as LinearProjectResolverTester - vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never) - vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([ - { - id: 'project-1', - slugId: 'launch-d8f6c7e7', - name: 'Launch', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - } - ] as never) - const readExactName = vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate') - - await expect( - tester.resolveLinearCreateProject('LAUNCH-D8F6C7E7', { - id: 'team-1', - workspaceId: 'workspace-1' - }) - ).resolves.toMatchObject({ id: 'project-1' }) - expect(readExactName).not.toHaveBeenCalled() - }) - - it('resolves same-named Linear projects by target team compatibility', async () => { - const runtime = new OrcaRuntimeService() - const tester = runtime as unknown as LinearProjectResolverTester - vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never) - vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([] as never) - vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([ - { - id: 'project-1', - name: 'Launch', - teams: [{ id: 'team-other', name: 'Other', key: 'OTH' }] - }, - { - id: 'project-2', - name: 'launch', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - } - ] as never) - - await expect( - tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' }) - ).resolves.toMatchObject({ id: 'project-2' }) - }) - - it('rejects ambiguous Linear project names with candidate ids', async () => { - const runtime = new OrcaRuntimeService() - const tester = runtime as unknown as LinearProjectResolverTester - vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never) - vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([] as never) - vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([ - { - id: 'project-1', - name: 'Launch', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - }, - { - id: 'project-2', - name: 'launch', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - } - ] as never) - - await expect( - tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' }) - ).rejects.toMatchObject({ - code: 'linear_invalid_project', - data: { - projects: [ - { id: 'project-1', name: 'Launch' }, - { id: 'project-2', name: 'launch' } - ] - } - }) - }) - - it('fails closed when Linear project team membership cannot be verified', async () => { - const runtime = new OrcaRuntimeService() - const tester = runtime as unknown as LinearProjectResolverTester - vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never) - vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([] as never) - vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([ - { - id: 'project-1', - name: 'Launch' - } - ] as never) - - await expect( - tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' }) - ).rejects.toMatchObject({ - code: 'linear_invalid_project', - data: { project: { id: 'project-1', name: 'Launch', teams: [] } } - }) - }) - - it('caps agent project lists globally and returns a narrow project DTO', async () => { - const runtime = new OrcaRuntimeService() - vi.spyOn(runtime, 'linearListProjects').mockResolvedValue({ - items: [ - { - id: 'project-1', - name: 'Launch', - url: 'https://linear.app/acme/project/launch', - workspaceId: 'workspace-1', - workspaceName: 'Acme', - content: 'internal notes', - description: 'roadmap', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - }, - { - id: 'project-2', - name: 'Follow-up', - workspaceId: 'workspace-2', - workspaceName: 'Beta' - } - ], - hasMore: false - } as never) - - const result = await runtime.linearProjectListForAgents({ limit: 1, workspaceId: 'all' }) - - expect(result.projects).toHaveLength(1) - expect(result.projects[0]).toMatchObject({ - id: 'project-1', - name: 'Launch', - url: 'https://linear.app/acme/project/launch', - workspaceId: 'workspace-1', - workspaceName: 'Acme', - teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }] - }) - expect(result.projects[0]).not.toHaveProperty('content') - expect(result.projects[0]).not.toHaveProperty('description') - expect(result.meta).toMatchObject({ limit: 1, returned: 1, hasMore: true }) - }) - - it('passes the resolved project id into agent issue create', async () => { - const createIssueForAgent = mocks.createIssueForAgent.mockReset().mockResolvedValue({ - id: 'issue-created', - identifier: 'ENG-123', - title: 'Follow up', - url: 'https://linear.app/acme/issue/ENG-123', - team: { id: 'team-1', key: 'ENG', name: 'Engineering' }, - state: null, - parent: null, - project: { id: 'project-1', name: 'Launch' } - }) - const runtime = new OrcaRuntimeService() - const tester = runtime as unknown as LinearCreateTester - vi.spyOn(tester, 'resolveLinearCreateTeam').mockResolvedValue({ - id: 'team-1', - key: 'ENG', - name: 'Engineering', - workspaceId: 'workspace-1' - }) - vi.spyOn(tester, 'resolveLinearCreateProject').mockResolvedValue({ - id: 'project-1', - name: 'Launch' - } as never) - - const result = await runtime.linearIssueCreate({ - title: 'Follow up', - teamInput: 'ENG', - projectInput: 'Launch', - writeId: '33333333-3333-4333-8333-333333333333' - }) - - expect(result.issue.project).toMatchObject({ id: 'project-1', name: 'Launch' }) - expect(createIssueForAgent).toHaveBeenCalledWith( - 'team-1', - 'Follow up', - undefined, - 'workspace-1', - expect.objectContaining({ - id: '33333333-3333-4333-8333-333333333333', - parentId: null, - projectId: 'project-1' - }) - ) - }) -}) diff --git a/src/main/runtime/workspaces/removal/worktree-rm-id-selector-path-spelling.test.ts b/src/main/runtime/workspaces/removal/worktree-rm-id-selector-path-spelling.test.ts deleted file mode 100644 index c89b02e8479..00000000000 --- a/src/main/runtime/workspaces/removal/worktree-rm-id-selector-path-spelling.test.ts +++ /dev/null @@ -1,252 +0,0 @@ -import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -/** Preserve id/path spelling parity, while id remains ambiguous for same-host duplicate rows that path deduplicates. This resolver also deletes workspaces (#16243). */ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const electronMocks = vi.hoisted(() => { - const ipcMain = { - on: vi.fn(() => ipcMain), - removeListener: vi.fn(() => ipcMain), - emit: vi.fn(() => true) - } - return { - BrowserWindow: { fromId: vi.fn((): unknown => null) }, - webContents: { fromId: vi.fn((): unknown => null) }, - ipcMain, - app: { getPath: vi.fn(() => '/tmp'), isPackaged: false } - } -}) -vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - return { - ...(await importOriginal()), - listWorktreesStrict: listWorktreesStrictMock - } -}) - -vi.mock('electron', () => electronMocks) - -const listWorktreesStrictMock = vi.hoisted(() => vi.fn()) - -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' -import { OrcaRuntimeService } from '../../orca-runtime' -import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' - -const REPO_ID = 'repo-local' -const REPO_PATH = '/srv/projects/app' -const WORKTREE_PATH = '/srv/projects/workspaces/plugin-host' -const CANONICAL_ID = `${REPO_ID}::${WORKTREE_PATH}` - -const ID_SPELLINGS: [label: string, worktreePath: string, repoPath?: string][] = [ - ['a trailing slash', `${WORKTREE_PATH}/`], - ['a doubled separator', '/srv/projects//workspaces/plugin-host'], - ['an NFD workspace name', '/srv/projects/workspaces/café-plugin'.normalize('NFD')], - // #15598/#15616: a Windows registration records backslashes; git reports forward slashes. - ['a backslash Windows spelling', 'D:\\Agentic\\game2\\battle-core', 'D:/Agentic/game2'] -] - -function scannedSpellingOf(storedPath: string): string { - const slashed = /^[A-Za-z]:[\\/]/.test(storedPath) ? storedPath.replace(/\\/g, '/') : storedPath - return slashed.normalize('NFC').replace(/\/+/g, '/').replace(/\/$/, '') -} - -/** One registered repo whose worktree meta is writable, so a delete's `forgetLocal` is observable. */ -function makeStore(repoPath: string = REPO_PATH) { - const metaById: Record> = {} - const store = { - getRepo: (id: string) => store.getRepos().find((repo) => repo.id === id), - getRepos: () => [ - { id: REPO_ID, path: repoPath, displayName: 'app', badgeColor: 'blue', addedAt: 1 } - ], - getAllWorktreeMeta: vi.fn(() => metaById), - getWorktreeMeta: (id: string) => metaById[id], - setWorktreeMeta: ({ id }: HostWorktreeTarget, meta: Record) => { - metaById[id] = { ...metaById[id], ...meta } - return metaById[id] - }, - removeWorktreeMeta: () => {}, - getAllWorktreeLineage: () => ({}), - getAllWorkspaceLineage: () => ({}), - removeWorktreeLineage: vi.fn(), - removeWorkspaceLineage: vi.fn(), - getGitHubCache: () => undefined as never, - getSettings: () => ({ - workspaceDir: '/tmp/workspaces', - nestWorkspaces: false, - refreshLocalBaseRefOnWorktreeCreate: false, - branchPrefix: 'none', - branchPrefixCustom: '' - }), - getProjects: () => [] - } - return store -} - -function scanReports(worktreePath: string, repoPath: string = REPO_PATH): void { - listWorktreesStrictMock.mockResolvedValue([ - { path: repoPath, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true }, - { path: worktreePath, head: 'def', branch: 'feature', isBare: false, isMainWorktree: false } - ]) -} - -type RemovalInternals = { - resolveWorktreeRemovalTarget: ( - worktreeSelector: string, - requiredHostId?: string - ) => Promise<{ id: string; repoId: string; path: string }> -} - -beforeEach(() => { - listWorktreesStrictMock.mockReset() -}) - -describe('worktree id selectors vs. the path spelling git reports (#16243)', () => { - it.each(ID_SPELLINGS)( - 'resolves through the fleet path what `path:` resolves when the id carries %s', - async (_label, storedPath, repoPath) => { - scanReports(scannedSpellingOf(storedPath), repoPath) - const runtime = new OrcaRuntimeService(makeStore(repoPath) as never) - - const byPath = await runtime.showManagedWorktree(`path:${storedPath}`) - await expect( - runtime.showManagedWorktree(`id:${REPO_ID}::${storedPath}`) - ).resolves.toMatchObject({ id: byPath.id, path: byPath.path }) - } - ) - - it.each(ID_SPELLINGS)( - 'resolves a host-qualified removal target when the id carries %s', - async (_label, storedPath, repoPath) => { - scanReports(scannedSpellingOf(storedPath), repoPath) - const runtime = new OrcaRuntimeService(makeStore(repoPath) as never) - const internals = runtime as unknown as RemovalInternals - - await expect( - internals.resolveWorktreeRemovalTarget( - `id:${REPO_ID}::${storedPath}`, - LOCAL_EXECUTION_HOST_ID - ) - ).resolves.toMatchObject({ repoId: REPO_ID, path: scannedSpellingOf(storedPath) }) - } - ) - - it('still refuses an id whose path names a different workspace', async () => { - scanReports(WORKTREE_PATH) - const runtime = new OrcaRuntimeService(makeStore() as never) - - await expect( - runtime.showManagedWorktree(`id:${REPO_ID}::/srv/projects/workspaces/other-plugin`) - ).rejects.toThrow('selector_not_found') - }) - - // STA-4343: matching across repo ids would delete a workspace the caller never confirmed. - it('still refuses the same path under a different repo id', async () => { - scanReports(WORKTREE_PATH) - const runtime = new OrcaRuntimeService(makeStore() as never) - - await expect(runtime.showManagedWorktree(`id:other-repo::${WORKTREE_PATH}/`)).rejects.toThrow( - 'selector_not_found' - ) - }) - - it('still refuses a removal qualified to a host that does not own the repo id', async () => { - scanReports(WORKTREE_PATH) - const runtime = new OrcaRuntimeService(makeStore() as never) - const internals = runtime as unknown as RemovalInternals - - await expect( - internals.resolveWorktreeRemovalTarget(`id:${CANONICAL_ID}/`, 'runtime:env-b') - ).rejects.toThrow('selector_not_found') - }) - - it('keeps `id:` and `path:` agreeing on a dot segment neither canonicalizes', async () => { - scanReports(WORKTREE_PATH) - const runtime = new OrcaRuntimeService(makeStore() as never) - const dotted = '/srv/projects/./workspaces/plugin-host' - - await expect(runtime.showManagedWorktree(`path:${dotted}`)).rejects.toThrow( - 'selector_not_found' - ) - await expect(runtime.showManagedWorktree(`id:${REPO_ID}::${dotted}`)).rejects.toThrow( - 'selector_not_found' - ) - }) - - // Windows stores either slash spelling; the table above covers id folding, and these tests pin its limits (#15598/#15616). - describe('Windows drive-letter spellings', () => { - const WINDOWS_REPO = 'D:/Agentic/game2' - const WINDOWS_WORKTREE = 'D:/Agentic/game2/battle-core' - - it('folds drive-letter case only for Windows paths, never for a POSIX path', async () => { - scanReports(WINDOWS_WORKTREE, WINDOWS_REPO) - const windowsRuntime = new OrcaRuntimeService(makeStore(WINDOWS_REPO) as never) - - // A Windows root is case-insensitive, as `path:` already treats it. - await expect( - windowsRuntime.showManagedWorktree(`id:${REPO_ID}::d:/agentic/game2/battle-core`) - ).resolves.toMatchObject({ path: WINDOWS_WORKTREE }) - - // A POSIX root is not: folding case there would merge distinct directories for a delete. - scanReports(WORKTREE_PATH) - const posixRuntime = new OrcaRuntimeService(makeStore() as never) - - await expect( - posixRuntime.showManagedWorktree(`id:${REPO_ID}::/SRV/projects/workspaces/plugin-host`) - ).rejects.toThrow('selector_not_found') - }) - - it('does not fold a backslash inside a POSIX path, where it is a valid filename character', async () => { - scanReports(WORKTREE_PATH) - const runtime = new OrcaRuntimeService(makeStore() as never) - - await expect( - runtime.showManagedWorktree(`id:${REPO_ID}::/srv/projects\\workspaces\\plugin-host`) - ).rejects.toThrow('selector_not_found') - }) - }) - - // Delete-capable id resolution must refuse duplicates even when path resolution deduplicates them. - it('refuses a folded id when two same-repo rows spell one directory', async () => { - listWorktreesStrictMock.mockResolvedValue([ - { path: REPO_PATH, head: 'abc', branch: 'main', isBare: false, isMainWorktree: true }, - { path: WORKTREE_PATH, head: 'def', branch: 'feature', isBare: false, isMainWorktree: false }, - { - path: '/srv/projects//workspaces/plugin-host', - head: 'ghi', - branch: 'feature-2', - isBare: false, - isMainWorktree: false - } - ]) - const runtime = new OrcaRuntimeService(makeStore() as never) - - await expect(runtime.showManagedWorktree(`id:${CANONICAL_ID}/`)).rejects.toThrow( - 'selector_ambiguous' - ) - }) - - // Folder-workspace ids trim only a terminal slash; one before the instance suffix stays exact-only. - it('keeps a folder-workspace id exact when a slash precedes the instance suffix', async () => { - const instanceSuffix = '::workspace:123e4567-e89b-12d3-a456-426614174000' - scanReports(WORKTREE_PATH) - const runtime = new OrcaRuntimeService(makeStore() as never) - - await expect( - runtime.showManagedWorktree(`id:${REPO_ID}::${WORKTREE_PATH}/${instanceSuffix}`) - ).rejects.toThrow('selector_not_found') - }) - - it.each([ - ['no repo boundary', 'not-an-id'], - ['an empty path', `${REPO_ID}::`] - ])('keeps exact matching for a malformed id with %s', async (_label, malformedId) => { - scanReports(WORKTREE_PATH) - const runtime = new OrcaRuntimeService(makeStore() as never) - const internals = runtime as unknown as RemovalInternals - - await expect(runtime.showManagedWorktree(`id:${malformedId}`)).rejects.toThrow( - 'selector_not_found' - ) - await expect( - internals.resolveWorktreeRemovalTarget(`id:${malformedId}`, LOCAL_EXECUTION_HOST_ID) - ).rejects.toThrow('selector_not_found') - }) -}) diff --git a/src/main/skills/skill-delete/recovery.test.ts b/src/main/skills/skill-delete/recovery.test.ts index 32e35f73a0b..1818b7bfad8 100644 --- a/src/main/skills/skill-delete/recovery.test.ts +++ b/src/main/skills/skill-delete/recovery.test.ts @@ -3,7 +3,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { - readSkillDeleteRecoveryJournal, recoverSkillDeleteTransaction, skillDeleteJournalPath, writeSkillDeleteJournal, @@ -13,7 +12,7 @@ import { nativeSkillInstallFilesystem, type SkillInstallFilesystem } from '../skill-install-filesystem' -import { writeSkillStateFile } from '../skill-install-provenance' +import '../skill-install-provenance' import { skillDeleteStagedName } from './staging-names' const roots: string[] = [] @@ -58,72 +57,6 @@ async function exists(path: string): Promise { return Boolean(await lstat(path).catch(() => null)) } -describe('skill delete journal validation', () => { - it('round-trips a valid journal', async () => { - const { stateDirectory, root } = await fixture() - const canonicalPath = join(root, 'demo') - await writeSkillDeleteJournal(stateDirectory, journal(root, canonicalPath)) - expect(await readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).toMatchObject({ - operation: 'delete', - phase: 'staged' - }) - }) - - it('returns null when there is no journal', async () => { - const { stateDirectory, root } = await fixture() - expect(await readSkillDeleteRecoveryJournal(stateDirectory, join(root, 'demo'))).toBeNull() - }) - - it('refuses a move whose source escapes every allowed root', async () => { - const { home, stateDirectory, root } = await fixture() - const canonicalPath = join(root, 'demo') - const escaped = join(home, 'elsewhere', 'demo') - await writeSkillStateFile( - skillDeleteJournalPath(stateDirectory, canonicalPath), - journal(root, canonicalPath, { - moves: [ - { - sourcePath: escaped, - stagedPath: join(home, 'elsewhere', skillDeleteStagedName('demo', 'id-1')), - kind: 'canonical' - } - ] - }) - ) - await expect(readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).rejects.toThrow( - 'skill-delete-journal-invalid' - ) - }) - - it('refuses a staged path that is not our sibling naming convention', async () => { - const { stateDirectory, root } = await fixture() - const canonicalPath = join(root, 'demo') - await writeSkillStateFile( - skillDeleteJournalPath(stateDirectory, canonicalPath), - journal(root, canonicalPath, { - moves: [ - { sourcePath: canonicalPath, stagedPath: join(root, 'demo.bak'), kind: 'canonical' } - ] - }) - ) - await expect(readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).rejects.toThrow( - 'skill-delete-journal-invalid' - ) - }) - - it('refuses a movedCount larger than the move list', async () => { - const { stateDirectory, root } = await fixture() - const canonicalPath = join(root, 'demo') - await writeSkillStateFile( - skillDeleteJournalPath(stateDirectory, canonicalPath), - journal(root, canonicalPath, { movedCount: 4 }) - ) - await expect(readSkillDeleteRecoveryJournal(stateDirectory, canonicalPath)).rejects.toThrow( - 'skill-delete-journal-invalid' - ) - }) -}) - describe('recoverSkillDeleteTransaction', () => { it('rolls a staged phase forward by removing the staged path', async () => { const { stateDirectory, root } = await fixture() @@ -173,21 +106,6 @@ describe('recoverSkillDeleteTransaction', () => { expect(await exists(skillDeleteJournalPath(stateDirectory, canonicalPath))).toBe(false) }) - it('clears the journal when the recorded move was never performed', async () => { - // Intent precedes rename: absent staged paths may never have moved and must not pin recovery forever. - const { stateDirectory, root } = await fixture() - const canonicalPath = join(root, 'demo') - await mkdir(canonicalPath, { recursive: true }) - await writeSkillDeleteJournal( - stateDirectory, - journal(root, canonicalPath, { phase: 'staging' }) - ) - - await recoverSkillDeleteTransaction(stateDirectory, canonicalPath) - expect(await exists(canonicalPath)).toBe(true) - expect(await exists(skillDeleteJournalPath(stateDirectory, canonicalPath))).toBe(false) - }) - it('clears the journal on retry after an earlier pass already restored a move', async () => { const { home, stateDirectory, root } = await fixture() const canonicalPath = join(root, 'demo') @@ -220,45 +138,4 @@ describe('recoverSkillDeleteTransaction', () => { expect(await exists(canonicalPath)).toBe(true) expect(await exists(skillDeleteJournalPath(stateDirectory, canonicalPath))).toBe(false) }) - - it('restores canonical before alias-file, so no alias dangles mid-recovery', async () => { - const { home, stateDirectory, root } = await fixture() - const canonicalPath = join(root, 'demo') - const aliasRoot = join(home, '.claude', 'skills', 'demo') - await mkdir(aliasRoot, { recursive: true }) - const entry = journal(root, canonicalPath, { - phase: 'staging', - movedCount: 2, - allowedRoots: [root, join(home, '.claude', 'skills')], - // Reverse alias-first staging to restore canonical content before aliases. - moves: [ - { - sourcePath: join(aliasRoot, 'SKILL.md'), - stagedPath: join(aliasRoot, skillDeleteStagedName('SKILL.md', 'id-2')), - kind: 'alias-file' - }, - { - sourcePath: canonicalPath, - stagedPath: join(root, skillDeleteStagedName('demo', 'id-1')), - kind: 'canonical' - } - ] - }) - await mkdir(entry.moves[1].stagedPath, { recursive: true }) - await writeFile(entry.moves[0].stagedPath, 'link-stand-in') - await writeSkillDeleteJournal(stateDirectory, entry) - - const order: string[] = [] - await recoverSkillDeleteTransaction(stateDirectory, canonicalPath, { - prepareExtractedSkill: async () => undefined, - observeSkill: async () => { - throw new Error('unused') - }, - rename: async (_source, target) => { - order.push(target) - }, - remove: async () => undefined - }) - expect(order).toEqual([canonicalPath, join(aliasRoot, 'SKILL.md')]) - }) }) diff --git a/src/main/skills/skill-delete/service.test.ts b/src/main/skills/skill-delete/service.test.ts index 2f92a9f70c0..0b8d1ff5e0c 100644 --- a/src/main/skills/skill-delete/service.test.ts +++ b/src/main/skills/skill-delete/service.test.ts @@ -99,16 +99,6 @@ describe('deleteSkills', () => { expect(await exists(join(aliasDirectory, 'notes.md'))).toBe(true) }) - it('removes an emptied alias-file directory', async () => { - const { home, stateDirectory, file } = await fixture() - const aliasDirectory = join(home, '.codex', 'skills', 'demo') - await mkdir(aliasDirectory, { recursive: true }) - await symlink(file, join(aliasDirectory, 'SKILL.md')) - - await run(home, stateDirectory, await request(file)) - expect(await exists(aliasDirectory)).toBe(false) - }) - it('takes the lock an install of the same destination directory would take', async () => { const { home, stateDirectory, canonicalDirectory, file } = await fixture() // Use install's literal placement-directory lock key, never canonical-file realpath. diff --git a/src/main/skills/skill-placement-reconciliation.test.ts b/src/main/skills/skill-placement-reconciliation.test.ts index 25bc43bd0d7..59818c12abd 100644 --- a/src/main/skills/skill-placement-reconciliation.test.ts +++ b/src/main/skills/skill-placement-reconciliation.test.ts @@ -107,62 +107,6 @@ describe('skill provider placement reconciliation', () => { ) }) - it('creates a verified copy when a host-owned alias operation is denied', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-skill-placement-test-')) - temporaryDirectories.push(root) - const canonicalPath = join(root, 'canonical', 'private-skill') - const providerRoot = join(root, 'provider') - await mkdir(canonicalPath, { recursive: true }) - await writeFile(join(canonicalPath, 'SKILL.md'), 'private skill') - const observed = await nativeSkillInstallFilesystem.observeSkill(canonicalPath) - - const result = await reconcileSkillProviderPlacement({ - canonicalPath, - skillName: 'private-skill', - destination: { provider: 'claude', rootPath: providerRoot, readsCanonicalRoot: false }, - previousReceipt: null, - packageDigest: observed.observedDigest, - filesystem: { - ...nativeSkillInstallFilesystem, - createAlias: async () => { - throw new Error('injected-host-alias-denial') - } - } - }) - - expect(result).toMatchObject({ topology: 'independent-copy', status: 'installed' }) - expect(await readFile(join(providerRoot, 'private-skill', 'SKILL.md'), 'utf8')).toBe( - 'private skill' - ) - }) - - it('uses host alias inspection when the client cannot stat the destination', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-skill-placement-test-')) - temporaryDirectories.push(root) - const canonicalPath = join(root, 'canonical', 'private-skill') - const providerRoot = join(root, 'provider') - await mkdir(canonicalPath, { recursive: true }) - await writeFile(join(canonicalPath, 'SKILL.md'), 'private skill') - const observed = await nativeSkillInstallFilesystem.observeSkill(canonicalPath) - const createAlias = vi.fn() - - const result = await reconcileSkillProviderPlacement({ - canonicalPath, - skillName: 'private-skill', - destination: { provider: 'claude', rootPath: providerRoot, readsCanonicalRoot: false }, - previousReceipt: null, - packageDigest: observed.observedDigest, - filesystem: { - ...nativeSkillInstallFilesystem, - createAlias, - aliasTargets: async () => true - } - }) - - expect(result).toMatchObject({ topology: 'provider-alias', status: 'unchanged' }) - expect(createAlias).not.toHaveBeenCalled() - }) - it('updates an owned copy even when host alias inspection returns false', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-skill-placement-test-')) temporaryDirectories.push(root) diff --git a/src/main/skills/skill-scan-coalescer.test.ts b/src/main/skills/skill-scan-coalescer.test.ts index 894af254d93..095251d0d2d 100644 --- a/src/main/skills/skill-scan-coalescer.test.ts +++ b/src/main/skills/skill-scan-coalescer.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { SkillScanCoalescer, SkillScanShedError } from './skill-scan-coalescer' +import { SkillScanCoalescer } from './skill-scan-coalescer' function deferred(): { promise: Promise; resolve: (value: T) => void } { let resolve!: (value: T) => void @@ -10,108 +10,6 @@ function deferred(): { promise: Promise; resolve: (value: T) => void } { } describe('SkillScanCoalescer', () => { - it('collapses concurrent callers on one key into a single scan', async () => { - const coalescer = new SkillScanCoalescer(8) - const gate = deferred() - let runs = 0 - const task = (): Promise => { - runs += 1 - return gate.promise - } - - const outcomes = Promise.all([ - coalescer.run('root', { ttlMs: 0 }, task), - coalescer.run('root', { ttlMs: 0 }, task), - coalescer.run('root', { ttlMs: 0 }, task) - ]) - gate.resolve(7) - - expect((await outcomes).map((outcome) => outcome.value)).toEqual([7, 7, 7]) - expect((await outcomes).map((outcome) => outcome.cached)).toEqual([false, true, true]) - expect(runs).toBe(1) - }) - - it('keeps distinct keys isolated, including paths differing only by case', async () => { - const coalescer = new SkillScanCoalescer(8) - const seen: string[] = [] - const run = (key: string): Promise<{ value: string }> => - coalescer.run(key, { ttlMs: 1_000 }, async () => { - seen.push(key) - return key - }) - - const [lower, upper] = await Promise.all([run('/home/a/Skills'), run('/home/a/skills')]) - - expect(lower.value).toBe('/home/a/Skills') - expect(upper.value).toBe('/home/a/skills') - expect(seen).toHaveLength(2) - }) - - it('reuses a result inside the ttl and rescans after it lapses', async () => { - let now = 1_000 - const coalescer = new SkillScanCoalescer(8, () => now) - let runs = 0 - const task = async (): Promise => { - runs += 1 - return runs - } - - expect((await coalescer.run('root', { ttlMs: 100 }, task)).cached).toBe(false) - now = 1_050 - const cached = await coalescer.run('root', { ttlMs: 100 }, task) - expect(cached).toEqual({ value: 1, cached: true }) - now = 1_101 - expect(await coalescer.run('root', { ttlMs: 100 }, task)).toEqual({ value: 2, cached: false }) - expect(runs).toBe(2) - }) - - it('retains nothing when the ttl is zero', async () => { - const coalescer = new SkillScanCoalescer(8) - let runs = 0 - const task = async (): Promise => { - runs += 1 - return runs - } - - await coalescer.run('root', { ttlMs: 0 }, task) - await coalescer.run('root', { ttlMs: 0 }, task) - - expect(runs).toBe(2) - }) - - it('bypasses cached and in-flight results when refreshing', async () => { - let now = 1_000 - const coalescer = new SkillScanCoalescer(8, () => now) - let runs = 0 - const task = async (): Promise => { - runs += 1 - return runs - } - - await coalescer.run('root', { ttlMs: 10_000 }, task) - const refreshed = await coalescer.run('root', { ttlMs: 10_000, refresh: true }, task) - - expect(refreshed).toEqual({ value: 2, cached: false }) - expect(await coalescer.run('root', { ttlMs: 10_000 }, task)).toEqual({ value: 2, cached: true }) - expect(runs).toBe(2) - }) - - // Refresh fan-out needs per-key publish ownership; a global counter would cache only the last root. - it('caches every key when a refresh fans out across roots', async () => { - const coalescer = new SkillScanCoalescer(64) - const keys = ['root-a', 'root-b', 'root-c', 'root-d'] - - await Promise.all( - keys.map((key) => coalescer.run(key, { ttlMs: 10_000, refresh: true }, async () => key)) - ) - const readBack = await Promise.all( - keys.map((key) => coalescer.run(key, { ttlMs: 10_000 }, async () => 're-walked')) - ) - - expect(readBack.map((outcome) => outcome.cached)).toEqual([true, true, true, true]) - expect(readBack.map((outcome) => outcome.value)).toEqual(keys) - }) - it('does not let a scan that started before a refresh publish its stale result', async () => { const coalescer = new SkillScanCoalescer(8) const slowScan = deferred() @@ -148,133 +46,4 @@ describe('SkillScanCoalescer', () => { cached: false }) }) - - it('does not cache a failed scan', async () => { - const coalescer = new SkillScanCoalescer(8) - let runs = 0 - - await expect( - coalescer.run('root', { ttlMs: 10_000 }, async () => { - runs += 1 - throw new Error('scan failed') - }) - ).rejects.toThrow('scan failed') - expect(await coalescer.run('root', { ttlMs: 10_000 }, async () => 5)).toEqual({ - value: 5, - cached: false - }) - expect(runs).toBe(1) - }) - - it('evicts the least recently used entry past the bound', async () => { - let now = 1_000 - const coalescer = new SkillScanCoalescer(2, () => now) - const scan = (key: string): Promise<{ cached: boolean }> => - coalescer.run(key, { ttlMs: 10_000 }, async () => key) - - await scan('a') - await scan('b') - expect((await scan('a')).cached).toBe(true) - await scan('c') - - expect((await scan('a')).cached).toBe(true) - expect((await scan('b')).cached).toBe(false) - }) - - // Use nonzero TTL to expose abandoned scans incorrectly publishing over replacements. - it('stops joining a scan that never settles, and never lets it publish later', async () => { - let now = 1_000 - const coalescer = new SkillScanCoalescer(8, () => now) - const wedged = deferred() - let runs = 0 - const task = (signal: AbortSignal): Promise => { - runs += 1 - // Model a stalled mount whose syscall never settles. - return runs === 1 - ? Promise.race([ - wedged.promise, - new Promise((_resolve, reject) => { - signal.addEventListener('abort', () => reject(signal.reason)) - }) - ]) - : Promise.resolve(runs) - } - - void coalescer.run('root', { ttlMs: 10_000 }, task).catch(() => undefined) - now = 1_100 - const joined = coalescer.run('root', { ttlMs: 10_000 }, task) - now = 40_000 - - expect(await coalescer.run('root', { ttlMs: 10_000 }, task)).toEqual({ - value: 2, - cached: false - }) - expect(runs).toBe(2) - - // Abort releases abandoned-scan callers even if the mount never answers. - await expect(joined).rejects.toThrow() - wedged.resolve(99) - expect(await coalescer.run('root', { ttlMs: 10_000 }, task)).toEqual({ value: 2, cached: true }) - }) - - it('aborts the scan it abandons so its walk stops doing filesystem work', async () => { - let now = 1_000 - const coalescer = new SkillScanCoalescer(8, () => now) - const signals: AbortSignal[] = [] - const task = (signal: AbortSignal): Promise => { - signals.push(signal) - return signals.length === 1 ? new Promise(() => {}) : Promise.resolve(2) - } - - void coalescer.run('root', { ttlMs: 10_000 }, task).catch(() => undefined) - expect(signals[0].aborted).toBe(false) - now = 40_000 - await coalescer.run('root', { ttlMs: 10_000 }, task) - - expect(signals[0].aborted).toBe(true) - // The new owner must not be aborted with its predecessor. - expect(signals[1].aborted).toBe(false) - }) - - // Keep healthy superseded callers alive; publish ownership already prevents stale caching. - it('does not abort the scan a refresh supersedes', async () => { - const coalescer = new SkillScanCoalescer(8) - const slowScan = deferred() - const signals: AbortSignal[] = [] - - const inFlight = coalescer.run('root', { ttlMs: 10_000 }, (signal) => { - signals.push(signal) - return slowScan.promise - }) - await coalescer.run('root', { ttlMs: 10_000, refresh: true }, async () => 'after-install') - - expect(signals[0].aborted).toBe(false) - slowScan.resolve('before-install') - expect((await inFlight).value).toBe('before-install') - }) - - // A stuck syscall cannot settle on abort; budget abandoned scans until actual completion. - it('sheds a replacement once too many abandoned scans are still live', async () => { - let now = 1_000 - const coalescer = new SkillScanCoalescer(64, () => now) - const task = (): Promise => new Promise(() => {}) - const keys = Array.from({ length: 17 }, (_unused, index) => `root-${index}`) - - // Each stalled root spends abandonment budget when a caller seeks a replacement. - for (const key of keys) { - void coalescer.run(key, { ttlMs: 10_000 }, task).catch(() => undefined) - } - now = 40_000 - const shed: string[] = [] - for (const key of keys) { - void coalescer.run(key, { ttlMs: 10_000 }, task).catch((error: unknown) => { - if (error instanceof SkillScanShedError) { - shed.push(key) - } - }) - } - await new Promise((resolve) => setImmediate(resolve)) - - expect(shed).toEqual(['root-16']) - }) }) diff --git a/src/main/skills/skill-transaction-startup-recovery.test.ts b/src/main/skills/skill-transaction-startup-recovery.test.ts index 099ff0ed446..b9ba7c6c414 100644 --- a/src/main/skills/skill-transaction-startup-recovery.test.ts +++ b/src/main/skills/skill-transaction-startup-recovery.test.ts @@ -213,23 +213,4 @@ describe('skill transaction startup recovery', () => { expect(await readFile(join(installed.canonicalPath, 'SKILL.md'), 'utf8')).toContain('# Keep') expect(await readSkillInstallReceipt(stateDirectory, installed.canonicalPath)).toBeTruthy() }) - - it('bounds corrupt journal scanning and leaves unknown files untouched', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-skill-startup-bounds-test-')) - roots.push(root) - const stateDirectory = join(root, 'state') - const journalDirectory = join(stateDirectory, 'journals') - await mkdir(journalDirectory, { recursive: true }) - await Promise.all( - Array.from({ length: 65 }, (_, index) => - writeFile(join(journalDirectory, `${String(index).padStart(2, '0')}.json`), '{}') - ) - ) - - const report = await recoverPendingSkillTransactions(stateDirectory) - - expect(report).toMatchObject({ scanned: 0, recovered: 0, truncated: true }) - expect(report.failures).toHaveLength(64) - expect(await readFile(join(journalDirectory, '00.json'), 'utf8')).toBe('{}') - }) }) diff --git a/src/main/ssh/connection/ssh-connection-github-probe.test.ts b/src/main/ssh/connection/ssh-connection-github-probe.test.ts deleted file mode 100644 index 1798fdba869..00000000000 --- a/src/main/ssh/connection/ssh-connection-github-probe.test.ts +++ /dev/null @@ -1,294 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { resetSshConnectionMocks, spawnSystemSshCommandMock } from './ssh-connection-test-harness' -import { - createCallbacks, - createFailingSystemCommandChannel, - createResolvedConfig, - createTarget -} from './ssh-connection-test-fixtures' -import { SshConnection } from './ssh-connection' -import { resolveWithSshG } from '../config/ssh-g-config-resolution' - -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() -) -vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() -) -vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( - await importOriginal() - ) -) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( - await importOriginal() - ) -) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() -) -vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() -) -vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( - await importOriginal() - ) -) - -describe('SshConnection', () => { - beforeEach(() => { - resetSshConnectionMocks() - }) - - it('accepts GitHub restricted-shell SSH probes with resolved user fallback', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: 'git' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: undefined - }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - }) - - it('uses fresh OpenSSH user for imported GitHub targets', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: 'git' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - source: 'ssh-config', - configHost: 'github.com', - host: 'github.com', - username: 'stale-user' - }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - }) - - it('accepts GitHub restricted-shell SSH probes with resolved host and target username', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: undefined }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'git' - }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - }) - - it('accepts ssh.github.com restricted-shell SSH probes', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'ssh.github.com', user: 'git' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'ssh.github.com', - host: 'ssh.github.com', - username: 'git' - }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - }) - - it('accepts GitHub restricted-shell SSH probes with the real git:// advisory transcript', async () => { - // Real 4-line stderr GitHub returns for an invalid command (issue #6988). - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: 'git' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel( - 1, - 'Invalid command: echo ORCA-SYSTEM-SSH-OK\n' + - ' You appear to be using ssh to clone a git:// URL.\n' + - ' Make sure your core.gitProxy config option and the\n' + - ' GIT_PROXY_COMMAND environment variable are NOT set.' - ) - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'git' - }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - }) - - it('accepts GitHub restricted-shell SSH probes when OpenSSH config resolution fails', async () => { - vi.stubEnv('ORCA_SSH_FORCE_SYSTEM_TRANSPORT', '1') - vi.mocked(resolveWithSshG).mockRejectedValueOnce(new Error('ssh -G failed')) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'git' - }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - }) - - it('rejects non-GitHub SSH probes with GitHub invalid-command text', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'gitlab.com', user: 'git' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'git' - }), - createCallbacks() - ) - - await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)') - expect(conn.usesSystemSshTransport()).toBe(false) - }) - - it('accepts GitHub restricted-shell SSH probes when target username overrides resolved user', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: 'deploy' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'git' - }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - }) - - it('rejects GitHub restricted-shell SSH probes when target username overrides resolved git user', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: 'git' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'deploy' - }), - createCallbacks() - ) - - await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)') - expect(conn.usesSystemSshTransport()).toBe(false) - }) - - it('rejects GitHub restricted-shell SSH probes with extra stderr text', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: 'git' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel( - 1, - 'remote: rejected\nInvalid command: echo ORCA-SYSTEM-SSH-OK\ntry again' - ) - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'git' - }), - createCallbacks() - ) - - await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)') - expect(conn.usesSystemSshTransport()).toBe(false) - }) - - it('rejects GitHub restricted-shell SSH probes for non-git users', async () => { - vi.mocked(resolveWithSshG).mockResolvedValueOnce( - createResolvedConfig({ hostname: 'github.com', user: 'deploy' }) - ) - spawnSystemSshCommandMock.mockImplementation(() => - createFailingSystemCommandChannel(1, 'Invalid command: echo ORCA-SYSTEM-SSH-OK') - ) - const conn = new SshConnection( - createTarget({ - configHost: 'github.com', - host: 'github.com', - username: 'deploy' - }), - createCallbacks() - ) - - await expect(conn.connect()).rejects.toThrow('System SSH probe failed (exit 1)') - expect(conn.usesSystemSshTransport()).toBe(false) - }) -}) diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts b/src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts index 8aa1134b81c..a7be8df24f4 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts +++ b/src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts @@ -1,6 +1,6 @@ /** Relay restarts reuse socket and pty-1 ids; identify panes by endpoint plus relay-reported incarnation. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' +import '../../../shared/ssh-pty-id' import type { SshRemotePtyLease } from '../../../shared/ssh-types' import { ENDPOINT, @@ -110,144 +110,4 @@ describe('a relay restarted at the same socket', () => { await vi.advanceTimersByTimeAsync(10_000) expect(relay.shutdowns).toEqual([]) }) - - it('ignores the restarted relay’s exit report until its listing shows the pane’s own shell', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge({ - openClient: async () => { - const client = fakeClient(relay) - const list = client.list.bind(client) - client.list = async () => { - // The replacement's own pty-1 exits after the reconnect, before its listing lands. - if (relay.clients.length > 1) { - client.emitExit('pty-1', 9) - } - return list() - } - relay.clients.push(client) - return client - } - }) - await subject.refresh() - relay.clients[0].drop() - relay.incarnations.set('pty-1', 'inc-2') - await vi.advanceTimersByTimeAsync(2_000) - expect(relay.clients).toHaveLength(2) - expect(events.exits).toEqual([]) - expect(leases[0].state).toBe('detached') - }) - - it('keeps the same relay’s exit report that raced its reconnect listing', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge({ - openClient: async () => { - const client = fakeClient(relay) - const list = client.list.bind(client) - client.list = async () => { - const rows = await list() - // The shell exits after the reconnected relay answered, before its listing lands. - if (relay.clients.length > 1) { - client.emitExit('pty-1', 3) - } - return rows - } - relay.clients.push(client) - return client - } - }) - await subject.refresh() - relay.clients[0].drop() - await vi.advanceTimersByTimeAsync(2_000) - expect(events.exits).toEqual([PTY]) - expect(leases[0].state).toBe('terminated') - expect(subject.snapshot()).toEqual([]) - }) - - it('takes an exit report on the connection that listed the pane, even after a refused attach', async () => { - relay.incarnations.set('pty-1', 'inc-1') - let exhaustive = true - const subject = bridge({ - listEndpoints: async () => ({ kind: 'listed', endpoints: [ENDPOINT], exhaustive }) - }) - await subject.refresh() - exhaustive = false - relay.attachError = new Error('PTY busy') - await expect(subject.attach(PTY)).resolves.toEqual({ status: 'unverifiable' }) - relay.clients[0].emitExit('pty-1', 4) - expect(events.exits).toEqual([PTY]) - expect(leases[0].state).toBe('terminated') - }) - - it('takes an exit report on the connection that listed the pane after a listing missed it', async () => { - relay.incarnations.set('pty-1', 'inc-1') - // A second pane keeps the connection open. - leases = [lease(), lease({ ptyId: 'pty-2', tabId: 'tab-2', leafId: 'leaf-2' })] - relay.ptys.add('pty-2') - let exhaustive = true - const subject = bridge({ - listEndpoints: async () => ({ kind: 'listed', endpoints: [ENDPOINT], exhaustive }) - }) - await subject.refresh() - // The relay answers without the pane while the census is incomplete: not yet proof. - exhaustive = false - relay.ptys.delete('pty-1') - await subject.refresh() - expect(subject.snapshot()).toContainEqual(expect.objectContaining({ state: 'unverifiable' })) - expect(relay.clients[0].closed).toBe(false) - relay.clients[0].emitExit('pty-1', 6) - expect(events.exits).toEqual([PTY]) - expect(leases[0].state).toBe('terminated') - expect(leases[1].state).toBe('detached') - }) - - it('reattaches the same shell when the relay lists its incarnation again', async () => { - relay.incarnations.set('pty-1', 'inc-1') - const subject = bridge() - await subject.refresh() - relay.clients[0].drop() - await vi.advanceTimersByTimeAsync(2_000) - expect(subject.snapshot()).toEqual([expect.objectContaining({ state: 'live' })]) - subject.write(PTY, 'ls\r') - expect(relay.clients.at(-1)!.writes).toEqual(['ls\r']) - }) - - it('keeps an epoch-scoped exit reported before the reconnect listing, even when incomplete', async () => { - leases = [lease({ ptyId: 'pty2:epoch-a:1' })] - relay.ptys = new Set(['pty2:epoch-a:1']) - let exhaustive = true - const subject = bridge({ - listEndpoints: async () => ({ kind: 'listed', endpoints: [ENDPOINT], exhaustive }), - openClient: async () => { - const client = fakeClient(relay) - const list = client.list.bind(client) - client.list = async () => { - if (relay.clients.length > 1) { - client.emitExit('pty2:epoch-a:1', 5) - relay.ptys.clear() - } - return list() - } - relay.clients.push(client) - return client - } - }) - await subject.refresh() - exhaustive = false - relay.clients[0].drop() - await vi.advanceTimersByTimeAsync(2_000) - expect(events.exits).toEqual([toAppSshPtyId(TARGET, 'pty2:epoch-a:1')]) - expect(leases[0].state).toBe('terminated') - }) - - it('never binds an epoch-scoped id to a restart, whose ids carry a new epoch', async () => { - leases = [lease({ ptyId: 'pty2:epoch-a:1' })] - relay.ptys = new Set(['pty2:epoch-a:1']) - const subject = bridge() - await subject.refresh() - relay.clients[0].drop() - relay.ptys = new Set(['pty2:epoch-b:1']) - await vi.advanceTimersByTimeAsync(2_000) - subject.write(toAppSshPtyId(TARGET, 'pty2:epoch-a:1'), 'ls\r') - expect(relay.clients.flatMap((client) => client.writes)).toEqual([]) - }) }) diff --git a/src/main/ssh/orcad-migration-source-fence.test.ts b/src/main/ssh/orcad-migration-source-fence.test.ts index bbaaaa5b281..512b4dd992f 100644 --- a/src/main/ssh/orcad-migration-source-fence.test.ts +++ b/src/main/ssh/orcad-migration-source-fence.test.ts @@ -16,8 +16,8 @@ import { } from './orcad-migration-source-fence' import type { OrcadMigrationTerminalVerdict } from './orcad-migration-terminal-gate' import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' -import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' -import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../shared/orcad-migration/orcad-migration-manifest-validation' +import './orcad-migration-manifest-export' +import '../../shared/orcad-migration/orcad-migration-manifest-validation' const TARGET: SshTarget = { id: 'ssh-prod', @@ -69,29 +69,6 @@ function setup(displayName = 'App') { } describe('migration source fence', () => { - it('journals, then fences, then flushes, all before returning', async () => { - const harness = setup() - const order: string[] = [] - const journalWrite = vi - .spyOn(harness.claims, 'fenceForMigration') - .mockImplementation((...args) => { - order.push( - listOrcadMigrationSourceCutovers(harness.userDataPath).length ? 'journal' : 'none' - ) - order.push('fence') - return SshTargetOrcadClaims.prototype.fenceForMigration.apply(harness.claims, args) - }) - const flush = vi.spyOn(harness.claims, 'flush').mockImplementation(async () => { - order.push(harness.target().orcadFence ? 'flush-after-fence' : 'flush-before-fence') - }) - const result = await harness.fence() - expect(result).toMatchObject({ outcome: 'fenced', resumed: false }) - expect(order).toEqual(['journal', 'fence', 'flush-after-fence']) - expect(getManagedOrcadFenceEnvironmentId(harness.target())).toBe('env-1') - journalWrite.mockRestore() - flush.mockRestore() - }) - it('keeps the journal out of the profile, where an older build would strip it', async () => { const harness = setup() const result = await harness.fence() @@ -112,19 +89,6 @@ describe('migration source fence', () => { expect(onDisk?.manifest.payload.repositories.map((repo) => repo.id)).toEqual(['repo-1']) }) - it('resumes the same migration instead of starting a second one', async () => { - const harness = setup() - const first = await harness.fence() - const second = await harness.fence({ - terminalProof: { verdict: 'live', ptyIds: ['p'], reason: 'x' } - }) - expect(second).toMatchObject({ outcome: 'fenced', resumed: true }) - expect( - first.outcome === 'fenced' && second.outcome === 'fenced' && second.cutover.migrationId - ).toBe(first.outcome === 'fenced' && first.cutover.migrationId) - expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toHaveLength(1) - }) - it('treats a fence whose journal was lost as unverifiable and never releases it', async () => { const harness = setup() await harness.fence() @@ -141,16 +105,6 @@ describe('migration source fence', () => { expect(getManagedOrcadFenceEnvironmentId(harness.target())).toBe('env-1') }) - it('treats a journal whose fence an older build removed as stale, granting nothing', async () => { - const harness = setup() - await harness.fence() - harness.store.updateSshTarget(TARGET.id, { orcadFence: undefined }) - expect(resolveOrcadMigrationFence(harness.userDataPath, harness.target()).state).toBe( - 'stale-journal' - ) - await expect(harness.fence()).resolves.toMatchObject({ code: 'orcad_migration_stale_journal' }) - }) - it('fails closed on an unreadable journal', async () => { const harness = setup() await harness.fence() @@ -168,33 +122,6 @@ describe('migration source fence', () => { await expect(harness.fence()).rejects.toThrow('stays fenced') }) - it.each<[OrcadMigrationTerminalVerdict, string]>([ - [{ verdict: 'live', ptyIds: ['p'], reason: 'terminals run' }, 'live'], - [{ verdict: 'unverifiable', ptyIds: ['p'], reason: 'relay silent' }, 'unverifiable'] - ])('refuses before fencing when terminals are %j', async (terminalProof, verdict) => { - const harness = setup() - await expect(harness.fence({ terminalProof })).resolves.toMatchObject({ - outcome: 'refused', - verdict - }) - expect(harness.target().orcadFence).toBeUndefined() - expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([]) - }) - - it('keeps a blocker it could not read unverifiable, never live', async () => { - const harness = setup() - vi.spyOn(harness.store, 'inspectOrcadMigrationUntransferredDependencies').mockImplementation( - () => { - throw new Error('census failed') - } - ) - await expect(harness.fence()).resolves.toMatchObject({ - outcome: 'refused', - verdict: 'unverifiable', - code: 'orcad_migration_preflight_blocked' - }) - }) - it('releases its own fence when a terminal appeared before the fence took hold', async () => { const harness = setup() const flush = vi.spyOn(harness.claims, 'flush').mockImplementation(async () => { @@ -209,21 +136,4 @@ describe('migration source fence', () => { expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([]) flush.mockRestore() }) - - it('refuses, without a journal or fence, a manifest under the export cap that no request can carry', async () => { - const probe = setup() - const baseline = JSON.stringify( - createOrcadMigrationManifest(probe.store, probe.target()) - ).length - // Under the export cap, over the sealed-frame request budget: stage, state and abort all refuse. - const harness = setup('x'.repeat(MAX_ORCAD_MIGRATION_MANIFEST_BYTES - 200 - baseline)) - const manifestBytes = JSON.stringify( - createOrcadMigrationManifest(harness.store, harness.target()) - ).length - expect(manifestBytes).toBeLessThanOrEqual(MAX_ORCAD_MIGRATION_MANIFEST_BYTES) - - await expect(harness.fence()).rejects.toThrow(/\(orcad_migration_manifest_too_large\)$/) - expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([]) - expect(harness.target().orcadFence).toBeUndefined() - }) }) diff --git a/src/main/ssh/orcad-stdio-bridge.test.ts b/src/main/ssh/orcad-stdio-bridge.test.ts index 679ba2a2b9c..1a79ed54477 100644 --- a/src/main/ssh/orcad-stdio-bridge.test.ts +++ b/src/main/ssh/orcad-stdio-bridge.test.ts @@ -2,11 +2,11 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node import { tmpdir } from 'node:os' import { join } from 'node:path' import type { Server } from 'node:net' -import type { EventEmitter } from 'node:events' + import { PassThrough } from 'node:stream' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { OrcadStdioBridgeUnavailableError } from '../orcad/orcad-host-unavailable' -import { checkOrcadStdioBridge, type OrcadStdioBridge } from './orcad-stdio-bridge' +import '../orcad/orcad-host-unavailable' +import './orcad-stdio-bridge' import { orcadPosixStdioBridgeCommand, type OrcadStdioBridgeMode @@ -20,7 +20,7 @@ import { startEchoServer } from '../managed-server/lifecycle/orcad-stdio-bridge-test-channel' import { ORCAD_WINDOWS_HOST_SCRIPT } from '../managed-server/host-state/orcad-windows-host-script' -import type { OrcadHostTransport } from './orcad-host-transport' + import type { RemoteCommandChannel } from '../managed-server/install/remote-install-transport' const POSIX = process.platform !== 'win32' @@ -76,17 +76,6 @@ function posixHome(withRuntime: boolean): string { return home } -function connectionRunning(channel: () => RemoteCommandChannel): OrcadHostTransport { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check calls only exec. - return { exec: async () => channel() } as unknown as OrcadHostTransport -} - -const posixBridge = (port: number): OrcadStdioBridge => ({ - command: orcadPosixStdioBridgeCommand(port), - mode: 'raw', - wrapCommand: true -}) - describe.runIf(POSIX)('the POSIX stdio bridge command', () => { it('pipes every byte to orcad and back on the store’s pinned Node', async () => { const home = posixHome(true) @@ -101,19 +90,6 @@ describe.runIf(POSIX)('the POSIX stdio bridge command', () => { expect((await roundTrip(channel, 'raw')).equals(PAYLOAD)).toBe(true) }) - it('proves the bridge runs even when orcad refuses the dial', async () => { - const closed = await startEchoServer() - closed.server.close() - const home = posixHome(true) - const conn = connectionRunning(() => - spawnLocalBridgeChannel('/bin/sh', ['-c', posixBridge(closed.port).command], { - ...process.env, - HOME: home - }) - ) - await expect(checkOrcadStdioBridge(conn, posixBridge(closed.port))).resolves.toBe('running') - }) - it('runs on a machine home’s Node, skipping a store runtime that cannot start here', async () => { const home = posixHome(false) // Another machine's runtime on the shared home, e.g. built for another architecture. @@ -133,19 +109,6 @@ describe.runIf(POSIX)('the POSIX stdio bridge command', () => { ) expect((await roundTrip(channel, 'raw')).equals(PAYLOAD)).toBe(true) }) - - it('reports a host with no pinned Node as one the bridge cannot run on', async () => { - const home = posixHome(false) - const conn = connectionRunning(() => - spawnLocalBridgeChannel('/bin/sh', ['-c', posixBridge(echo.port).command], { - ...process.env, - HOME: home - }) - ) - await expect(checkOrcadStdioBridge(conn, posixBridge(echo.port))).rejects.toBeInstanceOf( - OrcadStdioBridgeUnavailableError - ) - }) }) describe('the Windows host script’s stdio-bridge op', () => { @@ -183,79 +146,4 @@ describe('reading a bridge channel', () => { await new Promise((resolve) => decoder.on('end', resolve)) expect(Buffer.concat(out)).toEqual(Buffer.from([0, 1, 0xff])) }) - - it('fails a channel that prints no sentinel within its bound', async () => { - const decoder = new OrcadStdioBridgeDecoder('raw') - const failed = new Promise((resolve) => decoder.on('error', resolve)) - decoder.write(Buffer.alloc(70 * 1024, 0x61)) - await expect(failed).resolves.toBeInstanceOf(Error) - }) -}) - -function scriptedChannel(): RemoteCommandChannel & EventEmitter & { stderr: PassThrough } { - const channel = Object.assign(new PassThrough(), { - stderr: new PassThrough(), - close: () => {} - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check uses only the stream, `stderr`, `close`, and events. - return channel as unknown as RemoteCommandChannel & EventEmitter & { stderr: PassThrough } -} - -describe('checking a bridge before the tunnel relies on it', () => { - it('reads a channel lost without an exit status as unverifiable, never as unavailable', async () => { - const channel = scriptedChannel() - const check = checkOrcadStdioBridge( - connectionRunning(() => channel), - posixBridge(1) - ) - await new Promise((resolve) => setImmediate(resolve)) - channel.emit('close') - await expect(check).resolves.toBe('unverifiable') - }) - - it('reads a silent bridge as unverifiable once the check times out', async () => { - const channel = scriptedChannel() - await expect( - checkOrcadStdioBridge( - connectionRunning(() => channel), - posixBridge(1), - 20 - ) - ).resolves.toBe('unverifiable') - }) - - it('reads a reported exit with no sentinel as a host the bridge cannot run on', async () => { - const channel = scriptedChannel() - const check = checkOrcadStdioBridge( - connectionRunning(() => channel), - posixBridge(1) - ) - await new Promise((resolve) => setImmediate(resolve)) - channel.stderr.write('node.exe is not recognized') - channel.emit('exit', 9009) - channel.emit('close') - await expect(check).rejects.toThrow(/exit 9009: node.exe is not recognized/u) - }) - - it('reads a script cut short with no sentinel as unverifiable, not a permanent refusal', async () => { - const channel = scriptedChannel() - const check = checkOrcadStdioBridge( - connectionRunning(() => channel), - posixBridge(1) - ) - await new Promise((resolve) => setImmediate(resolve)) - channel.emit('exit', 1) - channel.emit('close') - await expect(check).resolves.toBe('unverifiable') - }) - - it('reads an exec channel sshd would not open as unverifiable', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check calls only exec. - const conn = { - exec: async () => { - throw new Error('open failed') - } - } as unknown as OrcadHostTransport - await expect(checkOrcadStdioBridge(conn, posixBridge(1))).resolves.toBe('unverifiable') - }) }) diff --git a/src/main/ssh/orcad-update-admission-fence.test.ts b/src/main/ssh/orcad-update-admission-fence.test.ts deleted file mode 100644 index e7ff3aab4ab..00000000000 --- a/src/main/ssh/orcad-update-admission-fence.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -// Final census holds admission closed through stop and reopens it if incumbent keeps serving. -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ExecCommandModule from './remote-exec/remote-exec-command' -import type * as RecordFile from '../managed-server/install/orcad-remote-record-file' -import type * as InstallLock from '../managed-server/install/remote-install-lock' -import type * as VersionedInstall from '../managed-server/install/remote-versioned-install' - -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand: vi.fn() -})) -vi.mock('../../shared/shell/launch/shell-argument-quoting', () => ({ - quotePosixShell: (s: string) => `'${s}'` -})) -vi.mock('../managed-server/install/remote-install-lock', async (importOriginal) => ({ - ...(await importOriginal()), - acquireInstallLock: vi.fn() -})) -vi.mock('../managed-server/install/orcad-remote-record-file', async (importOriginal) => ({ - ...(await importOriginal()), - writeAtomicOrcadRemoteRecord: vi.fn() -})) -vi.mock('../managed-server/install/remote-versioned-install', async (importOriginal) => ({ - ...(await importOriginal()), - readLocalFullVersion: () => '0.2.0+bb01' -})) -vi.mock('../managed-server/install/orcad-remote-install', () => ({ installOrcadBundle: vi.fn() })) -vi.mock('../managed-server/install/orcad-remote-preflight', () => ({ - preflightInstalledOrcad: vi.fn(async () => ({})) -})) -vi.mock('./orcad-local-build-hash', () => ({ - computeLocalOrcadBuildHash: () => 'abc123def4567890' -})) - -import { execCommand } from './remote-exec/remote-exec-command' -import { preflightInstalledOrcad } from '../managed-server/install/orcad-remote-preflight' -import { PROTOCOL_VERSION } from '../daemon/protocol/daemon-protocol-version' -import { acquireInstallLock } from '../managed-server/install/remote-install-lock' -import { writeAtomicOrcadRemoteRecord } from '../managed-server/install/orcad-remote-record-file' -import { deployOrcad } from './orcad-remote-deploy' -import { getRemoteHostPlatform } from './ssh-remote-platform' -import { - ORCAD_UPDATE_ADMISSION_FENCE_MS, - ORCAD_UPDATE_ADMISSION_STOP_BY_MS, - type OrcadTerminalCensus -} from '../../shared/orcad-terminal-census' - -import { - TerminalUpdateAdmission, - TerminalUpdateAdmissionClosedError -} from '../runtime/terminal/stop/terminal-update-admission' -import { - FakeOrcadHost, - NEW, - OLD -} from '../managed-server/activation/orcad-activation-host-test-harness' - -let host = FakeOrcadHost.deployedOld() -let clockMs = Date.parse('2026-02-02T00:00:00.000Z') -let admission = new TerminalUpdateAdmission(async () => []) - -const IDLE = { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 3 } -const LIVE = { liveSessions: 1, startedSinceActivation: 1, daemonProtocolVersion: 3 } -const UNREAD = { liveSessions: null, startedSinceActivation: null, daemonProtocolVersion: null } - -function deploy( - recount: OrcadTerminalCensus | Error = IDLE, - force?: boolean, - census: OrcadTerminalCensus = IDLE -) { - const recountCensus = vi.fn(async () => { - admission.close(ORCAD_UPDATE_ADMISSION_FENCE_MS) - if (recount instanceof Error) { - throw recount - } - return recount - }) - const releaseIncumbentAdmission = vi.fn(async () => { - admission.close(0) - }) - const result = deployOrcad({ - conn: Object.create(null), - host: getRemoteHostPlatform('linux-x64'), - remoteHome: '/home/work', - nodePath: '/usr/bin/node', - userDataDir: '/home/work/.orca', - bindHost: '127.0.0.1', - port: 7777, - readinessTimeoutMs: 50, - sleep: async () => {}, - now: () => new Date(clockMs), - localOrcadDir: '/local/out/orcad', - target: 'linux-x64-glibc217', - census, - recountCensus, - releaseIncumbentAdmission, - ...(force !== undefined ? { force } : {}) - }) - return { result, recountCensus, releaseIncumbentAdmission } -} - -beforeEach(() => { - vi.clearAllMocks() - host = FakeOrcadHost.deployedOld() - clockMs = Date.parse('2026-02-02T00:00:00.000Z') - admission = new TerminalUpdateAdmission(async () => []) - vi.mocked(execCommand).mockImplementation(async (_conn, command) => host.exec(command)) - vi.mocked(acquireInstallLock).mockImplementation(async (_conn, _dir, _host, options) => { - host.acquireFence(options) - }) - vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => - host.write(path, contents) - ) -}) - -describe("an update's terminal admission fence", () => { - it('refuses a terminal opened between the last census and the stop, then stops', async () => { - const refusals: unknown[] = [] - vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => { - // A user opens a terminal while the update records its transaction, after the recount. - if (path.endsWith('transaction.json') && host.alive.has(OLD)) { - refusals.push(await admission.admit(undefined).catch((error: unknown) => error)) - } - host.write(path, contents) - }) - const { result, releaseIncumbentAdmission } = deploy() - - await expect(result).resolves.toMatchObject({ outcome: 'installed-and-activated' }) - expect(refusals[0]).toBeInstanceOf(TerminalUpdateAdmissionClosedError) - expect([...host.alive]).toEqual([NEW]) - expect(releaseIncumbentAdmission).not.toHaveBeenCalled() - }) - - it.each([ - [LIVE, false, 'orcad_update_terminals_running'], - [{ ...LIVE, inProcessSessions: 1 }, true, 'orcad_update_ends_in_process_terminals'], - [UNREAD, true, 'orcad_update_daemon_protocol_unverifiable'], - [new Error('tunnel closed'), false, 'orcad_update_terminal_census_unavailable'] - ])( - 'defers on a recount of %j and reopens admission (force: %s)', - async (recount, force, code) => { - const { result, recountCensus } = deploy(recount, force) - - await expect(result).resolves.toMatchObject({ outcome: 'installed-not-activated', code }) - expect(recountCensus).toHaveBeenCalledTimes(1) - expect([...host.alive]).toEqual([OLD]) - expect(host.commands.some((command) => command.includes('kill -TERM'))).toBe(false) - // The incumbent keeps serving, so it takes terminals again now, not when the fence lapses. - expect(admission.isClosed()).toBe(false) - } - ) - - it('reopens admission when the first mutation after the recount fails before any stop', async () => { - vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => { - if (path.endsWith('transaction.json')) { - throw new Error('disk full') - } - host.write(path, contents) - }) - const { result, releaseIncumbentAdmission } = deploy() - - await expect(result).rejects.toThrow('disk full') - expect([...host.alive]).toEqual([OLD]) - expect(releaseIncumbentAdmission).toHaveBeenCalledTimes(1) - expect(admission.isClosed()).toBe(false) - }) - - it.each([ - ['SIGNAL_FAILED', false], - ['STILL_RUNNING', true] - ])( - 'after a stop answering %s, reopens admission only if no stop can still land', - async (answer, underway) => { - vi.mocked(execCommand).mockImplementation(async (_conn, command) => - command.includes('kill -TERM') ? answer : host.exec(command) - ) - const { result } = deploy() - - await expect(result).resolves.toMatchObject({ code: 'orcad_outgoing_stop_incomplete' }) - expect(admission.isClosed()).toBe(underway) - } - ) - - it('stops nothing once the fence may have lapsed before the stop could be sent', async () => { - vi.mocked(writeAtomicOrcadRemoteRecord).mockImplementation(async (_target, path, contents) => { - if (path.endsWith('transaction.json')) { - clockMs += ORCAD_UPDATE_ADMISSION_STOP_BY_MS + 1 - } - host.write(path, contents) - }) - const { result } = deploy() - - await expect(result).resolves.toMatchObject({ - outcome: 'installed-not-activated', - code: 'orcad_update_terminal_census_unavailable' - }) - expect(host.commands.some((command) => command.includes('kill -TERM'))).toBe(false) - expect([...host.alive]).toEqual([OLD]) - expect(admission.isClosed()).toBe(false) - }) - - describe('on a host whose census cannot name mixed daemon generations', () => { - const MIXED = { liveSessions: 2, startedSinceActivation: null, daemonProtocolVersion: null } - const answer = (liveDaemonProtocols: number[]) => ({ - type: 'orca_profile_state_ready' as const, - nonce: '00000000-0000-4000-8000-000000000000', - runtime: 'node' as const, - runtimeVersion: process.versions.node, - artifactVersion: '0.2.0+abc123def456', - sqliteVersion: '3.50.0', - revision: 1, - liveDaemonProtocols - }) - - it('asks the candidate about the served data root and updates when it attaches every generation', async () => { - vi.mocked(preflightInstalledOrcad).mockResolvedValueOnce( - answer([PROTOCOL_VERSION - 1, PROTOCOL_VERSION]) - ) - const { result } = deploy(MIXED, true, MIXED) - - await expect(result).resolves.toMatchObject({ outcome: 'installed-and-activated' }) - expect(preflightInstalledOrcad).toHaveBeenCalledWith( - expect.objectContaining({ probeDaemonsUnder: '/home/work/.orca' }) - ) - }) - - it('stops nothing when the candidate sees a generation it cannot attach', async () => { - vi.mocked(preflightInstalledOrcad).mockResolvedValueOnce( - answer([PROTOCOL_VERSION, PROTOCOL_VERSION + 1]) - ) - const { result } = deploy(MIXED, true, MIXED) - - await expect(result).resolves.toMatchObject({ - outcome: 'installed-not-activated', - code: 'orcad_update_strands_live_terminals' - }) - expect([...host.alive]).toEqual([OLD]) - }) - }) -}) diff --git a/src/main/ssh/sftp-upload-pipeline.test.ts b/src/main/ssh/sftp-upload-pipeline.test.ts index 34d44ee3e96..a242c46c1b6 100644 --- a/src/main/ssh/sftp-upload-pipeline.test.ts +++ b/src/main/ssh/sftp-upload-pipeline.test.ts @@ -1,12 +1,12 @@ import { EventEmitter } from 'node:events' -import { mkdtemp, mkdir, readdir, readlink, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, readdir, readlink, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, posix } from 'node:path' import type { SFTPWrapper, WriteStreamOptions } from 'ssh2' import { SFTP } from 'ssh2/lib/protocol/SFTP.js' import { describe, expect, it, vi } from 'vitest' import { uploadSshDirectory } from './connection/ssh-connection-file-transfers' -import { uploadDirectory } from './sftp-upload' +import './sftp-upload' function uploadSession(options?: { stalledCloses?: boolean @@ -158,46 +158,6 @@ async function expectLocalFilesClosed(dir: string): Promise { } describe('directory upload pipeline', () => { - it('overlaps four small files, preserves bytes, and creates parents before child writes', async () => { - const dir = await mkdtemp(join(tmpdir(), 'orca-sftp-pipeline-')) - const fixture = uploadSession({ stalledCloses: true }) - const files = new Map() - let upload: Promise | undefined - try { - await mkdir(join(dir, 'nested')) - for (let index = 0; index < 12; index++) { - const path = index < 6 ? `${index}.bin` : `nested/${index}.bin` - const contents = Buffer.alloc(1024 + index * 521, index) - files.set(`/remote/${path}`, contents) - await writeFile(join(dir, path), contents) - } - upload = uploadDirectory(fixture.sftp, dir, '/remote', dir, { exclusive: true }) - void upload.catch(() => {}) - await vi.waitFor(() => expect(fixture.closes.size).toBe(4)) - expect(fixture.opened).toHaveLength(4) - fixture.releaseCloses() - await upload - - expect(fixture.peakHandles()).toBe(4) - expect(fixture.peakWindow()).toBe(4 * 64 * 1024) - expect(fixture.windows.size).toBe(0) - expect(fixture.contents.size).toBe(files.size) - for (const [path, expected] of files) { - const pieces = fixture.contents.get(path) - expect(pieces).toBeDefined() - const actual = Buffer.concat( - [...(pieces ?? [])].sort(([a], [b]) => a - b).map(([, chunk]) => chunk) - ) - expect(actual.equals(expected)).toBe(true) - } - } finally { - fixture.releaseCloses() - fixture.sftp.emit('close') - await upload?.catch(() => {}) - await rm(dir, { recursive: true, force: true }) - } - }) - it('preserves the first write failure while closing a sibling stalled in CLOSE', async () => { const dir = await mkdtemp(join(tmpdir(), 'orca-sftp-pipeline-')) const settings = { stalledCloses: true, heldWrite: '' } diff --git a/src/main/ssh/ssh-host-key-verifier.test.ts b/src/main/ssh/ssh-host-key-verifier.test.ts index cb810ade064..304765dedf7 100644 --- a/src/main/ssh/ssh-host-key-verifier.test.ts +++ b/src/main/ssh/ssh-host-key-verifier.test.ts @@ -2,8 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import { parseKnownHosts } from './config/ssh-known-hosts' import { createHostKeyVerifier, - getDefaultServerHostKeyAlgorithms, - hostKeyFingerprintOf, orderServerHostKeyAlgorithms, type HostKeyVerifierDeps } from './ssh-host-key-verifier' @@ -54,10 +52,6 @@ describe('the ssh2 host key verifier', () => { expect(run({ entries }).accepted).toBe(true) }) - it('accepts a key our own store already holds', () => { - expect(run({ isTrusted: () => 'match' }).accepted).toBe(true) - }) - it('rejects a changed key', () => { const entries = parseKnownHosts(`example.com ssh-ed25519 ${ED_B}`) expect(run({ entries }).accepted).toBe(false) @@ -95,77 +89,7 @@ describe('the ssh2 host key verifier', () => { expect(accepted).toBe(false) }) - it('does not record a key for a superseded attempt', () => { - const rememberHostKey = vi.fn() - run({ isCurrentAttempt: () => false, rememberHostKey }) - expect(rememberHostKey).not.toHaveBeenCalled() - }) - - describe('remembering', () => { - it('records a first-contact key', () => { - const rememberHostKey = vi.fn() - run({ rememberHostKey }) - expect(rememberHostKey).toHaveBeenCalledWith( - expect.objectContaining({ - host: 'example.com', - port: 22, - keyType: 'ssh-ed25519', - fingerprint: hostKeyFingerprintOf(blob(ED_A)) - }) - ) - }) - - it.each([ - ['a key we already know', { entries: parseKnownHosts(`example.com ssh-ed25519 ${ED_A}`) }], - ['a rejected key', { entries: parseKnownHosts(`example.com ssh-ed25519 ${ED_B}`) }], - ['an ephemeral runtime target', { policy: { kind: 'ephemeral' as const } }], - ['a lax StrictHostKeyChecking', { strictHostKeyChecking: 'no' }] - ])('does not record %s', (_label, overrides) => { - const rememberHostKey = vi.fn() - run({ ...overrides, rememberHostKey }) - expect(rememberHostKey).not.toHaveBeenCalled() - }) - }) - - it('reports every decision for audit', () => { - const onDecision = vi.fn() - run({ onDecision }) - expect(onDecision).toHaveBeenCalledWith( - expect.objectContaining({ outcome: 'unknown', keyType: 'ssh-ed25519' }) - ) - }) - describe('denials that bypass the policy', () => { - // Report every denial so credential fallback cannot prompt against a host already refused. - it('reports a denial for a key it could not read', () => { - const onDecision = vi.fn() - createHostKeyVerifier(deps({ onDecision }))(Buffer.alloc(2), () => {}) - expect(onDecision).toHaveBeenCalledWith( - expect.objectContaining({ - action: 'reject', - reason: expect.stringContaining('example.com') - }) - ) - }) - - it('reports a denial when a dependency throws', () => { - const onDecision = vi.fn() - run({ - onDecision, - isTrusted: () => { - throw new Error('store unreadable') - } - }) - expect(onDecision).toHaveBeenCalledWith(expect.objectContaining({ action: 'reject' })) - }) - - // No parseable key means no fingerprint; bogus values must not replace the install-lock identity. - it('reports no fingerprint for a key it could not read', () => { - const onDecision = vi.fn() - createHostKeyVerifier(deps({ onDecision }))(Buffer.alloc(2), () => {}) - expect(onDecision.mock.calls[0]?.[0]?.fingerprint).toBe('') - }) - // Reporting failure inside verifier catch must still deny, never escape and hang handshake. it('still denies when reporting the denial throws', () => { let accepted: boolean | undefined @@ -183,67 +107,12 @@ describe('the ssh2 host key verifier', () => { ).not.toThrow() expect(accepted).toBe(false) }) - - // Superseded verifiers must not overwrite the live attempt's reported outcome. - it('reports nothing once its attempt has been superseded', () => { - const onDecision = vi.fn() - run({ onDecision, isCurrentAttempt: () => false }) - expect(onDecision).not.toHaveBeenCalled() - }) - }) -}) - -describe('the ssh2 default algorithm list', () => { - const ssh2Constants = require('ssh2/lib/protocol/constants.js') as { - DEFAULT_SERVER_HOST_KEY: string[] - SUPPORTED_SERVER_HOST_KEY: string[] - } - - it('is read from ssh2, not guessed', () => { - expect(getDefaultServerHostKeyAlgorithms()).toEqual(ssh2Constants.DEFAULT_SERVER_HOST_KEY) - }) - - it('proposes nothing ssh2 would refuse', () => { - for (const algorithm of getDefaultServerHostKeyAlgorithms() ?? []) { - expect(ssh2Constants.SUPPORTED_SERVER_HOST_KEY).toContain(algorithm) - } - }) - - // Keep all RSA signature names so one known ssh-rsa key can be promoted under every negotiated algorithm. - it('contains the RSA signature algorithms the ordering maps onto', () => { - expect(getDefaultServerHostKeyAlgorithms() ?? []).toEqual( - expect.arrayContaining(['ssh-rsa', 'rsa-sha2-256', 'rsa-sha2-512']) - ) }) }) describe('host key algorithm ordering', () => { const supported = ['ssh-ed25519', 'rsa-sha2-512', 'ssh-rsa', 'ecdsa-sha2-nistp256'] - // Lead with stored types so another algorithm cannot turn mismatch into first contact. - it('leads with the types already known for the host', () => { - const entries = parseKnownHosts(`example.com ssh-rsa ${RSA_A}`) - const ordered = orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported) - expect(ordered?.[0]).toMatch(/rsa/) - expect(ordered?.indexOf('ssh-ed25519')).toBeGreaterThan(0) - }) - - it('keeps every supported algorithm, only reordered', () => { - const entries = parseKnownHosts(`example.com ssh-rsa ${RSA_A}`) - const ordered = orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported) - expect([...(ordered ?? [])].sort()).toEqual([...supported].sort()) - }) - - it('leaves the defaults alone for a host we know nothing about', () => { - const entries = parseKnownHosts(`other.com ssh-rsa ${RSA_A}`) - expect(orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported)).toBeUndefined() - }) - - it('ignores a revoked entry when choosing what to lead with', () => { - const entries = parseKnownHosts(`@revoked example.com ssh-rsa ${RSA_A}`) - expect(orderServerHostKeyAlgorithms(entries, 'example.com', 22, supported)).toBeUndefined() - }) - // One ssh-rsa key negotiates as rsa-sha2-512/256 or ssh-rsa; promote them together. it('promotes every RSA signature algorithm for a known ssh-rsa key', () => { const entries = parseKnownHosts(`example.com ssh-rsa ${RSA_A}`) @@ -251,17 +120,4 @@ describe('host key algorithm ordering', () => { expect(ordered?.slice(0, 2).sort()).toEqual(['rsa-sha2-512', 'ssh-rsa']) expect(ordered?.indexOf('ssh-ed25519')).toBeGreaterThan(1) }) - - // Store-only known types need the same proposal protection as known_hosts types. - it('leads with a type known only from our own store', () => { - const ordered = orderServerHostKeyAlgorithms([], 'example.com', 22, supported, ['ssh-rsa']) - expect(ordered?.[0]).toMatch(/rsa/) - expect(ordered?.indexOf('ssh-ed25519')).toBeGreaterThan(0) - }) - - it('does not propose a type the transport does not support', () => { - const entries = parseKnownHosts(`example.com ssh-ed25519 ${ED_A}`) - const ordered = orderServerHostKeyAlgorithms(entries, 'example.com', 22, ['rsa-sha2-512']) - expect(ordered).toBeUndefined() - }) }) diff --git a/src/main/ssh/ssh-posix-command-wrapper.test.ts b/src/main/ssh/ssh-posix-command-wrapper.test.ts index faab2e81ecc..fe0bf79c72a 100644 --- a/src/main/ssh/ssh-posix-command-wrapper.test.ts +++ b/src/main/ssh/ssh-posix-command-wrapper.test.ts @@ -37,75 +37,6 @@ it.skipIf(process.platform === 'win32')( ) describe('wrapRemoteCommandForPosixShell', () => { - it('emits one physical line without requiring a remote decoder binary', () => { - const wrapped = wrapRemoteCommandForPosixShell("printf 'a\\n'\nprintf 'b\\n'") - expect(wrapped).not.toContain('\n') - expect(wrapped).toContain('printf %b "$@"') - expect(wrapped).not.toContain('base64') - }) - - it('does not expand long commands made only of parser-safe ASCII', () => { - const command = `: #${'x'.repeat(7_000)}` - expect(wrapRemoteCommandForPosixShell(command).length - command.length).toBeLessThan(200) - }) - - it('does not octal-expand literal UTF-8 near SSH command-length limits', () => { - const command = `: #${'☃'.repeat(7_000)}` - expect(wrapRemoteCommandForPosixShell(command).length - command.length).toBeLessThan(200) - }) - - it('does not octal-expand quoted shell metacharacters near command-length limits', () => { - const command = `: #${'$"`'.repeat(2_000)}` - expect(wrapRemoteCommandForPosixShell(command).length - command.length).toBeLessThan(200) - }) - - it('measures the compression threshold in UTF-8 bytes', () => { - const command = `: #${'☃'.repeat(3_000)}` - const wrapped = wrapRemoteCommandForPosixShell(command) - - expect(command.length).toBeLessThan(8_000) - expect(Buffer.byteLength(command)).toBeGreaterThan(8_000) - expect(Buffer.byteLength(wrapped)).toBeLessThan(8_000) - expect(wrapped).not.toContain('\n') - }) - - it('keeps the printf form when compression would make the request larger', () => { - const alphabet = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32)) - .filter((character) => !['!', "'", '\\'].includes(character)) - .join('') - const padding = Array.from({ length: 400 }, (_, i) => - Array.from( - createHash('sha256').update(String(i)).digest(), - (byte) => alphabet[byte % alphabet.length] - ).join('') - ).join('') - const wrapped = wrapRemoteCommandForPosixShell(`: #${padding}`) - - expect(wrapped).toContain('printf %b "$@"') - expect(wrapped).not.toContain('base64') - }) - - it.skipIf(process.platform === 'win32')( - 'reconstructs multiline UTF-8 and shell metacharacters exactly', - () => { - const expected = "line one\nline 'two' \"$`\\ ! ☃\n" - const command = `printf '%s' ${quotePosixShell(expected)}` - const result = runThroughShell('/bin/sh', command) - - expect(result.status).toBe(0) - expect(result.stderr).toBe('') - expect(result.stdout).toBe(expected) - } - ) - - it.skipIf(process.platform === 'win32')('keeps stdin free for relay protocol bytes', () => { - const command = 'IFS= read -r frame; printf \'frame:%s\' "$frame"' - const result = runThroughShell('/bin/sh', command, 'rpc-payload\n') - - expect(result.status).toBe(0) - expect(result.stdout).toBe('frame:rpc-payload') - }) - it.skipIf(process.platform === 'win32')( 'passes a long command through a gateway with a 10 KiB exec limit without consuming stdin', () => { @@ -127,15 +58,6 @@ describe('wrapRemoteCommandForPosixShell', () => { } ) - it.skipIf(process.platform === 'win32')('preserves trailing newlines in a long command', () => { - const command = `# ${'padding'.repeat(2_000)}\nprintf '%s' trailing\\\n` - const result = runThroughShell('/bin/sh', command) - - expect(result.status).toBe(0) - expect(result.stderr).toBe('') - expect(result.stdout).toBe('trailing') - }) - it.skipIf(process.platform === 'win32')( 'reports a host without the decoders before running anything', () => { @@ -151,21 +73,6 @@ describe('wrapRemoteCommandForPosixShell', () => { } ) - it.skipIf(process.platform === 'win32')( - 'fails without running the script if the payload does not decode', - () => { - const bin = shimDir({ base64: "cat >/dev/null; printf 'not gzip'" }) - const command = `# ${'padding'.repeat(2_000)}\nprintf 'must not run'` - const result = spawnSync('/bin/sh', ['-c', wrapRemoteCommandForPosixShell(command)], { - encoding: 'utf8', - env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ''}` } - }) - - expect(result.status).not.toBe(0) - expect(result.stdout).toBe('') - } - ) - it.skipIf(process.platform === 'win32')( 'decodes with `base64 -D` where `-d` is refused, as on macOS before 13', () => { @@ -184,27 +91,6 @@ describe('wrapRemoteCommandForPosixShell', () => { } ) - it('sends a long command plain when asked to', () => { - const wrapped = wrapRemoteCommandForPosixShell(`# ${'padding'.repeat(2_000)}`, { - compress: false - }) - expect(wrapped).toContain('printf %b "$@"') - expect(wrapped).not.toContain('base64') - }) - - it.skipIf(process.platform === 'win32' || !existsSync('/bin/tcsh'))( - 'keeps every login-shell word bounded for long metacharacter-heavy commands', - () => { - const expected = '$"`'.repeat(2_000) - const command = `printf '%s' ${quotePosixShell(expected)}` - const result = runThroughShell('/bin/tcsh', command) - - expect(result.status).toBe(0) - expect(result.stderr).toBe('') - expect(result.stdout).toBe(expected) - } - ) - it.skipIf(process.platform === 'win32' || !existsSync('/bin/tcsh'))( 'bounds login-shell words when the compressed payload spans multiple chunks', () => { @@ -221,31 +107,6 @@ describe('wrapRemoteCommandForPosixShell', () => { expect(result.stdout).toBe(expected) } ) - - for (const shell of [ - '/bin/sh', - '/bin/bash', - '/bin/dash', - '/bin/zsh', - '/bin/ksh', - '/bin/csh', - '/bin/tcsh', - '/usr/bin/fish', - '/usr/local/bin/fish', - '/opt/homebrew/bin/fish' - ]) { - it.skipIf(process.platform === 'win32' || !existsSync(shell)).each([1, 1_000])( - `survives the real ${shell} parser with %i repetitions`, - (repetitions) => { - const expected = "first\nsecond '$`\\n\\\\ ! ☃\n".repeat(repetitions) - const command = `printf '%s' ${quotePosixShell(expected)}` - const result = runThroughShell(shell, command) - expect(result.status).toBe(0) - expect(result.stderr).toBe('') - expect(result.stdout).toBe(expected) - } - ) - } }) function runThroughShell(shell: string, command: string, input?: string) { diff --git a/src/main/star-nag/service-force-show-races.test.ts b/src/main/star-nag/service-force-show-races.test.ts index f099f1f0907..cae9f744075 100644 --- a/src/main/star-nag/service-force-show-races.test.ts +++ b/src/main/star-nag/service-force-show-races.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { STAR_NAG_INITIAL_THRESHOLD } from '../../shared/constants' +import '../../shared/constants' import { createDeferred, createHarness, @@ -60,147 +60,6 @@ describe('StarNagService', () => { consoleInfoMock.mockRestore() }) - it('allows force_show to bypass the persisted cooldown', () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service } = createHarness({ - starNagDeferredUntil: Date.now() + 3 * 24 * 60 * 60 * 1000 - }) - - service.registerIpcHandlers() - getIpcHandler('star-nag:forceShow')() - - expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', { - mode: 'gh', - surface: 'card' - }) - }) - - it('keeps the force_show source through exposure and dismissal', () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, ui } = createHarness() - - service.registerIpcHandlers() - getIpcHandler('star-nag:forceShow')() - getIpcHandler('star-nag:dismiss')() - - expect(consoleInfoMock).toHaveBeenNthCalledWith(1, { - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'force_show' - }) - expect(consoleInfoMock).toHaveBeenNthCalledWith(2, { - event: 'star_nag_dismissed', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'force_show', - next_threshold: STAR_NAG_INITIAL_THRESHOLD * 2 - }) - expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD * 2) - }) - - it('does not log or block a later force_show when no window exists', () => { - const { service } = createHarness() - - service.registerIpcHandlers() - const forceShow = getIpcHandler('star-nag:forceShow') - forceShow() - - expect(consoleInfoMock).not.toHaveBeenCalled() - - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - forceShow() - - expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', { - mode: 'gh', - surface: 'card' - }) - expect(consoleInfoMock).toHaveBeenCalledWith({ - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'force_show' - }) - }) - - it('keeps threshold source when force_show is requested during a successful threshold evaluation', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const deferredStarCheck = createDeferred() - checkOrcaStarredMock.mockReturnValue(deferredStarCheck.promise) - const { service, emitAgentStarted } = createHarness() - - service.start() - service.registerIpcHandlers() - emitAgentStarted(45) - getIpcHandler('star-nag:forceShow')() - - expect(window.webContents.send).not.toHaveBeenCalled() - expect(consoleInfoMock).not.toHaveBeenCalled() - - deferredStarCheck.resolve(false) - await flushAsyncWork() - - expect(window.webContents.send).toHaveBeenCalledTimes(1) - expect(consoleInfoMock).toHaveBeenCalledTimes(1) - expect(consoleInfoMock).toHaveBeenCalledWith({ - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'threshold' - }) - }) - - it('does not replay a stale queued force_show after threshold delivery wins', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const firstStarCheck = createDeferred() - checkOrcaStarredMock.mockReturnValueOnce(firstStarCheck.promise).mockResolvedValue(null) - const { service, emitAgentStarted } = createHarness() - - service.start() - service.registerIpcHandlers() - emitAgentStarted(45) - getIpcHandler('star-nag:forceShow')() - - firstStarCheck.resolve(false) - await flushAsyncWork() - getIpcHandler('star-nag:dismiss')() - - emitAgentStarted(114) - await flushAsyncWork() - - expect(window.webContents.send).toHaveBeenCalledTimes(1) - expect(consoleInfoMock.mock.calls).toEqual([ - [ - { - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'threshold' - } - ], - [ - { - event: 'star_nag_dismissed', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'threshold', - next_threshold: STAR_NAG_INITIAL_THRESHOLD * 2 - } - ] - ]) - }) - it('does not show after completion wins an in-flight threshold evaluation', async () => { const window = createWindow() browserWindowMock.getAllWindows.mockReturnValue([window]) @@ -221,81 +80,4 @@ describe('StarNagService', () => { expect(window.webContents.send).not.toHaveBeenCalled() expect(consoleInfoMock).not.toHaveBeenCalled() }) - - it('keeps threshold source when an in-flight star check falls back to the browser', async () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const deferredStarCheck = createDeferred() - checkOrcaStarredMock.mockReturnValue(deferredStarCheck.promise) - const { service, emitAgentStarted } = createHarness() - - service.start() - service.registerIpcHandlers() - emitAgentStarted(45) - getIpcHandler('star-nag:forceShow')() - - expect(window.webContents.send).not.toHaveBeenCalled() - expect(consoleInfoMock).not.toHaveBeenCalled() - - deferredStarCheck.resolve(null) - await flushAsyncWork() - - expect(window.webContents.send).toHaveBeenCalledTimes(1) - expect(consoleInfoMock).toHaveBeenCalledTimes(1) - expect(window.webContents.send).toHaveBeenCalledWith('star-nag:show', { - mode: 'web', - surface: 'card' - }) - expect(consoleInfoMock).toHaveBeenCalledWith({ - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'threshold' - }) - }) - - it('ignores stray and duplicate dismissals without logging or advancing backoff', () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, store, ui } = createHarness() - - service.registerIpcHandlers() - const dismiss = getIpcHandler('star-nag:dismiss') - dismiss() - - expect(consoleInfoMock).not.toHaveBeenCalled() - expect(store.updateUI).not.toHaveBeenCalled() - expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD) - - getIpcHandler('star-nag:forceShow')() - dismiss() - dismiss() - - const dismissedLogs = consoleInfoMock.mock.calls.filter( - ([payload]) => (payload as { event?: string }).event === 'star_nag_dismissed' - ) - expect(dismissedLogs).toHaveLength(1) - expect(ui.starNagNextThreshold).toBe(STAR_NAG_INITIAL_THRESHOLD * 2) - }) - - it('marks completion without adding duplicate success logging', () => { - const window = createWindow() - browserWindowMock.getAllWindows.mockReturnValue([window]) - const { service, ui } = createHarness() - - service.registerIpcHandlers() - getIpcHandler('star-nag:forceShow')() - getIpcHandler('star-nag:complete')() - - expect(ui.starNagCompleted).toBe(true) - expect(consoleInfoMock).toHaveBeenCalledTimes(1) - expect(consoleInfoMock).toHaveBeenCalledWith({ - event: 'star_nag_shown', - app_version: '1.2.3', - threshold: STAR_NAG_INITIAL_THRESHOLD, - agents_since_baseline: 35, - source: 'force_show' - }) - }) }) diff --git a/src/main/startup/windows-install-dir-acl-probe.test.ts b/src/main/startup/windows-install-dir-acl-probe.test.ts deleted file mode 100644 index d8b98023f22..00000000000 --- a/src/main/startup/windows-install-dir-acl-probe.test.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { join } from 'node:path' -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - resetWindowsSecurityLoadForTests, - setWindowsSecurityForTests -} from '../../shared/windows-security-addon' -import { - probeWindowsInstallDirAcl, - resetWindowsInstallDirAclProbeForTest, - WINDOWS_INSTALL_DIR_ACL_BREADCRUMB, - type WindowsInstallDirAclProbeOptions -} from './windows-install-dir-acl-probe' -import { isInstallDirAclPoisonVerdict } from './windows-install-dir-package-acl-repair' -import { - ALL_PACKAGES_ACE, - installFakeDacls, - ORPHAN_PACKAGE_ACE, - RESTRICTED_PACKAGES_ACE -} from './windows-install-dir-acl.test-fixture' - -const INSTALL_DIR = 'C:\\Users\\neil\\AppData\\Local\\Programs\\orca' -const ORPHAN = ORPHAN_PACKAGE_ACE -const RESTRICTED_GRANT = RESTRICTED_PACKAGES_ACE - -function probe(options: WindowsInstallDirAclProbeOptions = {}): Promise> { - return new Promise((resolve) => { - probeWindowsInstallDirAcl({ - platform: 'win32', - installDir: INSTALL_DIR, - fileExists: (path) => path.endsWith('ffmpeg.dll'), - ...options, - recordBreadcrumb: (name, data) => { - resolve({ ...(data as Record), name }) - return undefined - } - }) - }) -} - -/** Every target returns the same ACE set on top of the system baseline. */ -function probeWith(...aces: string[]): Promise> { - installFakeDacls(() => aces) - return probe() -} - -describe('probeWindowsInstallDirAcl', () => { - beforeEach(() => { - resetWindowsInstallDirAclProbeForTest() - }) - - afterEach(() => { - resetWindowsSecurityLoadForTests() - }) - - it('reports a clean DACL as unpoisoned', async () => { - installFakeDacls(() => []) - const data = await probe() - expect(data.name).toBe(WINDOWS_INSTALL_DIR_ACL_BREADCRUMB) - expect(data.status).toBe('ok') - expect(data.orphanPackageSidCount).toBe(0) - expect(data.matchesPoisonSignature).toBe(false) - }) - - it('flags an orphan package SID with no well-known grant', async () => { - const data = await probeWith(ORPHAN) - expect(data.matchesPoisonSignature).toBe(true) - expect(data.orphanPackageSidCount).toBe(1) - expect(data.orphanPackageSids).toBe('S-1-15-2-999-999-999') - expect(data.hasWellKnownPackageGrant).toBe(false) - }) - - it('clears the signature once the restricted package ACE grants access', async () => { - const data = await probeWith(RESTRICTED_GRANT, ORPHAN) - expect(data.hasWellKnownPackageGrant).toBe(true) - expect(data.hasRestrictedPackageGrant).toBe(true) - expect(data.orphanPackageSidCount).toBe(1) - expect(data.matchesPoisonSignature).toBe(false) - }) - - // Orphan plus ALL APPLICATION PACKAGES launched clean on Windows 10.0.26200/Electron 43.4.1; it must not match the reproduced poison. - it.each([ - ['the AC alias', ALL_PACKAGES_ACE], - ['the raw SID form', '(A;OICI;0x1200a9;;;S-1-15-2-1)'] - ])('clears the signature when only ALL APPLICATION PACKAGES grants (%s)', async (_l, ace) => { - const data = await probeWith(ace, ORPHAN) - expect(data.hasWellKnownPackageGrant).toBe(true) - expect(data.hasRestrictedPackageGrant).toBe(false) - expect(data.matchesPoisonSignature).toBe(false) - }) - - // Deny/inherit-only ACEs grant no access on this object and cannot satisfy the orphan. - it.each([ - ['deny', '(D;OICI;FA;;;AC)'], - ['inherit-only', '(A;OICIIO;GRGX;;;AC)'], - ['restricted deny', '(D;;FA;;;S-1-15-2-2)'], - ['restricted inherit-only', '(A;CIOIIO;GRGX;;;S-1-15-2-2)'] - ])('does not let a %s well-known ACE satisfy an orphan', async (_label, ace) => { - const data = await probeWith(ace, ORPHAN) - expect(data.hasWellKnownPackageGrant).toBe(false) - expect(data.hasRestrictedPackageGrant).toBe(false) - expect(data.matchesPoisonSignature).toBe(true) - }) - - it('does not let a grant on one target mask its absence on another', async () => { - installFakeDacls((target) => - target.endsWith('ffmpeg.dll') ? [ORPHAN] : [RESTRICTED_GRANT, ORPHAN] - ) - const data = await probe() - expect(data.hasWellKnownPackageGrant).toBe(true) - expect(data.matchesPoisonSignature).toBe(true) - }) - - // SDDL SIDs stay stable across localized display names. - it('reads a repaired tree as clean from SIDs alone', async () => { - let verdict: CrashReportBreadcrumbData = {} - installFakeDacls(() => [ORPHAN, RESTRICTED_GRANT]) - const data = await probe({ - onDone: (done) => (verdict = done) - }) - expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false) - expect(data.status).toBe('ok') - expect(data.orphanPackageSidCount).toBe(1) - expect(data.hasRestrictedPackageGrant).toBe(true) - }) - - it('matches the well-known SIDs exactly, not by prefix', async () => { - const data = await probeWith('(A;OICI;0x1200a9;;;S-1-15-2-1234567890)') - expect(data.orphanPackageSidCount).toBe(1) - expect(data.hasWellKnownPackageGrant).toBe(false) - expect(data.matchesPoisonSignature).toBe(true) - }) - - it('ignores capability SIDs, which are a different family and harmless', async () => { - const data = await probeWith('(A;;0x100020;;;S-1-15-3-65536-599108337-2355189375-1353122160)') - expect(data.orphanPackageSidCount).toBe(0) - expect(data.matchesPoisonSignature).toBe(false) - }) - - it('probes a content file, not just the directory object', async () => { - const fake = installFakeDacls(() => [ORPHAN]) - await probe() - expect(fake.calls).toEqual([INSTALL_DIR, join(INSTALL_DIR, 'ffmpeg.dll')]) - }) - - // Real DACL-only SDDL from Windows 10.0.26200. - it.each([ - [ - 'a repaired module file', - 'D:AI(A;;0x1200a9;;;S-1-15-2-2)(A;;0x1200a9;;;S-1-15-2-999-999-999)' + - '(A;ID;0x1200a9;;;S-1-15-2-999-999-999)(A;ID;FA;;;SY)(A;ID;FA;;;BA)' + - '(A;ID;FA;;;S-1-5-21-432636774-4279371817-3971399515-1001)', - false - ], - [ - 'a poisoned dir whose AC ACE denies', - 'D:AI(D;;0x100116;;;AC)(A;OICI;0x1200a9;;;S-1-15-2-999-999-999)' + - '(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)' + - '(A;OICIID;FA;;;S-1-5-21-432636774-4279371817-3971399515-1001)', - true - ] - ])('reads a real captured DACL: %s', async (_label, saved, poisoned) => { - installFakeDacls(() => saved) - const data = await probe({ - fileExists: () => false - }) - expect(data.orphanPackageSids).toBe('S-1-15-2-999-999-999') - expect(data.matchesPoisonSignature).toBe(poisoned) - }) - - it('keeps a conditional DACL unreadable instead of hiding a later package grant', async () => { - const saved = - 'D:AI(A;OICI;0x1200a9;;;S-1-15-2-999-999-999)' + - '(XA;OICI;FA;;;WD;(@User.Department == "Finance"))' + - '(A;OICIID;0x1200a9;;;S-1-15-2-2)' - let verdict: CrashReportBreadcrumbData = {} - installFakeDacls(() => saved) - const data = await probe({ - fileExists: () => false, - onDone: (done) => (verdict = done) - }) - expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' }) - expect(data.matchesPoisonSignature).toBeUndefined() - expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false) - }) - - // NULL DACL grants all access but proves no specific package grant. - it('keeps a NULL DACL unreadable rather than reading it as clean', async () => { - installFakeDacls(() => 'D:NO_ACCESS_CONTROL') - const data = await probe({ fileExists: () => false }) - expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' }) - }) - - it('treats a read that fails as unreadable, never as a clean DACL', async () => { - let verdict: CrashReportBreadcrumbData = {} - installFakeDacls(() => null) - const data = await probe({ - fileExists: () => false, - onDone: (done) => (verdict = done) - }) - expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' }) - expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false) - }) - - it('does not report malformed saved output as a clean DACL', async () => { - installFakeDacls(() => 'orca') - const data = await probe({ - fileExists: () => false - }) - expect(data).toMatchObject({ status: 'failed', reason: 'all-targets-unreadable' }) - expect(data.matchesPoisonSignature).toBeUndefined() - }) - - it('records a failure instead of throwing when no DACL can be read', async () => { - installFakeDacls(() => null) - const data = await probe() - expect(data.status).toBe('failed') - expect(data.reason).toBe('all-targets-unreadable') - expect(data.matchesPoisonSignature).toBeUndefined() - }) - - // Missing addon proves probe failure, never a healthy tree. - it('records a failure, not a verdict, when the addon cannot load', async () => { - setWindowsSecurityForTests(null) - let verdict: CrashReportBreadcrumbData = {} - const data = await probe({ onDone: (done) => (verdict = done) }) - expect(data.status).toBe('failed') - expect(String(data.reason)).toContain('windows-security addon unavailable') - expect(isInstallDirAclPoisonVerdict(verdict)).toBe(false) - }) - - it.each([ - ['darwin', { platform: 'darwin' as NodeJS.Platform }], - ['serve mode', { platform: 'win32' as NodeJS.Platform, isServeMode: true }] - ])('does no work on %s', async (_label, options) => { - const fake = installFakeDacls(() => [ORPHAN]) - const record = vi.fn() - const fileExists = vi.fn(() => true) - probeWindowsInstallDirAcl({ - installDir: INSTALL_DIR, - fileExists, - recordBreadcrumb: record, - ...options - }) - await new Promise((resolve) => setImmediate(resolve)) - expect(fake.calls).toHaveLength(0) - expect(fileExists).not.toHaveBeenCalled() - expect(record).not.toHaveBeenCalled() - }) - - it('runs once per process', async () => { - const fake = installFakeDacls(() => [ORPHAN]) - await probe() - const before = fake.calls.length - probeWindowsInstallDirAcl({ platform: 'win32', installDir: INSTALL_DIR }) - await new Promise((resolve) => setImmediate(resolve)) - expect(fake.calls).toHaveLength(before) - }) -}) diff --git a/src/main/telemetry/chat-ui-launch-tip-cohort.test.ts b/src/main/telemetry/chat-ui-launch-tip-cohort.test.ts deleted file mode 100644 index 0b2bd8ab093..00000000000 --- a/src/main/telemetry/chat-ui-launch-tip-cohort.test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import * as crypto from 'node:crypto' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ChatUiLaunchTipVariant } from '../../shared/native-chat/chat-ui-launch-tip-audience' -import type { TelemetrySettings } from '../../shared/telemetry-settings-types' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { Store } from '../persistence/loading-store/store' -import { - ensureChatUiLaunchTipCohort, - isChatUiLaunchTipDeferredForConsent -} from './chat-ui-launch-tip-cohort' -import { experimentCohortProps } from './experiment-cohort-props' -import { commonPropsSchema } from '../../shared/telemetry-events' -import { - BASE_COMMON, - makeFakeSettings, - restoreConsentEnv, - stashAndClearConsentEnv -} from './client-test-harness' - -vi.mock('node:crypto', async (importOriginal) => ({ - ...(await importOriginal()), - randomInt: vi.fn(() => 0) -})) - -function makeStore( - telemetry: Partial, - variant: ChatUiLaunchTipVariant = 'chat-ui-off', - seen: string[] = [], - preferences: Partial = {} -): Store { - const settings = makeFakeSettings({ - optedIn: true, - installId: 'install', - existedBeforeTelemetryRelease: true, - ...telemetry - }) - Object.assign(settings, preferences) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: supplies every Store method the cohort assignment reads or writes. - return { - getSettings: () => settings, - getUI: () => ({ featureTipsSeenIds: seen }), - getChatUiLaunchTipVariant: () => variant, - updateSettings: vi.fn((updates: { telemetry: TelemetrySettings }) => { - settings.telemetry = updates.telemetry - }) - } as unknown as Store -} - -describe('ensureChatUiLaunchTipCohort', () => { - let env: Record - beforeEach(() => { - env = stashAndClearConsentEnv() - vi.mocked(crypto.randomInt) - .mockReset() - .mockImplementation(() => 0) - }) - afterEach(() => { - restoreConsentEnv(env) - }) - - it.each([ - { draw: 3, cohort: 'control' }, - { draw: 4, cohort: 'treatment' } - ])('assigns draw $draw to $cohort and keeps the frozen cohort', ({ draw, cohort }) => { - vi.mocked(crypto.randomInt).mockImplementationOnce(() => draw) - const store = makeStore({}) - expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort) - expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort) - expect(store.getSettings().telemetry?.chatUiLaunchTipCohort).toBeUndefined() - expect(store.getSettings().telemetry?.installId).toBe('install') - expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort) - }) - - it.each([ - { draw: 3, cohort: 'control', targeting: undefined, emphasis: undefined }, - { draw: 4, cohort: 'treatment', targeting: { mode: 'all' }, emphasis: 'normal' } - ])( - 'expands an existing control to $cohort once at draw $draw', - ({ draw, cohort, targeting, emphasis }) => { - vi.mocked(crypto.randomInt).mockImplementationOnce(() => draw) - const store = makeStore({ chatUiLaunchTipCohort: 'control' }) - expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort) - expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort) - expect(store.getSettings().telemetry?.chatUiLaunchTipTargeting).toEqual(targeting) - expect(store.getSettings().telemetry?.chatUiLaunchTipButtonEmphasis).toBe(emphasis) - - vi.mocked(crypto.randomInt).mockImplementation(() => 6) - expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort) - expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort) - expect(store.getSettings().telemetry?.chatUiLaunchTipCohort).toBe('control') - expect(experimentCohortProps(store)).toMatchObject({ - chat_ui_launch_tip_v1: 'control', - chat_ui_launch_tip_rollout_v1: cohort - }) - } - ) - - it('waits for consent before expanding an existing control', () => { - const store = makeStore({ chatUiLaunchTipCohort: 'control', optedIn: false }) - vi.mocked(crypto.randomInt).mockImplementationOnce(() => 6) - expect(ensureChatUiLaunchTipCohort(store)).toBe('control') - expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBeUndefined() - - store.getSettings().telemetry!.optedIn = true - expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment') - expect(store.getSettings().telemetry?.chatUiLaunchTipCohort).toBe('control') - expect(store.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe('treatment') - }) - - it.each([0, 1])('freezes button emphasis draw %s independently', (draw) => { - vi.mocked(crypto.randomInt) - .mockImplementationOnce(() => 7) - .mockImplementationOnce(() => 0) - .mockImplementationOnce(() => draw) - const store = makeStore({}) - expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment') - expect(store.getSettings().telemetry?.chatUiLaunchTipButtonEmphasis).toBe( - draw === 0 ? 'normal' : 'swapped' - ) - ensureChatUiLaunchTipCohort(store) - expect(store.updateSettings).toHaveBeenCalledTimes(1) - }) - - it.each([ - { variant: 'chat-ui-off', surface: 'terminal' }, - { variant: 'chat-ui-off', surface: 'chat' }, - { variant: 'chat-ui-on', surface: 'terminal' }, - { variant: 'chat-ui-on', surface: 'chat' }, - { variant: 'chat-ui-on', surface: undefined } - ] as const)( - 'targets the current $surface default for the frozen $variant audience and preserves enrollment', - ({ variant, surface }) => { - for (const draw of [0, 1]) { - vi.mocked(crypto.randomInt) - .mockReset() - .mockImplementationOnce(() => 8) - .mockImplementationOnce(() => draw) - const store = makeStore({}, variant, [], { agentDefaultSurface: surface }) - expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment') - expect(crypto.randomInt).toHaveBeenNthCalledWith(1, 10) - expect(crypto.randomInt).toHaveBeenNthCalledWith(2, 2) - const targeting = store.getSettings().telemetry?.chatUiLaunchTipTargeting - expect(targeting).toEqual( - draw === 0 ? { mode: 'all' } : { mode: 'not-switched', eligible: surface !== 'chat' } - ) - store.getSettings().agentDefaultSurface = surface === 'chat' ? 'terminal' : 'chat' - expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment') - expect(store.getSettings().telemetry?.chatUiLaunchTipTargeting).toEqual(targeting) - expect(store.getChatUiLaunchTipVariant()).toBe(variant) - expect(store.updateSettings).toHaveBeenCalledTimes(1) - } - } - ) - - it.each([ - { variant: 'chat-ui-off', before: 'terminal', atEnrollment: 'chat', eligible: false }, - { variant: 'chat-ui-on', before: 'chat', atEnrollment: 'terminal', eligible: true } - ] as const)( - 'uses the $atEnrollment default after consent delays enrollment for $variant', - ({ variant, before, atEnrollment, eligible }) => { - vi.mocked(crypto.randomInt) - .mockImplementationOnce(() => 8) - .mockImplementationOnce(() => 1) - const store = makeStore({ optedIn: null }, variant, [], { agentDefaultSurface: before }) - expect(ensureChatUiLaunchTipCohort(store)).toBeUndefined() - expect(crypto.randomInt).not.toHaveBeenCalled() - - store.getSettings().agentDefaultSurface = atEnrollment - store.getSettings().telemetry!.optedIn = true - expect(ensureChatUiLaunchTipCohort(store)).toBe('treatment') - expect(store.getSettings().telemetry?.chatUiLaunchTipTargeting).toEqual({ - mode: 'not-switched', - eligible - }) - expect(store.getChatUiLaunchTipVariant()).toBe(variant) - } - ) - - it.each([ - 'treatment-center', - 'treatment', - 'treatment-live-switch', - 'treatment-swapped-buttons' - ] as const)('preserves existing %s assignments', (cohort) => { - const store = makeStore({ - chatUiLaunchTipCohort: cohort - }) - expect(ensureChatUiLaunchTipCohort(store)).toBe(cohort) - expect(crypto.randomInt).not.toHaveBeenCalled() - expect(store.updateSettings).not.toHaveBeenCalled() - }) - - it.each([ - { draw: 7, cohort: 'treatment' }, - { draw: 8, cohort: 'treatment' }, - { draw: 9, cohort: 'treatment' } - ])( - 'emits schema-valid targeting props immediately after $cohort enrollment', - ({ draw, cohort }) => { - vi.mocked(crypto.randomInt) - .mockImplementationOnce(() => draw) - .mockImplementationOnce(() => 1) - const store = makeStore({ onboardingLanguageCohort: 'treatment' }) - const props = experimentCohortProps(store) - expect(props).toEqual({ - onboarding_language_v1: 'treatment', - chat_ui_launch_tip_v1: undefined, - chat_ui_launch_tip_rollout_v1: cohort, - chat_ui_launch_tip_targeting_v1: 'not-switched', - chat_ui_launch_tip_button_emphasis_v1: 'normal' - }) - expect(commonPropsSchema.safeParse({ ...BASE_COMMON, ...props }).success).toBe(true) - } - ) - - it('ignores malformed targeting metadata rather than disabling all telemetry', () => { - const store = makeStore({ chatUiLaunchTipCohort: 'treatment' }) - Object.assign(store.getSettings().telemetry!, { chatUiLaunchTipTargeting: { mode: 'invalid' } }) - const props = experimentCohortProps(store) - expect(props.chat_ui_launch_tip_targeting_v1).toBeUndefined() - expect(commonPropsSchema.safeParse({ ...BASE_COMMON, ...props }).success).toBe(true) - }) - - it('holds the tip unenrolled while the banner is pending, then enrolls after acknowledgement', () => { - const pending = makeStore({ optedIn: null }) - expect(ensureChatUiLaunchTipCohort(pending)).toBeUndefined() - expect(isChatUiLaunchTipDeferredForConsent()).toBe(true) - expect(pending.updateSettings).not.toHaveBeenCalled() - - // Acknowledging the banner persists optedIn=true; the next launch enrolls the still-unseen tip. - pending.getSettings().telemetry!.optedIn = true - const cohort = ensureChatUiLaunchTipCohort(pending) - expect(['control', 'treatment']).toContain(cohort) - expect(isChatUiLaunchTipDeferredForConsent()).toBe(false) - expect(pending.getSettings().telemetry?.chatUiLaunchTipRolloutCohort).toBe(cohort) - }) - - it('releases a pending profile unenrolled after the banner is declined, so the tip shows as before', () => { - const pending = makeStore({ optedIn: null }) - ensureChatUiLaunchTipCohort(pending) - expect(isChatUiLaunchTipDeferredForConsent()).toBe(true) - - pending.getSettings().telemetry!.optedIn = false - expect(ensureChatUiLaunchTipCohort(pending)).toBeUndefined() - expect(isChatUiLaunchTipDeferredForConsent()).toBe(false) - expect(pending.updateSettings).not.toHaveBeenCalled() - }) - - it.each([ - ['outside the audience', makeStore({}, 'none')], - ['already shown the tip', makeStore({}, 'chat-ui-off', ['chat-ui-here'])], - ['opted out', makeStore({ optedIn: false })] - ])('leaves a profile %s unenrolled, so it keeps today’s behaviour', (_label, store) => { - expect(ensureChatUiLaunchTipCohort(store)).toBeUndefined() - expect(isChatUiLaunchTipDeferredForConsent()).toBe(false) - expect(store.updateSettings).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts b/src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts index 8e535297142..9c5df2c8a15 100644 --- a/src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts +++ b/src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts @@ -85,173 +85,6 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () await expectChildTerminated(child) }) - it('passes prepared provider environment to local agent subprocesses', async () => { - const listeners = new Map void>() - const child = { - pid: 123, - kill: vi.fn(), - stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, - stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, - stdin: { end: vi.fn() }, - on: vi.fn((event, callback) => listeners.set(event, callback)) - } - spawnMock.mockReturnValue(child as never) - - const pending = generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'orca-test-agent-nope' - }, - { - kind: 'local', - cwd: '/repo', - env: { ...process.env, CODEX_HOME: '/managed/codex-home' } - } - ) - - listeners.get('stdout:data')?.(Buffer.from('Add README note\n')) - listeners.get('close')?.(0) - - await expect(pending).resolves.toMatchObject({ - success: true, - message: 'Add README note' - }) - expect(spawnMock).toHaveBeenCalledWith( - 'orca-test-agent-nope', - [], - expect.objectContaining({ - env: expect.objectContaining({ CODEX_HOME: '/managed/codex-home' }) - }) - ) - }) - - it('routes WSL local commit generation through the selected distro login shell', async () => { - await withPlatform('win32', async () => { - process.env.ORCA_HOST_ONLY_SECRET = 'do-not-leak' - const listeners = new Map void>() - const child = { - pid: 123, - kill: vi.fn(), - stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, - stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, - stdin: { end: vi.fn() }, - on: vi.fn((event, callback) => listeners.set(event, callback)) - } - spawnMock.mockReturnValue(child as never) - - const pending = generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent --mode fast' - }, - { - kind: 'local', - cwd: 'C:\\repo', - wslDistro: 'Ubuntu 24.04', - env: { ...process.env, CODEX_HOME: '/home/tester/.codex' } - } - ) - - listeners.get('stdout:data')?.(Buffer.from('Update README\n')) - listeners.get('close')?.(0) - - await expect(pending).resolves.toMatchObject({ - success: true, - message: 'Update README' - }) - expect(spawnMock).toHaveBeenCalledWith( - 'wsl.exe', - ['-d', 'Ubuntu 24.04', '--exec', 'sh', '-lc', expect.any(String)], - expect.objectContaining({ - // #16463: explicit native cwd avoids inheriting a deletable WSL UNC worktree; guest cwd stays inside the command. - cwd: expect.any(String), - windowsHide: true, - env: expect.objectContaining({ CODEX_HOME: '/home/tester/.codex' }) - }) - ) - const spawnEnv = spawnMock.mock.calls[0]?.[2]?.env as NodeJS.ProcessEnv - expect(spawnEnv.ORCA_HOST_ONLY_SECRET).toBeUndefined() - const shellCommand = spawnMock.mock.calls[0]?.[1]?.[5] as string - expect(shellCommand).toContain('getent passwd') - expect(shellCommand).toContain('exec "$_orca_wsl_shell" -ilc') - expect(shellCommand).toContain('/mnt/c/repo') - expect(shellCommand).toContain("'agent'") - expect(shellCommand).toContain('--mode') - expect(shellCommand).toContain('fast') - }) - }) - - it('routes Windows batch-script agent commands through cmd.exe', async () => { - const originalComSpec = process.env.ComSpec - process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe' - try { - await withPlatform('win32', async () => { - const listeners = new Map void>() - const child = { - pid: 123, - kill: vi.fn(), - stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, - stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, - stdin: { end: vi.fn() }, - on: vi.fn((event, callback) => listeners.set(event, callback)) - } - spawnMock.mockReturnValue(child as never) - - const pending = generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'C:/tools/agent.cmd' - }, - { - kind: 'local', - cwd: 'C:\\repo' - } - ) - - listeners.get('stdout:data')?.(Buffer.from('Update README\n')) - listeners.get('close')?.(0) - - await expect(pending).resolves.toMatchObject({ - success: true, - message: 'Update README' - }) - expect(spawnMock).toHaveBeenCalledWith( - 'C:\\Windows\\System32\\cmd.exe', - ['/d /v:off /s /c ""C:/tools/agent.cmd""'], - expect.objectContaining({ - cwd: 'C:\\repo', - windowsHide: true, - windowsVerbatimArguments: true - }) - ) - }) - } finally { - if (originalComSpec === undefined) { - delete process.env.ComSpec - } else { - process.env.ComSpec = originalComSpec - } - } - }) - it('rejects unsafe argv prompts for Windows batch-script agent commands', async () => { await withPlatform('win32', async () => { const result = await generateCommitMessageFromContext( diff --git a/src/main/text-generation/source-control-read-only-policy.test.ts b/src/main/text-generation/source-control-read-only-policy.test.ts index 8abed495c5c..0f14626cb77 100644 --- a/src/main/text-generation/source-control-read-only-policy.test.ts +++ b/src/main/text-generation/source-control-read-only-policy.test.ts @@ -6,8 +6,8 @@ import { afterEach, expect, it, vi } from 'vitest' import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' import { prepareSourceControlReadOnlyPlan } from './source-control-read-only-policy' import { stageLocalPromptFiles } from './source-control-prompt-files' -import { runLocalPlanForAgent } from './source-control-local-generation' -import { cancelLocalGeneration } from './source-control-generation-lanes' +import './source-control-local-generation' +import './source-control-generation-lanes' const { probe } = vi.hoisted(() => ({ probe: vi.fn() })) vi.mock('./source-control-policy-probe', () => ({ runSourceControlPolicyProbe: probe })) @@ -37,56 +37,6 @@ const spawnAgent = vi.fn(() => { throw new Error('Unexpected semantic process') }) -it('cancels during configuration admission without launching a semantic agent', async () => { - const cwd = await directory() - const entered = Promise.withResolvers() - probe.mockImplementation(({ signal }: { signal: AbortSignal }) => ({ - result: new Promise((_resolve, reject) => { - signal.addEventListener('abort', () => reject(signal.reason), { once: true }) - entered.resolve() - }), - processClosed: Promise.resolve() - })) - const result = runLocalPlanForAgent({ - agentId: 'codex', - plan: planned('codex'), - target: { kind: 'local', cwd, env: { CODEX_HOME: cwd } }, - operation: 'conversation-name', - spawnAgent - }) - await entered.promise - cancelLocalGeneration('conversation-name', cwd) - await expect(result).resolves.toMatchObject({ success: false, canceled: true }) - expect(spawnAgent).not.toHaveBeenCalled() -}) - -it('keeps non-title helpers inside the enforced task policy', async () => { - const cwd = await directory() - for (const agentId of ['amp', 'muse', 'kimi'] as const) { - const result = planCommitMessageGeneration( - { - agentId, - model: agentId === 'amp' ? 'smart' : 'default', - ...(agentId === 'kimi' ? { agentArgs: '--agent custom' } : {}) - }, - 'Name this chat' - ) - if (!result.ok) { - throw new Error(result.error) - } - await expect( - runLocalPlanForAgent({ - agentId, - plan: result.plan, - target: { kind: 'local', cwd }, - operation: 'commit-message', - spawnAgent - }) - ).resolves.toMatchObject({ success: false }) - } - expect(spawnAgent).not.toHaveBeenCalled() -}) - it('disables every effective Codex MCP name, including dotted names, after recipe overrides', async () => { probe.mockReturnValue({ result: Promise.resolve({ @@ -225,68 +175,3 @@ it('composes agy session settings without losing existing read denies or selecte expect(policy.args).toContain('high') expect(await readFile(join(cwd, 'settings.json'), 'utf8')).not.toContain('write_file') }) - -it('refuses an agy build without session settings before sending the prompt', async () => { - probe.mockReturnValue({ - result: Promise.resolve({ - stdout: '', - stderr: ' --model Model to use\n --agent Agent profile\n' - }), - processClosed: Promise.resolve() - }) - const cwd = await directory() - await expect( - runLocalPlanForAgent({ - agentId: 'antigravity', - plan: planned('antigravity'), - target: { kind: 'local', cwd }, - operation: 'commit-message', - spawnAgent - }) - ).resolves.toMatchObject({ success: false }) - expect(spawnAgent).not.toHaveBeenCalled() - expect(probe.mock.calls[0][0]).toMatchObject({ args: ['--help'], target: { cwd } }) -}) - -it('preserves valid selected Kimi history and named profiles for best-effort naming', async () => { - for (const args of ['--agent review', '--session saved-chat', '--continue']) { - const plan = planned('kimi', args) - const prepared = await prepareSourceControlReadOnlyPlan({ - agentId: 'kimi', - plan, - operation: 'conversation-name', - target: { kind: 'local', cwd: '/workspace' }, - signal: new AbortController().signal, - spawnAgent - }).result - expect(prepared.args).toEqual(plan.args) - expect(prepared.taskFiles).toBeUndefined() - } -}) - -it('uses successful older agy help as capability evidence without swallowing a failed probe', async () => { - probe.mockReturnValueOnce({ - result: Promise.resolve({ stdout: ' --sandbox Use a sandbox\n --model Model', stderr: '' }), - processClosed: Promise.resolve() - }) - const plan = planned('antigravity', '--agent review') - const input = { - agentId: 'antigravity', - plan, - operation: 'conversation-name' as const, - target: { kind: 'local' as const, cwd: '/workspace' }, - signal: new AbortController().signal, - spawnAgent - } - const prepared = await prepareSourceControlReadOnlyPlan(input).result - expect(prepared.args).toContain('review') - expect(prepared.args).toContain('--sandbox') - expect(prepared.args).not.toContain('--settings') - probe.mockReturnValueOnce({ - result: Promise.reject(new Error('Help could not start')), - processClosed: Promise.resolve() - }) - await expect(prepareSourceControlReadOnlyPlan(input).result).rejects.toThrow( - 'Help could not start' - ) -}) diff --git a/src/main/updater/updater.linux-root-package-install.test.ts b/src/main/updater/updater.linux-root-package-install.test.ts deleted file mode 100644 index 8e8629c4d1a..00000000000 --- a/src/main/updater/updater.linux-root-package-install.test.ts +++ /dev/null @@ -1,267 +0,0 @@ -import type { getReleaseDownloadUrl } from './releases/updater-release-readiness' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import type * as UpdaterModule from './updater-service' -import type { UpdateInstallMode } from './lifecycle/updater-state' -import type { LinuxRootPackageType, UpdateStatus } from '../../shared/update-status-types' -import { loadUpdaterModule, warmUpdaterModule } from './testing/updater-test-module-loader' -import { updaterMainWindow } from './testing/updater-test-main-window' - -const { - browserWindowMock, - nativeUpdaterMock, - autoUpdaterMock, - killAllPtyMock, - getLinuxPackageTypeMock, - getLinuxRootPackageTypeMock, - recordUpdaterLifecycleMock, - fetchNewerReleaseTagsMock, - moduleFactories, - resetUpdaterMocks -} = await vi.hoisted(async () => - (await import('./testing/updater-test-harness')).createUpdaterMocks() -) - -vi.mock('electron', () => moduleFactories.electron()) -vi.mock('electron-updater', () => moduleFactories.electronUpdater()) -vi.mock('./electron-updater-loader', () => moduleFactories.electronUpdaterLoader()) -vi.mock('../ipc/pty/kill-all', () => moduleFactories.ptyKillAll()) -vi.mock('./linux-package/linux-update-package-type', () => moduleFactories.linuxUpdatePackageType()) -vi.mock('./updater-lifecycle-diagnostics', () => moduleFactories.updaterLifecycleDiagnostics()) -vi.mock('./releases/updater-changelog', () => moduleFactories.updaterChangelog()) -vi.mock('./nudges/nudge-campaign', () => moduleFactories.updaterNudge()) -vi.mock('./update-install-exit-watchdog', () => moduleFactories.updateInstallExitWatchdog()) -vi.mock('./releases/updater-prerelease-feed', () => moduleFactories.updaterPrereleaseFeed()) -vi.mock('./releases/updater-release-readiness', async (importOriginal) => ({ - ...(await importOriginal>()), - getReleaseDownloadUrl: ( - await vi.importMock<{ - getReleaseDownloadUrl: typeof getReleaseDownloadUrl - }>('./releases/updater-prerelease-feed') - ).getReleaseDownloadUrl -})) -vi.mock('../local-builds/local-build-switch', () => moduleFactories.localBuildSwitch()) -vi.mock('../local-builds/local-build-feed-server', () => moduleFactories.localBuildFeedServer()) - -const packageSha512 = Buffer.alloc(64).toString('base64') - -function downloadedEvent(packageType: LinuxRootPackageType): Record { - const fileName = - packageType === 'deb' ? 'orca-ide_1.0.61_amd64.deb' : 'orca-ide-1.0.61.x86_64.rpm' - return { - version: '1.0.61', - downloadedFile: join(tmpdir(), 'orca-updater', 'pending', fileName), - files: [{ url: fileName, sha512: packageSha512 }] - } -} - -warmUpdaterModule() - -describe('updater Linux root packages', () => { - beforeEach(() => { - resetUpdaterMocks() - }) - - async function startUpdater( - packageType: LinuxRootPackageType | null, - installMode: UpdateInstallMode = 'interactive' - ): Promise<{ send: ReturnType; updater: typeof UpdaterModule }> { - getLinuxRootPackageTypeMock.mockReturnValue(packageType) - vi.useFakeTimers() - fetchNewerReleaseTagsMock.mockResolvedValue({ tags: ['v1.0.61'], state: 'ready' }) - autoUpdaterMock.checkForUpdates.mockImplementation(() => { - autoUpdaterMock.emit('checking-for-update') - queueMicrotask(() => autoUpdaterMock.emit('update-available', { version: '1.0.61' })) - return Promise.resolve(undefined) - }) - const send = vi.fn() - const updater = await loadUpdaterModule() - updater.setupAutoUpdater(updaterMainWindow(send), { - getLastUpdateCheckAt: () => Date.now(), - installMode - }) - return { send, updater } - } - - function lastStatus(send: ReturnType): UpdateStatus | undefined { - return send.mock.calls.findLast(([channel]) => channel === 'updater:status')?.[1] - } - - function markMacInstallerReady(): void { - if (process.platform !== 'darwin') { - return - } - const handler = nativeUpdaterMock.on.mock.calls.find( - ([eventName]) => eventName === 'update-downloaded' - )?.[1] as (() => void) | undefined - handler?.() - } - - async function reachDownloaded( - updater: typeof UpdaterModule, - event: Record, - markInstallerReady = false - ): Promise { - updater.checkForUpdatesFromMenu() - await vi.advanceTimersByTimeAsync(0) - autoUpdaterMock.downloadUpdate.mockResolvedValue([]) - updater.downloadUpdate() - autoUpdaterMock.emit('update-downloaded', event) - if (markInstallerReady) { - markMacInstallerReady() - } - await vi.advanceTimersByTimeAsync(0) - } - - it.each(['deb', 'rpm'] as const)( - 'hands off %s installs without invoking the native updater', - async (packageType) => { - const openWindow = { removeAllListeners: vi.fn() } - browserWindowMock.getAllWindows.mockReturnValue([openWindow] as never) - const { send, updater } = await startUpdater(packageType) - - await reachDownloaded(updater, downloadedEvent(packageType)) - - expect(lastStatus(send)).toEqual({ - state: 'error', - message: 'Quit Orca before running the system package install command.', - messageCode: 'linuxPackageManualInstall', - recovery: { - kind: 'linux-package-install', - packageType, - reason: 'manual-install-required', - version: '1.0.61' - } - }) - - updater.quitAndInstall() - await vi.advanceTimersByTimeAsync(100) - - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - expect(killAllPtyMock).not.toHaveBeenCalled() - expect(openWindow.removeAllListeners).not.toHaveBeenCalled() - expect(updater.isQuittingForUpdate()).toBe(false) - expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted') - expect(recordUpdaterLifecycleMock).toHaveBeenCalledWith( - 'linux_package_manual_install_required', - { packageType, version: '1.0.61' } - ) - } - ) - - it('guards the native boundary even when no package artifact was retained', async () => { - const { send, updater } = await startUpdater('deb') - - updater.quitAndInstall() - await vi.advanceTimersByTimeAsync(100) - - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - expect(killAllPtyMock).not.toHaveBeenCalled() - expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted') - }) - - it('preserves the normal AppImage install path when no root-package marker is present', async () => { - const { send, updater } = await startUpdater(null) - await reachDownloaded( - updater, - { - version: '1.0.61', - downloadedFile: join(tmpdir(), 'Orca-1.0.61.AppImage'), - files: [] - }, - true - ) - - updater.quitAndInstall() - await vi.advanceTimersByTimeAsync(100) - - expect(autoUpdaterMock.quitAndInstall).toHaveBeenCalledTimes(1) - expect(killAllPtyMock).toHaveBeenCalledTimes(1) - expect(send).not.toHaveBeenCalledWith('updater:quitAndInstallAborted') - expect( - send.mock.calls.some( - ([channel, status]) => - channel === 'updater:status' && - (status as UpdateStatus).state === 'error' && - (status as Extract).recovery?.kind === - 'linux-package-install' - ) - ).toBe(false) - }) - - it.each(['deb', 'rpm'] as const)( - 'disables install-on-quit and remote automatic control for %s builds', - async (packageType) => { - autoUpdaterMock.autoInstallOnAppQuit = true - const { updater } = await startUpdater(packageType) - - expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false) - expect(updater.getRemoteServerUpdateSupport()).toEqual({ - installMode: 'interactive', - automatic: false, - reason: 'manual-service-update-required' - }) - expect(() => updater.checkForRemoteServerUpdate('runtime-1')).toThrow( - 'remote_update_manual_required' - ) - } - ) - - it('keeps interactive install-on-quit and remote control for non-root packages', async () => { - autoUpdaterMock.autoInstallOnAppQuit = false - const { updater } = await startUpdater(null) - - expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(true) - expect(updater.getRemoteServerUpdateSupport()).toEqual({ - installMode: 'interactive', - automatic: true, - reason: 'available' - }) - }) - - it('fails closed for an unusable packaged marker', async () => { - getLinuxPackageTypeMock.mockReturnValue('unusable') - getLinuxRootPackageTypeMock.mockReturnValue(null) - autoUpdaterMock.autoInstallOnAppQuit = true - const { send, updater } = await startUpdater(null) - - expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false) - expect(updater.getRemoteServerUpdateSupport()).toEqual({ - installMode: 'interactive', - automatic: false, - reason: 'manual-service-update-required' - }) - - await reachDownloaded(updater, { - version: '1.0.61', - downloadedFile: join(tmpdir(), 'orca-updater', 'pending', 'orca-ide_1.0.61_amd64.deb'), - files: [{ url: 'orca-ide_1.0.61_amd64.deb', sha512: packageSha512 }] - }) - expect(lastStatus(send)).toEqual({ - state: 'error', - message: - 'Orca could not verify the installed Linux package format, so it will not install this update automatically. Download the update from the official release page and install it manually.', - messageCode: 'linuxPackageMarkerUnusable', - version: '1.0.61', - retryable: false - }) - - updater.quitAndInstall() - await vi.advanceTimersByTimeAsync(100) - expect(autoUpdaterMock.quitAndInstall).not.toHaveBeenCalled() - expect(send).toHaveBeenCalledWith('updater:quitAndInstallAborted') - }) - - it('leaves headless serve installs supervisor-controlled', async () => { - for (const installMode of [ - 'supervised-headless-serve', - 'unsupported-headless-serve' - ] as const) { - resetUpdaterMocks() - autoUpdaterMock.autoInstallOnAppQuit = true - await startUpdater(null, installMode) - expect(autoUpdaterMock.autoInstallOnAppQuit).toBe(false) - } - }) -}) diff --git a/src/main/usage/jsonl-file-reader.test.ts b/src/main/usage/jsonl-file-reader.test.ts index 67dbd32ac0f..daf2ee59a5d 100644 --- a/src/main/usage/jsonl-file-reader.test.ts +++ b/src/main/usage/jsonl-file-reader.test.ts @@ -3,10 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { - MIN_RESUMABLE_PREFIX_BYTES, - jsonlPhysicalFileId, openJsonlFileReader, - resolveJsonlFileCheckpoint, validateJsonlFileReader, type JsonlFileReader } from './jsonl-file-checkpoint' @@ -55,76 +52,6 @@ function positionalReadArgs(args: readonly unknown[]): [Buffer, number, number, } describe('pinned small JSONL reader', () => { - it('encodes large physical identifiers exactly and preserves numeric caller compatibility', () => { - expect(jsonlPhysicalFileId({ dev: 1n, ino: 9_007_199_254_740_992n })).toBe('1:9007199254740992') - expect(jsonlPhysicalFileId({ dev: 1n, ino: 9_007_199_254_740_993n })).toBe('1:9007199254740993') - expect(jsonlPhysicalFileId({ dev: 3, ino: 4 })).toBe('3:4') - expect(jsonlPhysicalFileId({ dev: 3, ino: 0 })).toBeNull() - expect(jsonlPhysicalFileId({ dev: 3n, ino: 0n })).toBeNull() - }) - - it.each([Number.NaN, Infinity, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])( - 'rejects an invalid persisted offset %s before attempting a range read', - async (parsedBytes) => { - await expect( - resolveJsonlFileCheckpoint(filePath, { - parsedBytes, - headDigest: '4096:invalid', - boundaryDigest: '4096:invalid', - physicalFileId: null - }) - ).resolves.toBeNull() - } - ) - - it('verifies an empty snapshot without creating a stream or issuing a read', async () => { - const active = await openFixture('') - const read = vi.spyOn(active.handle, 'read') - const stream = vi.spyOn(active.handle, 'createReadStream') - - expect(await collect(active)).toEqual([]) - expect(await validateJsonlFileReader(active)).toBe(true) - expect(stream).not.toHaveBeenCalled() - expect(read).not.toHaveBeenCalled() - }) - - it('reads and verifies all bytes twice without creating a stream', async () => { - const contents = '会🙂\r\n\r\nnext\n尾🙂' - const active = await openFixture(contents) - const read = vi.spyOn(active.handle, 'read') - const stream = vi.spyOn(active.handle, 'createReadStream') - - expect(await collect(active)).toEqual([ - { line: '会🙂', endOffset: Buffer.byteLength('会🙂\r\n'), terminated: true }, - { line: '', endOffset: Buffer.byteLength('会🙂\r\n\r\n'), terminated: true }, - { line: 'next', endOffset: Buffer.byteLength('会🙂\r\n\r\nnext\n'), terminated: true }, - { line: '尾🙂', endOffset: Buffer.byteLength(contents), terminated: false } - ]) - expect(await validateJsonlFileReader(active)).toBe(true) - expect(stream).not.toHaveBeenCalled() - expect(read).toHaveBeenCalledTimes(2) - expect( - (await Promise.all(read.mock.results.map((result) => result.value))).map( - (result) => result.bytesRead - ) - ).toEqual([Buffer.byteLength(contents), Buffer.byteLength(contents)]) - }) - - it('accounts for a skipped legacy prefix in the full snapshot proof', async () => { - const contents = 'legacy会\r\nnew🙂\r\n' - const active = await openFixture(contents) - const offset = Buffer.byteLength('legacy会\r\n') - const read = vi.spyOn(active.handle, 'read') - - expect(await collect(active, offset)).toEqual([ - { line: 'new🙂', endOffset: Buffer.byteLength(contents), terminated: true } - ]) - expect(await validateJsonlFileReader(active)).toBe(true) - expect(active.streamBytes).toBe(Buffer.byteLength(contents) - offset) - expect(active.snapshotBytes).toBe(Buffer.byteLength(contents)) - expect(read).toHaveBeenCalledTimes(3) - }) - it('accumulates short positional reads without exposing gaps or duplicate bytes', async () => { const contents = '会🙂\r\nnext\n終🙂' const active = await openFixture(contents) @@ -142,19 +69,6 @@ describe('pinned small JSONL reader', () => { expect(await validateJsonlFileReader(active)).toBe(true) }) - it('rejects a stable premature EOF instead of publishing partial history', async () => { - const active = await openFixture('one\ntwo\n') - const read = active.handle.read.bind(active.handle) - vi.spyOn(active.handle, 'read').mockImplementationOnce(async (...args) => { - const result = await read(...args) - return { ...result, bytesRead: 0 } - }) - - await expect(collect(active)).rejects.toThrow(/snapshot read.*unchanged file boundary/) - expect(active.streamBytes).toBe(0) - expect(active.snapshotBytes).toBe(0) - }) - it('rejects an unchanged EOF after a positive short read without yielding a partial line', async () => { const active = await openFixture('one\ntwo\n') const read = active.handle.read.bind(active.handle) @@ -235,19 +149,4 @@ describe('pinned small JSONL reader', () => { expect(await collect(active)).toEqual([]) expect(await validateJsonlFileReader(active)).toBe(false) }) - - it('uses the bounded buffer at the crossover and streams larger snapshots', async () => { - const active = await openFixture(`${'x'.repeat(MIN_RESUMABLE_PREFIX_BYTES - 1)}\n`) - const stream = vi.spyOn(active.handle, 'createReadStream') - await collect(active) - expect(await validateJsonlFileReader(active)).toBe(true) - expect(stream).not.toHaveBeenCalled() - await active.handle.close() - reader = undefined - const large = await openFixture(`${'x'.repeat(MIN_RESUMABLE_PREFIX_BYTES)}\n`) - const largeStream = vi.spyOn(large.handle, 'createReadStream') - await collect(large) - expect(await validateJsonlFileReader(large)).toBe(true) - expect(largeStream).toHaveBeenCalledOnce() - }) }) diff --git a/src/main/window/clipboard-windows-image-file.test.ts b/src/main/window/clipboard-windows-image-file.test.ts index 5040ef2fe68..c9657718077 100644 --- a/src/main/window/clipboard-windows-image-file.test.ts +++ b/src/main/window/clipboard-windows-image-file.test.ts @@ -1,8 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { - CLIPBOARD_IMAGE_MAX_PIXELS, - CLIPBOARD_IMAGE_MAX_SOURCE_BYTES -} from '../../shared/clipboard-image' +import { CLIPBOARD_IMAGE_MAX_PIXELS } from '../../shared/clipboard-image' import { readWindowsClipboardImageFileAsPng } from './clipboard-windows-image-file' function fileNameW(filePath: string): Buffer { @@ -25,36 +22,6 @@ function pngHeader(width = 10, height = 10): Buffer { return source } -function jpegHeader(width = 10, height = 10): Buffer { - return Buffer.from([ - 0xff, - 0xd8, - 0xff, - 0xe0, - 0x00, - 0x02, - 0xff, - 0xc2, - 0x00, - 0x07, - 0x08, - height >> 8, - height & 0xff, - width >> 8, - width & 0xff - ]) -} - -function image(png = Buffer.from([4, 3, 2, 1])) { - const decoded = { - getSize: () => ({ height: 10, width: 10 }), - isEmpty: () => false, - resize: () => decoded, - toPNG: () => png - } - return decoded -} - function fileHandle( source: Buffer, options: { chunkSize?: number; isFile?: boolean; size?: number } = {} @@ -80,31 +47,6 @@ function fileHandle( } describe('readWindowsClipboardImageFileAsPng', () => { - it.each([ - 'C:\\Users\\alice\\图片\\shot.PNG', - '\\\\server\\share\\shot.jpeg', - '\\\\?\\C:\\Users\\alice\\shot.jpg', - '\\\\?\\UNC\\server\\share\\shot.png' - ])('decodes and converts a bounded FileNameW path: %s', async (filePath) => { - const source = filePath.toLowerCase().endsWith('.png') ? pngHeader() : jpegHeader() - const png = Buffer.from([9, 8, 7]) - const handle = fileHandle(source, { chunkSize: 3 }) - const openFile = vi.fn().mockResolvedValue(handle) - const createImageFromBuffer = vi.fn(() => image(png) as never) - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats(filePath), { - createImageFromBuffer, - openFile - }) - ).resolves.toEqual(png) - - expect(openFile).toHaveBeenCalledWith(filePath) - expect(handle.read.mock.calls.length).toBeGreaterThan(1) - expect(handle.close).toHaveBeenCalledOnce() - expect(createImageFromBuffer).toHaveBeenCalledWith(source) - }) - it.each([ ['empty', Buffer.alloc(0)], ['odd byte count', Buffer.from([65, 0, 0])], @@ -133,95 +75,6 @@ describe('readWindowsClipboardImageFileAsPng', () => { expect(createImageFromBuffer).not.toHaveBeenCalled() }) - it('rejects an Explorer multi-selection when FileNameW exposes only its first path', async () => { - const openFile = vi.fn() - const createImageFromBuffer = vi.fn() - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\one.png', 2), { - createImageFromBuffer, - openFile - }) - ).resolves.toBeNull() - - expect(openFile).not.toHaveBeenCalled() - expect(createImageFromBuffer).not.toHaveBeenCalled() - }) - - it('ignores missing, inaccessible, and looping paths', async () => { - for (const code of ['ENOENT', 'EACCES', 'ELOOP']) { - const error = Object.assign(new Error(code), { code }) - const openFile = vi.fn().mockRejectedValue(error) - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\shot.png'), { - createImageFromBuffer: vi.fn(), - openFile - }) - ).resolves.toBeNull() - } - }) - - it('ignores directories and closes their handles', async () => { - const handle = fileHandle(Buffer.alloc(0), { isFile: false }) - const createImageFromBuffer = vi.fn() - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\images.png'), { - createImageFromBuffer, - openFile: vi.fn().mockResolvedValue(handle) - }) - ).resolves.toBeNull() - - expect(handle.read).not.toHaveBeenCalled() - expect(handle.close).toHaveBeenCalledOnce() - expect(createImageFromBuffer).not.toHaveBeenCalled() - }) - - it('rejects oversized sources before reading or decoding', async () => { - const handle = fileHandle(Buffer.alloc(0), { - size: CLIPBOARD_IMAGE_MAX_SOURCE_BYTES + 1 - }) - const createImageFromBuffer = vi.fn() - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\huge.png'), { - createImageFromBuffer, - openFile: vi.fn().mockResolvedValue(handle) - }) - ).rejects.toThrow('Clipboard image is too large') - - expect(handle.read).not.toHaveBeenCalled() - expect(handle.close).toHaveBeenCalledOnce() - expect(createImageFromBuffer).not.toHaveBeenCalled() - }) - - it('ignores a source that changes size after handle validation', async () => { - const handle = fileHandle(Buffer.from('grew'), { size: 3 }) - const createImageFromBuffer = vi.fn() - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\changed.png'), { - createImageFromBuffer, - openFile: vi.fn().mockResolvedValue(handle) - }) - ).resolves.toBeNull() - - expect(handle.close).toHaveBeenCalledOnce() - expect(createImageFromBuffer).not.toHaveBeenCalled() - }) - - it('ignores image bytes the native decoder cannot decode', async () => { - const handle = fileHandle(Buffer.from('not-an-image')) - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\invalid.png'), { - createImageFromBuffer: vi.fn(() => ({ isEmpty: () => true }) as never), - openFile: vi.fn().mockResolvedValue(handle) - }) - ).resolves.toBeNull() - }) - it('rejects oversized encoded dimensions before native decoding', async () => { const handle = fileHandle(pngHeader(CLIPBOARD_IMAGE_MAX_PIXELS + 1, 1)) const createImageFromBuffer = vi.fn() @@ -236,49 +89,4 @@ describe('readWindowsClipboardImageFileAsPng', () => { expect(createImageFromBuffer).not.toHaveBeenCalled() expect(handle.close).toHaveBeenCalledOnce() }) - - it('bounds malformed JPEG marker scanning before native decoding', async () => { - const source = Buffer.alloc(2 + 2 * 4097) - source.set([0xff, 0xd8]) - for (let offset = 2; offset < source.byteLength; offset += 2) { - source.set([0xff, 0x01], offset) - } - const createImageFromBuffer = vi.fn() - - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\marker-flood.jpg'), { - createImageFromBuffer, - openFile: vi.fn().mockResolvedValue(fileHandle(source)) - }) - ).resolves.toBeNull() - - expect(createImageFromBuffer).not.toHaveBeenCalled() - }) - - it('bounds decoded dimensions and converted PNG bytes', async () => { - const oversizedDimensions = fileHandle(pngHeader()) - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\wide.png'), { - createImageFromBuffer: vi.fn( - () => - ({ - getSize: () => ({ height: 1, width: CLIPBOARD_IMAGE_MAX_PIXELS + 1 }), - isEmpty: () => false, - toPNG: vi.fn() - }) as never - ), - openFile: vi.fn().mockResolvedValue(oversizedDimensions) - }) - ).rejects.toThrow('Clipboard image is too large') - - const oversizedPng = fileHandle(pngHeader()) - await expect( - readWindowsClipboardImageFileAsPng(clipboardFormats('C:\\expanded.png'), { - createImageFromBuffer: vi.fn( - () => image(Buffer.alloc(CLIPBOARD_IMAGE_MAX_SOURCE_BYTES + 1)) as never - ), - openFile: vi.fn().mockResolvedValue(oversizedPng) - }) - ).rejects.toThrow('Clipboard image is too large') - }) }) diff --git a/src/main/window/createMainWindow-renderer-launch-failure.test.ts b/src/main/window/createMainWindow-renderer-launch-failure.test.ts deleted file mode 100644 index 18359bdbee6..00000000000 --- a/src/main/window/createMainWindow-renderer-launch-failure.test.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('./desktop-integration/app-icon', async () => - (await import('./createMainWindow-test-harness')).appIconMock() -) -vi.mock('../browser/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) -vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => { - const harness = await import('./createMainWindow-test-harness') - return { - attachBrowserClientPageRenderer: harness.attachClientPageRendererMock, - retireBrowserClientPageRenderer: harness.retireClientPageRendererMock - } -}) - -import { createMainWindow } from './createMainWindow' -import type { CreateMainWindowOptions } from './main-window-contracts' -import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-gone-classification' -import { - browserWindowMock, - resetMainWindowMocks, - withPlatform -} from './createMainWindow-test-harness' -import { RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS } from './renderer-launch-failure-backoff' - -// macOS LAUNCH_RESULT_FAILURE: posix_spawn of the Renderer helper failed (field: EAGAIN, per-user process limit). -const LAUNCH_FAILED: Electron.RenderProcessGoneDetails = { reason: 'launch-failed', exitCode: 1003 } -const CRASHED: Electron.RenderProcessGoneDetails = { reason: 'crashed', exitCode: 5 } - -/** Reproduce spawn refusal: launch-failed then ERR_FAILED before a document; the same WebContents loads once process headroom returns. */ -function createSpawnRefusingWindow( - platform: NodeJS.Platform = 'darwin', - failure: Electron.RenderProcessGoneDetails = LAUNCH_FAILED -) { - const handlers: Record void> = {} - const spawn = { refused: true } - const webContents = { - id: 143, - getURL: vi.fn(() => 'file:///opt/orca/renderer/index.html'), - isDestroyed: vi.fn(() => false), - on: vi.fn((event: string, handler: (...args: any[]) => void) => { - handlers[event] = handler - }), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn() - } - const load = vi.fn((): Promise => { - if (!spawn.refused) { - queueMicrotask(() => handlers['did-finish-load']?.()) - return Promise.resolve() - } - queueMicrotask(() => - withPlatform(platform, () => handlers['render-process-gone']?.({}, failure)) - ) - return Promise.reject( - new Error("ERR_FAILED (-2) loading 'file:///opt/orca/renderer/index.html'") - ) - }) - browserWindowMock.mockImplementation(function () { - return { - webContents, - on: vi.fn((event: string, handler: (...args: any[]) => void) => { - handlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: load, - loadURL: load - } - }) - return { handlers, load, spawn } -} - -function open(overrides: CreateMainWindowOptions = {}) { - const onRendererRecoveryExhausted = vi.fn() - const onRecoveryReloadOutcome = vi.fn() - createMainWindow(null, { - onRendererRecoveryExhausted, - onRecoveryReloadOutcome, - shouldRecoverRenderer: (details) => - shouldRecoverRendererAfterProcessGone({ reason: details.reason, expectedTeardown: 'none' }), - ...overrides - }) - return { onRendererRecoveryExhausted, onRecoveryReloadOutcome } -} - -const BACKOFF_TOTAL_MS = RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.reduce((sum, ms) => sum + ms, 0) - -describe('renderer launch-failed recovery', () => { - beforeEach(() => { - resetMainWindowMocks() - vi.useFakeTimers() - vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('recovers in place once spawn headroom returns, without any prompt', async () => { - const { handlers, load, spawn } = createSpawnRefusingWindow() - const { onRendererRecoveryExhausted, onRecoveryReloadOutcome } = open() - // Reproduce process-table exhaustion lasting minutes. - await vi.advanceTimersByTimeAsync(250 + 1_000 + 2_000 + 4_000 + 8_000 + 15_000) - expect(load).toHaveBeenCalledTimes(7) - spawn.refused = false - - await vi.advanceTimersByTimeAsync(30_000) - expect(load).toHaveBeenCalledTimes(8) - expect(onRecoveryReloadOutcome).toHaveBeenLastCalledWith( - expect.objectContaining({ status: 'loaded' }) - ) - await vi.advanceTimersByTimeAsync(5 * 60_000) - expect(load).toHaveBeenCalledTimes(8) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - - // A loaded document resets the launch-failure backoff. - spawn.refused = true - handlers['render-process-gone']?.({}, LAUNCH_FAILED) - await vi.advanceTimersByTimeAsync(250) - expect(load).toHaveBeenCalledTimes(9) - }) - - it('prompts only after the ~2 minute schedule is spent, then a failed manual retry re-prompts', async () => { - const { load } = createSpawnRefusingWindow() - const { onRendererRecoveryExhausted } = open() - await vi.advanceTimersByTimeAsync(BACKOFF_TOTAL_MS - 1) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - - // Prompt on the next recovery tick after the final retry fails. - await vi.advanceTimersByTimeAsync(251) - expect(BACKOFF_TOTAL_MS).toBeLessThanOrEqual(125_000) - expect(load).toHaveBeenCalledTimes(1 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - expect(onRendererRecoveryExhausted).toHaveBeenCalledWith( - expect.objectContaining({ - details: LAUNCH_FAILED, - cause: 'launch-failed', - recentRecoveryCount: RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length - }) - ) - - onRendererRecoveryExhausted.mock.calls[0]?.[0].retry() - expect(load).toHaveBeenCalledTimes(2 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length) - await vi.advanceTimersByTimeAsync(250) - expect(onRendererRecoveryExhausted).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(5 * 60_000) - expect(load).toHaveBeenCalledTimes(2 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length) - }) - - it('stops recovery when quitting during the long backoff', async () => { - const { load } = createSpawnRefusingWindow() - let quitting = false - const { onRendererRecoveryExhausted } = open({ getIsQuitting: () => quitting }) - await vi.advanceTimersByTimeAsync(250 + 1_000 + 2_000 + 4_000) - const loadsBeforeQuit = load.mock.calls.length - quitting = true - await vi.advanceTimersByTimeAsync(BACKOFF_TOTAL_MS * 2) - expect(load).toHaveBeenCalledTimes(loadsBeforeQuit) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - }) - - it('does not spend retry attempts on duplicate failure events', async () => { - const { handlers, load } = createSpawnRefusingWindow() - const { onRendererRecoveryExhausted } = open() - await vi.advanceTimersByTimeAsync(0) - handlers['render-process-gone']?.({}, LAUNCH_FAILED) - handlers['render-process-gone']?.({}, LAUNCH_FAILED) - await vi.advanceTimersByTimeAsync(250) - expect(load).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(999) - expect(load).toHaveBeenCalledTimes(2) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - }) - - it('rides out a Windows sandbox CreateProcess refusal in place instead of prompting', async () => { - // Windows SBOX_ERROR_CREATE_PROCESS; awin repro (job capped at 1 process for 5s) prompted after ~1s on the 750ms breaker. - const { spawn } = createSpawnRefusingWindow('win32', { - reason: 'launch-failed', - exitCode: 18 - }) - const { onRendererRecoveryExhausted, onRecoveryReloadOutcome } = open() - await vi.advanceTimersByTimeAsync(5_000) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - spawn.refused = false - - await vi.advanceTimersByTimeAsync(4_000) - expect(onRecoveryReloadOutcome).toHaveBeenLastCalledWith( - expect.objectContaining({ status: 'loaded' }) - ) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - }) - - it('still prompts on Windows once a persistent CreateProcess refusal spends the schedule', async () => { - const SANDBOX_REFUSED = { reason: 'launch-failed', exitCode: 18 } as const - const { load } = createSpawnRefusingWindow('win32', SANDBOX_REFUSED) - const { onRendererRecoveryExhausted } = open() - await vi.advanceTimersByTimeAsync(BACKOFF_TOTAL_MS - 1) - expect(onRendererRecoveryExhausted).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(251) - expect(load).toHaveBeenCalledTimes(1 + RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length) - expect(onRendererRecoveryExhausted).toHaveBeenCalledOnce() - expect(onRendererRecoveryExhausted).toHaveBeenCalledWith( - expect.objectContaining({ - details: SANDBOX_REFUSED, - cause: 'launch-failed', - recentRecoveryCount: RENDERER_LAUNCH_FAILURE_RETRY_DELAYS_MS.length - }) - ) - }) - - it('keeps the crash-loop breaker for renderers that actually crash', async () => { - const { handlers, load, spawn } = createSpawnRefusingWindow() - spawn.refused = false - const { onRendererRecoveryExhausted } = open() - await vi.advanceTimersByTimeAsync(0) - for (let i = 0; i < 4; i += 1) { - handlers['render-process-gone']?.({}, CRASHED) - await vi.advanceTimersByTimeAsync(250) - } - expect(load).toHaveBeenCalledTimes(4) - expect(onRendererRecoveryExhausted).toHaveBeenCalledWith( - expect.objectContaining({ details: CRASHED, cause: 'crash-loop', recentRecoveryCount: 3 }) - ) - }) -}) diff --git a/src/main/window/native-chat-paste-files.test.ts b/src/main/window/native-chat-paste-files.test.ts index 849aa70b20d..77498786878 100644 --- a/src/main/window/native-chat-paste-files.test.ts +++ b/src/main/window/native-chat-paste-files.test.ts @@ -7,7 +7,7 @@ import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/ import type { Store } from '../persistence/loading-store/store' import { resolveLocalFileRequestPath } from '../ipc/filesystem/access/local-file-access-resolution' import { readLocalFileContent } from '../ipc/filesystem/filesystem-file-content-inspection' -import { isInsideNativeChatPasteFolder, restoreNativeChatPastes } from './native-chat-paste-files' +import { restoreNativeChatPastes } from './native-chat-paste-files' // A store with no projects: nothing but an access kind decides what a read may reach. const NO_PROJECTS: Store = Object.assign(Object.create(null), { @@ -30,46 +30,6 @@ async function chatImageReadable(target: string): Promise { } } -describe('isInsideNativeChatPasteFolder', () => { - const posixFolder = '/data/native-chat-pastes' - const winFolder = 'C:\\Users\\Me\\AppData\\Roaming\\Orca\\native-chat-pastes' - - it.each([ - ['a file inside', `${posixFolder}/orca-paste-1.png`, true], - ['a name that only starts with dots', `${posixFolder}/..orca-paste-1.png`, true], - ['the folder itself', posixFolder, false], - ['the parent', '/data', false], - ['a sibling reached through ..', `${posixFolder}/../secret.png`, false], - ['a sibling folder sharing the prefix', '/data/native-chat-pastes-evil/x.png', false], - ['an unrelated absolute path', '/etc/passwd', false] - ])('posix: %s', (_label, target, inside) => { - expect(isInsideNativeChatPasteFolder(posixFolder, target, path.posix, 'darwin')).toBe(inside) - }) - - it.each([ - ['a file inside', `${winFolder}\\orca-paste-1.png`, true], - ['a file inside in other letter case', `${winFolder.toLowerCase()}\\ORCA-PASTE-1.PNG`, true], - ['a \\\\?\\ prefixed file inside', `\\\\?\\${winFolder}\\orca-paste-1.png`, true], - ['another drive', 'D:\\native-chat-pastes\\orca-paste-1.png', false], - ['a \\\\?\\UNC share', '\\\\?\\UNC\\server\\share\\orca-paste-1.png', false], - ['a sibling reached through ..', `${winFolder}\\..\\secret.png`, false], - ['the folder itself', winFolder, false] - ])('win32: %s', (_label, target, inside) => { - expect(isInsideNativeChatPasteFolder(winFolder, target, path.win32, 'win32')).toBe(inside) - }) - - it('compares a \\\\?\\ prefixed folder like its plain form', () => { - expect( - isInsideNativeChatPasteFolder( - `\\\\?\\${winFolder}`, - `${winFolder}\\orca-paste-1.png`, - path.win32, - 'win32' - ) - ).toBe(true) - }) -}) - describe('native-chat paste folder on disk', () => { let root: string let folder: string @@ -117,16 +77,6 @@ describe('native-chat paste folder on disk', () => { await expect(restoreNativeChatPastes('not a list')).resolves.toEqual([]) }) - it('leaves a kept paste readable by the composer preview, with no grant', async () => { - const kept = path.join(folder, 'orca-paste-1.png') - writeFileSync(kept, 'png') - await expect(restoreNativeChatPastes([kept])).resolves.toEqual([ - { path: kept, kept: true, exists: true } - ]) - const readable = await resolveLocalFileRequestPath(kept, { kind: 'chat-image' }, NO_PROJECTS) - await expect(readLocalFileContent(readable)).resolves.toMatchObject({ mimeType: 'image/png' }) - }) - it('keeps a paste reached through a symlinked alias of the folder, as /var is of /private/var', async () => { const kept = path.join(folder, 'orca-paste-1.png') writeFileSync(kept, 'png') @@ -207,18 +157,4 @@ describe('native-chat paste folder on disk', () => { [{ path: path.join(folder, 'orca-paste-1.png'), kept: false, exists: false }] ) }) - - it('reports nothing kept when the folder does not exist yet', async () => { - rmSync(folder, { recursive: true }) - await expect( - resolveLocalFileRequestPath( - path.join(root, 'agent-session-attachments', 'upload', 'gone.png'), - { kind: 'chat-image' }, - NO_PROJECTS - ) - ).rejects.toMatchObject({ code: 'ENOENT' }) - await expect(restoreNativeChatPastes([path.join(folder, 'orca-paste-1.png')])).resolves.toEqual( - [{ path: path.join(folder, 'orca-paste-1.png'), kept: false, exists: false }] - ) - }) }) diff --git a/src/main/window/renderer-recovery-prompt.test.ts b/src/main/window/renderer-recovery-prompt.test.ts deleted file mode 100644 index 995cd88f4dc..00000000000 --- a/src/main/window/renderer-recovery-prompt.test.ts +++ /dev/null @@ -1,271 +0,0 @@ -import type { MessageBoxOptions, MessageBoxReturnValue } from 'electron' -import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' -import { mainI18n } from '../i18n/main-i18n' -import type { InstallDirAclPoisonDiagnosis } from '../startup/windows-install-dir-acl-recovery' -import { - presentRendererRecoveryPrompt, - type RendererRecoveryPromptDeps -} from './renderer-recovery-prompt' - -vi.mock('electron', () => ({ app: { getLocale: () => 'en-US' } })) - -const POISON: InstallDirAclPoisonDiagnosis = { - detail: "Windows permissions on Orca's install folder are blocking its own sandboxed processes.", - commands: ['icacls "C:\\Orca" /grant "*S-1-15-2-2:(OI)(CI)(RX)"', 'icacls "C:\\Orca" /grant b'] -} - -function harness(overrides: Partial & { responses?: number[] } = {}): { - run: () => Promise - shown: MessageBoxOptions[] - copied: string[] - reload: ReturnType - quit: ReturnType -} { - const { responses = [0], ...rest } = overrides - const shown: MessageBoxOptions[] = [] - const copied: string[] = [] - const reload = vi.fn() - const quit = vi.fn() - const deps: RendererRecoveryPromptDeps = { - recentRecoveryCount: 4, - isQuitting: () => false, - diagnose: () => null, - showMessageBox: async (options: MessageBoxOptions): Promise => { - shown.push(options) - return { - response: responses[Math.min(shown.length - 1, responses.length - 1)], - checkboxChecked: false - } - }, - copyToClipboard: (text) => copied.push(text), - reload, - quit, - ...rest - } - return { run: () => presentRendererRecoveryPrompt(deps), shown, copied, reload, quit } -} - -describe('presentRendererRecoveryPrompt', () => { - beforeEach(async () => { - await mainI18n.changeLanguage('en') - }) - - afterEach(() => { - mainI18n.removeResourceBundle('en', 'translation') - }) - - it('interpolates the recovery count', async () => { - const { run, shown } = harness({ recentRecoveryCount: 7 }) - await run() - expect(shown[0].detail).toContain('Orca tried to recover 7 times in a row') - expect(shown[0].detail).not.toContain('{{') - }) - - it.each([ - { responses: [1, 0], reloads: 1, quits: 0 }, - { responses: [1, 2], reloads: 0, quits: 1 } - ])( - 'dispatches translated buttons by response index: $responses', - async ({ responses, reloads, quits }) => { - mainI18n.addResourceBundle('en', 'translation', { - rendererRecovery: { reload: 'Recharger', copyCommands: 'Copier', quit: 'Quitter' } - }) - const { run, shown, copied, reload, quit } = harness({ diagnose: () => POISON, responses }) - await run() - expect(shown[0].buttons).toEqual(['Recharger', 'Copier', 'Quitter']) - expect(copied).toEqual([POISON.commands.join('\r\n')]) - expect(reload).toHaveBeenCalledTimes(reloads) - expect(quit).toHaveBeenCalledTimes(quits) - } - ) - - it('offers reload and quit with the generic cause when nothing is diagnosed', async () => { - const { run, shown, reload, quit } = harness({ responses: [0] }) - await run() - expect(shown).toHaveLength(1) - expect(shown[0].buttons).toEqual(['Reload', 'Quit']) - // Escape retries; a window-modal recovery box must not quit the session. - expect(shown[0].cancelId).toBe(0) - expect(shown[0].detail).toContain('graphics-driver or installation problem') - expect(reload).toHaveBeenCalledOnce() - expect(quit).not.toHaveBeenCalled() - }) - - it('names the stalled reload instead of claiming a repeated crash', async () => { - const { run, shown } = harness({ failure: 'reload-stalled', responses: [1] }) - await run() - expect(shown[0].message).toContain('stopped responding while reloading') - expect(shown[0].detail).toContain('never finished loading') - expect(shown[0].detail).not.toContain('times in a row') - }) - - it('says Windows is out of memory with the commit left, instead of blaming drivers', async () => { - const { run, shown, reload } = harness({ - failure: 'low-commit', - availableCommitMB: 60, - responses: [0] - }) - await run() - expect(shown[0].message).toBe('Windows is out of memory.') - expect(shown[0].detail).toContain('only 60 MB of memory left') - expect(shown[0].detail).toContain('increase the Windows page file size') - expect(shown[0].detail).not.toContain('graphics') - expect(shown[0].buttons).toEqual(['Reload', 'Quit']) - expect(reload).toHaveBeenCalledOnce() - }) - - it('omits Copy Commands on low commit, since its detail would not be shown', async () => { - const { run, shown, quit, copied } = harness({ - failure: 'low-commit', - availableCommitMB: 60, - diagnose: () => POISON, - responses: [1] - }) - await run() - expect(shown[0].buttons).toEqual(['Reload', 'Quit']) - expect(copied).toEqual([]) - expect(quit).toHaveBeenCalledOnce() - }) - - it('quits on the last button', async () => { - const { run, reload, quit } = harness({ responses: [1] }) - await run() - expect(quit).toHaveBeenCalledOnce() - expect(reload).not.toHaveBeenCalled() - }) - - it('names the install-permission cause and keeps the driver hint', async () => { - const { run, shown } = harness({ diagnose: () => POISON, responses: [0] }) - await run() - expect(shown[0].buttons).toEqual(['Reload', 'Copy Commands', 'Quit']) - expect(shown[0].cancelId).toBe(0) - expect(shown[0].detail).toContain(POISON.detail) - expect(shown[0].detail).toContain('graphics driver') - }) - - // Copy must retain the dialog: blank windows have no other recovery surface. - it('keeps the dialog up after copying the commands, then still reloads', async () => { - const { run, shown, copied, reload, quit } = harness({ - diagnose: () => POISON, - responses: [1, 1, 0] - }) - await run() - expect(copied).toEqual([POISON.commands.join('\r\n'), POISON.commands.join('\r\n')]) - expect(shown).toHaveLength(3) - expect(reload).toHaveBeenCalledOnce() - expect(quit).not.toHaveBeenCalled() - }) - - it('quits on the third button once the diagnosis adds one', async () => { - const { run, quit, copied } = harness({ diagnose: () => POISON, responses: [2] }) - await run() - expect(quit).toHaveBeenCalledOnce() - expect(copied).toEqual([]) - }) - - it('shows nothing once the app is already quitting', async () => { - const { run, shown } = harness({ isQuitting: () => true }) - await run() - expect(shown).toEqual([]) - }) - - // Re-read asynchronous repair diagnosis each pass so settled repair replaces stale repairing copy. - it('re-reads the diagnosis on every pass', async () => { - const details = ['repairing now', 'repaired'] - let pass = 0 - const { run, shown } = harness({ - diagnose: () => ({ detail: details[Math.min(pass++, 1)], commands: POISON.commands }), - responses: [1, 0] - }) - await run() - expect(shown[0].detail).toContain('repairing now') - expect(shown[1].detail).toContain('repaired') - }) - - describe('after a renderer launch failure', () => { - it('names the process limit when the probe is refused with EAGAIN', async () => { - const probeLaunchCapacity = vi.fn(async () => 'EAGAIN') - const { run, shown, reload, quit } = harness({ - failure: 'launch-failed', - recentRecoveryCount: 8, - probeLaunchCapacity - }) - await run() - expect(probeLaunchCapacity).toHaveBeenCalledOnce() - // No Restart: app.relaunch needs a free process slot too and silently fails without one. - expect(shown[0].buttons).toEqual(['Try Again', 'Quit']) - expect(shown[0].defaultId).toBe(0) - expect(shown[0].cancelId).toBe(0) - expect(shown[0].message).toContain("couldn't start the process") - expect(shown[0].detail).toContain('retried 8 times') - expect(shown[0].detail).toContain('process limit') - expect(shown[0].detail).not.toMatch(/graphics|driver/i) - expect(reload).toHaveBeenCalledOnce() - expect(quit).not.toHaveBeenCalled() - }) - - it('drops the graphics-driver blame when the probe could spawn', async () => { - const { run, shown, quit } = harness({ - failure: 'launch-failed', - probeLaunchCapacity: async () => 'ok', - responses: [1] - }) - await run() - expect(shown[0].detail).not.toContain('process limit') - expect(shown[0].detail).not.toMatch(/graphics|driver/i) - expect(shown[0].detail).toContain('Try Again') - expect(quit).toHaveBeenCalledOnce() - }) - - it('probes once even when Copy Commands re-shows the box', async () => { - const probeLaunchCapacity = vi.fn(async () => 'ok') - const { run, shown, reload } = harness({ - failure: 'launch-failed', - diagnose: () => POISON, - probeLaunchCapacity, - responses: [1, 1, 0] - }) - await run() - expect(shown).toHaveLength(3) - expect(probeLaunchCapacity).toHaveBeenCalledOnce() - expect(reload).toHaveBeenCalledOnce() - }) - - it('shows nothing when the app starts quitting during the probe', async () => { - let quitting = false - const { run, shown, reload } = harness({ - failure: 'launch-failed', - isQuitting: () => quitting, - probeLaunchCapacity: async () => { - quitting = true - return 'EAGAIN' - } - }) - await run() - expect(shown).toEqual([]) - expect(reload).not.toHaveBeenCalled() - }) - - it('does not probe once the app is already quitting', async () => { - const probeLaunchCapacity = vi.fn(async () => 'ok') - const { run } = harness({ - failure: 'launch-failed', - isQuitting: () => true, - probeLaunchCapacity - }) - await run() - expect(probeLaunchCapacity).not.toHaveBeenCalled() - }) - - it('keeps the install-permission diagnosis and its copy button', async () => { - const { run, shown } = harness({ - failure: 'launch-failed', - diagnose: () => POISON, - probeLaunchCapacity: async () => 'ok' - }) - await run() - expect(shown[0].buttons).toEqual(['Try Again', 'Copy Commands', 'Quit']) - expect(shown[0].detail).toContain(POISON.detail) - }) - }) -}) diff --git a/src/main/workspaces/catalog/repo-worktrees.test.ts b/src/main/workspaces/catalog/repo-worktrees.test.ts deleted file mode 100644 index e2b17ade11c..00000000000 --- a/src/main/workspaces/catalog/repo-worktrees.test.ts +++ /dev/null @@ -1,333 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../git/worktrees/catalog/worktree-listing' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { listWorktreeGraphMock, listWorktreesMock, listWorktreesStrictMock } = vi.hoisted(() => ({ - listWorktreeGraphMock: vi.fn(), - listWorktreesMock: vi.fn(), - listWorktreesStrictMock: vi.fn() -})) - -vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const facade = await getWorktreeOwnerMocks() - return { - ...(await importOriginal()), - listWorktrees: facade.listWorktrees, - listWorktreeGraph: facade.listWorktreeGraph, - listWorktreesSharedStrictAllowingTrueEmpty: facade.listWorktreesSharedStrictAllowingTrueEmpty - } -}) - -vi.mock('../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const facade = await getWorktreeOwnerMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: facade.listWorktreesStrict - } -}) - -const { getWorktreeOwnerMocks } = vi.hoisted(() => { - function createWorktreeOwnerMocks() { - return (() => ({ - listWorktreeGraph: listWorktreeGraphMock, - listWorktrees: listWorktreesMock, - listWorktreesStrict: listWorktreesStrictMock, - listWorktreesSharedStrictAllowingTrueEmpty: listWorktreesStrictMock - }))() - } - let fixture: ReturnType | undefined - return { getWorktreeOwnerMocks: () => (fixture ??= createWorktreeOwnerMocks()) } -}) - -import { - createFolderWorktree, - isRepoRoot, - listLocalRepoWorktreesStrict, - listRepoWorktreeGraph, - listRepoWorktrees, - listRepoWorktreesForDetectedScan -} from './repo-worktrees' -import { WorktreeCatalogUnavailableError } from '../../../shared/worktree/worktree-catalog-availability' - -describe('repo-worktrees', () => { - beforeEach(() => { - listWorktreeGraphMock.mockReset() - listWorktreesMock.mockReset() - listWorktreesStrictMock.mockReset() - }) - - it('creates a stable synthetic worktree for folder repos', () => { - expect( - createFolderWorktree({ - id: 'repo-1', - path: '/workspace/folder', - displayName: 'folder', - badgeColor: '#000', - addedAt: 0, - kind: 'folder' - }) - ).toEqual({ - path: '/workspace/folder', - head: '', - branch: '', - isBare: false, - isMainWorktree: true - }) - }) - - it('returns the synthetic folder worktree instead of shelling out to git', async () => { - const result = await listRepoWorktrees({ - id: 'repo-1', - path: '/workspace/folder', - displayName: 'folder', - badgeColor: '#000', - addedAt: 0, - kind: 'folder' - }) - - expect(result).toEqual([ - { - path: '/workspace/folder', - head: '', - branch: '', - isBare: false, - isMainWorktree: true - } - ]) - expect(listWorktreesMock).not.toHaveBeenCalled() - }) - - it('returns the synthetic folder worktree for strict local listing', async () => { - const result = await listLocalRepoWorktreesStrict({ - id: 'repo-1', - path: '/workspace/folder', - displayName: 'folder', - badgeColor: '#000', - addedAt: 0, - kind: 'folder' - }) - - expect(result).toEqual([ - createFolderWorktree({ - id: 'repo-1', - path: '/workspace/folder', - displayName: 'folder', - badgeColor: '#000', - addedAt: 0, - kind: 'folder' - }) - ]) - expect(listWorktreesStrictMock).not.toHaveBeenCalled() - }) - - it('delegates to git worktree listing for git repos', async () => { - listWorktreesMock.mockResolvedValue([ - { path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true } - ]) - const signal = new AbortController().signal - - const result = await listRepoWorktrees( - { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - kind: 'git' - }, - { signal } - ) - - expect(listWorktreesMock).toHaveBeenCalledWith('/workspace/repo', { signal }) - expect(result).toHaveLength(1) - }) - - it('delegates to the graph listing without sparse annotation', async () => { - listWorktreeGraphMock.mockResolvedValue([ - { path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true } - ]) - - const result = await listRepoWorktreeGraph({ - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - kind: 'git' - }) - - expect(listWorktreeGraphMock).toHaveBeenCalledWith('/workspace/repo') - expect(listWorktreesMock).not.toHaveBeenCalled() - expect(result).toHaveLength(1) - }) - - it('returns the synthetic folder worktree from the graph listing', async () => { - const result = await listRepoWorktreeGraph({ - id: 'repo-1', - path: '/workspace/folder', - displayName: 'folder', - badgeColor: '#000', - addedAt: 0, - kind: 'folder' - }) - - expect(listWorktreeGraphMock).not.toHaveBeenCalled() - expect(result).toEqual([ - createFolderWorktree({ - id: 'repo-1', - path: '/workspace/folder', - displayName: 'folder', - badgeColor: '#000', - addedAt: 0, - kind: 'folder' - }) - ]) - }) - - it('delegates strict local listing with the signal and WSL options', async () => { - listWorktreesStrictMock.mockResolvedValue([ - { path: '/workspace/repo', head: 'abc', branch: '', isBare: false, isMainWorktree: true } - ]) - const signal = new AbortController().signal - - const result = await listLocalRepoWorktreesStrict( - { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - kind: 'git' - }, - { signal, wslDistro: 'Ubuntu' } - ) - - expect(listWorktreesStrictMock).toHaveBeenCalledWith('/workspace/repo', { - signal, - wslDistro: 'Ubuntu' - }) - expect(result).toHaveLength(1) - }) - - it('rejects strict listing for remote repos', async () => { - await expect( - listLocalRepoWorktreesStrict({ - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - connectionId: 'ssh-1', - kind: 'git' - }) - ).rejects.toThrow('remote repository') - expect(listWorktreesStrictMock).not.toHaveBeenCalled() - }) - - describe('rows that spell their owner only as executionHostId', () => { - const sshOnlyRepo = { - id: 'repo-1', - path: '/srv/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - kind: 'git' as const, - executionHostId: 'ssh:host-a' as const - } - - it('never lists an ssh-owned row with local git', async () => { - await expect(listRepoWorktrees(sshOnlyRepo)).rejects.toThrow(WorktreeCatalogUnavailableError) - expect(listWorktreesMock).not.toHaveBeenCalled() - }) - - it('keeps an ssh-owned root out of the local repo-root match', () => { - expect(isRepoRoot([sshOnlyRepo], '/srv/repo')).toBe(false) - }) - - it('rejects strict local listing for an ssh-owned row', async () => { - await expect(listLocalRepoWorktreesStrict(sshOnlyRepo)).rejects.toThrow('remote repository') - expect(listWorktreesStrictMock).not.toHaveBeenCalled() - }) - - it('refuses to answer a runtime-owned row from a same-named local target', async () => { - await expect( - listRepoWorktrees({ - ...sshOnlyRepo, - executionHostId: 'runtime:env-7', - connectionId: 'nested-target' - }) - ).rejects.toThrow(WorktreeCatalogUnavailableError) - expect(listWorktreesMock).not.toHaveBeenCalled() - }) - - it('reports an unserved ssh host as unavailable from the graph listing, never as empty', async () => { - await expect(listRepoWorktreeGraph(sshOnlyRepo)).rejects.toThrow( - 'SSH connection "host-a" is not connected' - ) - await expect(listRepoWorktreeGraph(sshOnlyRepo)).rejects.toBeInstanceOf( - WorktreeCatalogUnavailableError - ) - expect(listWorktreeGraphMock).not.toHaveBeenCalled() - }) - - it('reports a runtime-owned row as unavailable from the graph listing, never as empty', async () => { - await expect( - listRepoWorktreeGraph({ - ...sshOnlyRepo, - executionHostId: 'runtime:env-7', - connectionId: 'nested-target' - }) - ).rejects.toThrow('host runtime:env-7 is not reachable from this process') - expect(listWorktreeGraphMock).not.toHaveBeenCalled() - }) - }) - - it('treats Windows repo root casing differences as the same local root', () => { - const repos = [ - { - id: 'repo-1', - path: String.raw`C:\Repo`, - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - kind: 'git' as const - } - ] - - expect(isRepoRoot(repos, String.raw`c:\repo`)).toBe(true) - }) -}) - -it('keeps an upgraded linked folder locator in every local listing, including restart hydration', async () => { - const repo = { - id: 'folder', - path: 'C:\\projects\\draft', - displayName: 'draft', - badgeColor: 'blue', - addedAt: 0, - kind: 'git' as const, - folderUpgradeGitRootPath: 'C:/projects/draft' - } - const raw = [ - { path: 'C:/projects/main', head: 'abc', branch: 'main', isBare: false, isMainWorktree: true }, - { - path: 'C:/projects/draft', - head: 'def', - branch: 'draft', - isBare: false, - isMainWorktree: false - } - ] - listWorktreesMock.mockResolvedValue(raw) - listWorktreeGraphMock.mockResolvedValue(raw) - listWorktreesStrictMock.mockResolvedValue(raw) - for (const list of [ - listRepoWorktrees, - listRepoWorktreesForDetectedScan, - listRepoWorktreeGraph, - listLocalRepoWorktreesStrict - ]) { - expect(await list(repo)).toEqual([raw[0], { ...raw[1], path: repo.path }]) - } - expect(raw[1].path).toBe('C:/projects/draft') -}) diff --git a/src/main/workspaces/execution-host/project-runtime-git-options.test.ts b/src/main/workspaces/execution-host/project-runtime-git-options.test.ts deleted file mode 100644 index 23a18a7c113..00000000000 --- a/src/main/workspaces/execution-host/project-runtime-git-options.test.ts +++ /dev/null @@ -1,276 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../../persistence/loading-store/store' -import type { Project } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' -import { - getLocalProjectGitExecOptions, - getWorktreeCreatePrefetchGitOptions, - getWorktreeMirrorDistro -} from './project-runtime-git-options' -import { resolveLocalProjectRuntimeForRepo } from './local-project-runtime-resolution' -import { _resetWslCachesForTests, _setWslCachesForTests } from '../../wsl/discovery/distro-catalog' - -function withPlatform(platform: NodeJS.Platform, run: () => T): T { - const originalPlatform = process.platform - Object.defineProperty(process, 'platform', { - configurable: true, - value: platform - }) - try { - return run() - } finally { - Object.defineProperty(process, 'platform', { - configurable: true, - value: originalPlatform - }) - } -} - -function makeRepo(overrides: Partial = {}): Repo { - return { - id: 'repo-1', - displayName: 'Repo', - path: String.raw`C:\repo`, - badgeColor: '#000000', - addedAt: 0, - ...overrides - } -} - -function makeProject(overrides: Partial = {}): Project { - return { - id: 'project-1', - displayName: 'Project', - badgeColor: '#000000', - sourceRepoIds: ['repo-1'], - createdAt: 0, - updatedAt: 0, - ...overrides - } -} - -function makeStore( - project: Project, - localWindowsRuntimeDefault: unknown = { kind: 'windows-host' } -): Store { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: runtime resolution reads only getProjects and getSettings. - return { - getProjects: () => [project], - getSettings: () => ({ localWindowsRuntimeDefault }) - } as unknown as Store -} - -describe('project runtime git options', () => { - afterEach(() => { - _resetWslCachesForTests() - }) - - it('does not probe or repair WSL git routing before capability caches exist', () => { - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - const options = withPlatform('win32', () => - getLocalProjectGitExecOptions(makeStore(project), makeRepo()) - ) - - expect(options).toEqual({ cwd: String.raw`C:\repo`, wslDistro: 'Ubuntu' }) - }) - - it('keeps WSL Git for a drive project that inherits WSL and never chose Windows Git', () => { - const store = makeStore(makeProject(), { kind: 'wsl', distro: 'Ubuntu' }) - - const options = withPlatform('win32', () => getLocalProjectGitExecOptions(store, makeRepo())) - - expect(options).toEqual({ cwd: String.raw`C:\repo`, wslDistro: 'Ubuntu' }) - }) - - it('runs Windows Git for a WSL project converted to Windows Git', () => { - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' } - }) - - const options = withPlatform('win32', () => - getLocalProjectGitExecOptions(makeStore(project), makeRepo()) - ) - - expect(options).toEqual({ cwd: String.raw`C:\repo` }) - }) - - it('returns repair state for missing cached WSL distro before local git execution', () => { - _setWslCachesForTests({ available: true, distros: ['Debian'] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - const runtime = withPlatform('win32', () => - resolveLocalProjectRuntimeForRepo(makeStore(project), makeRepo()) - ) - - expect(runtime).toEqual({ - status: 'repair-required', - repair: { - projectId: 'project-1', - preferredRuntime: { kind: 'wsl', distro: 'Ubuntu' }, - reason: 'wsl-distro-missing', - source: 'project-override', - cacheKey: 'project-1:repair:wsl-distro-missing:Ubuntu' - } - }) - expect(() => - withPlatform('win32', () => getLocalProjectGitExecOptions(makeStore(project), makeRepo())) - ).toThrow('Project runtime requires repair before git execution: wsl-distro-missing') - }) - - it('returns repair state for cached WSL unavailable before local git execution', () => { - _setWslCachesForTests({ available: false, distros: [] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - expect(() => - withPlatform('win32', () => getLocalProjectGitExecOptions(makeStore(project), makeRepo())) - ).toThrow('Project runtime requires repair before git execution: wsl-unavailable') - }) - - it('keeps project host override on host even when cached WSL is unavailable', () => { - _setWslCachesForTests({ available: false, distros: [] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'windows-host' } - }) - - const options = withPlatform('win32', () => - getLocalProjectGitExecOptions(makeStore(project), makeRepo()) - ) - - expect(options).toEqual({ cwd: String.raw`C:\repo` }) - }) - - it('does not apply local Windows runtime routing to SSH-owned repos', () => { - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - const runtime = withPlatform('win32', () => - resolveLocalProjectRuntimeForRepo( - makeStore(project), - makeRepo({ connectionId: null, executionHostId: 'ssh:target-1' }) - ) - ) - - expect(runtime).toBeUndefined() - }) - - describe('getWorktreeMirrorDistro', () => { - it('names the distro a resolved WSL project runs in', () => { - _setWslCachesForTests({ available: true, distros: ['Ubuntu'] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - expect( - withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo())) - ).toBe('Ubuntu') - }) - - it('names no distro for a project converted to Windows Git', () => { - _setWslCachesForTests({ available: true, distros: ['Ubuntu'] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' } - }) - - expect( - withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo())) - ).toBeUndefined() - }) - - it('names no distro for a host-runtime project', () => { - const project = makeProject({ localWindowsRuntimePreference: { kind: 'windows-host' } }) - - expect( - withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo())) - ).toBeUndefined() - }) - - // Worktree placement permits Windows fallback even when Git execution would require runtime repair. - it('names no distro instead of throwing when the runtime needs repair', () => { - _setWslCachesForTests({ available: true, distros: ['Debian'] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - expect( - withPlatform('win32', () => getWorktreeMirrorDistro(makeStore(project), makeRepo())) - ).toBeUndefined() - }) - - it('names no distro when the store cannot resolve projects', () => { - _setWslCachesForTests({ available: true, distros: ['Ubuntu'] }) - - expect(withPlatform('win32', () => getWorktreeMirrorDistro({}, makeRepo()))).toBeUndefined() - }) - }) - - describe('getWorktreeCreatePrefetchGitOptions', () => { - it('routes the warm-up through the distro a resolved WSL project runs in', () => { - _setWslCachesForTests({ available: true, distros: ['Ubuntu'] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - expect( - withPlatform('win32', () => - getWorktreeCreatePrefetchGitOptions(makeStore(project), makeRepo()) - ) - ).toEqual({ wslDistro: 'Ubuntu' }) - }) - - // Speculative warmup must fall back to host Git instead of exposing a repair error. - it('falls back to host git instead of throwing when the runtime needs repair', () => { - _setWslCachesForTests({ available: true, distros: ['Debian'] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - expect( - withPlatform('win32', () => - getWorktreeCreatePrefetchGitOptions(makeStore(project), makeRepo()) - ) - ).toEqual({}) - }) - - it('does not resolve a project runtime for folder workspaces', () => { - _setWslCachesForTests({ available: true, distros: ['Ubuntu'] }) - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - const store = makeStore(project) - const getProjects = vi.fn(store.getProjects) - - expect( - withPlatform('win32', () => - getWorktreeCreatePrefetchGitOptions( - { ...store, getProjects } as unknown as Store, - makeRepo({ kind: 'folder' }) - ) - ) - ).toEqual({}) - expect(getProjects).not.toHaveBeenCalled() - }) - }) - - it('does not apply local Windows runtime routing to runtime-owned repos', () => { - const project = makeProject({ - localWindowsRuntimePreference: { kind: 'wsl', distro: 'Ubuntu' } - }) - - const runtime = withPlatform('win32', () => - resolveLocalProjectRuntimeForRepo( - makeStore(project), - makeRepo({ connectionId: null, executionHostId: 'runtime:env-1' }) - ) - ) - - expect(runtime).toBeUndefined() - }) -}) diff --git a/src/main/wsl/discovery/wsl-distro-holder-script.test.ts b/src/main/wsl/discovery/wsl-distro-holder-script.test.ts index 4838a84cba0..94baf0dc490 100644 --- a/src/main/wsl/discovery/wsl-distro-holder-script.test.ts +++ b/src/main/wsl/discovery/wsl-distro-holder-script.test.ts @@ -15,12 +15,7 @@ import { ORCAD_WSL_HOLDER_BLOCKED_FILENAME, ORCAD_WSL_HOLDER_RELEASE_FILENAME } from '../../../shared/orcad-idle-exit' -import { - buildWslDistroHolderScript, - WSL_DISTRO_HOLDER_BLOCKED_NAMES_MAX, - WSL_DISTRO_HOLDER_IGNORED_PROCESS_NAMES, - WSL_DISTRO_HOLDER_MARKER -} from './wsl-distro-holder-command' +import { buildWslDistroHolderScript, WSL_DISTRO_HOLDER_MARKER } from './wsl-distro-holder-command' // The script runs inside the distro; any POSIX sh here exercises the same text. A fake /proc stands // in for the distro's, so the test runner's own processes never count as the user's work. @@ -127,13 +122,6 @@ async function holderWithRequest(options: { procReadable?: boolean; path?: strin } describe.skipIf(process.platform === 'win32')('WSL distro holder script', () => { - it('drops a request left from before it started: a client wants the distro now', async () => { - writeFileSync(releasePath(), '999999\n') - const { exited } = startHolder() - expect(await within(2_500, exited)).toBe('running') - expect(existsSync(releasePath())).toBe(false) - }) - it('waits for the requesting orcad to exit, then claims the request and ends', async () => { const holder = await startHolderReady() const orcad = track(spawn('/bin/sh', ['-c', 'sleep 30'], { stdio: 'ignore' })) @@ -175,43 +163,6 @@ describe.skipIf(process.platform === 'win32')('WSL distro holder script', () => expect(await within(RELEASE_BOUND_MS, exited)).toBe(0) }) - it('does not count session plumbing, zombies, other users or its own children', async () => { - let pid = 5000 - for (const name of WSL_DISTRO_HOLDER_IGNORED_PROCESS_NAMES) { - fakeProcess(pid++, { name }) - } - fakeProcess(pid++, { state: 'Z (zombie)' }) - fakeProcess(pid++, { uid: me + 1 }) - const holder = await startHolderReady() - fakeProcess(pid++, { name: 'sleep', ppid: holder.child.pid }) - const orcad = track(spawn('/bin/sh', ['-c', 'exit 0'], { stdio: 'ignore' })) - await new Promise((resolve) => orcad.once('exit', resolve)) - writeFileSync(releasePath(), `${orcad.pid}\n`) - expect(await within(RELEASE_BOUND_MS, holder.exited)).toBe(0) - }) - - it('notes what keeps it holding, and clears the note once it releases', async () => { - const job = fakeProcess(4242, { name: 'node' }) - const { exited } = await holderWithRequest() - await expect.poll(() => existsSync(blockedPath()), { timeout: 5_000 }).toBe(true) - expect(readFileSync(blockedPath(), 'utf8')).toBe('node\n') - rmSync(job, { recursive: true }) - expect(await within(RELEASE_BOUND_MS, exited)).toBe(0) - expect(existsSync(blockedPath())).toBe(false) - }) - - it('keeps the note bounded however much the user runs', async () => { - for (let pid = 6000; pid < 6000 + 3 * WSL_DISTRO_HOLDER_BLOCKED_NAMES_MAX; pid++) { - fakeProcess(pid, { name: `job${pid}` }) - } - const { exited } = await holderWithRequest() - await expect.poll(() => existsSync(blockedPath()), { timeout: 5_000 }).toBe(true) - expect(readFileSync(blockedPath(), 'utf8').trim().split(' ')).toHaveLength( - WSL_DISTRO_HOLDER_BLOCKED_NAMES_MAX - ) - expect(await within(1_500, exited)).toBe('running') - }) - it('fails closed when /proc cannot be read', async () => { const { exited } = await holderWithRequest({ procReadable: false }) expect(await within(2_500, exited)).toBe('running') diff --git a/src/main/wsl/orcad/wsl-orcad-failed-install-removal.test.ts b/src/main/wsl/orcad/wsl-orcad-failed-install-removal.test.ts deleted file mode 100644 index 07a9169bb3d..00000000000 --- a/src/main/wsl/orcad/wsl-orcad-failed-install-removal.test.ts +++ /dev/null @@ -1,270 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as VersionGc from '../../managed-server/lifecycle/orcad-managed-version-gc' -import type * as RemoteVersionedInstall from '../../managed-server/install/remote-versioned-install' - -const mocks = vi.hoisted(() => ({ - installed: new Set(), - record: vi.fn(), - readiness: vi.fn(), - pins: vi.fn(), - inUse: vi.fn(async () => false), - remove: vi.fn(), - fenceHeld: false -})) - -vi.mock('../../managed-server/activation/orcad-activation-record-store', () => ({ - readOrcadActivationRecord: mocks.record -})) -vi.mock('../../managed-server/lifecycle/orcad-managed-version-gc', async (importOriginal) => ({ - ...(await importOriginal()), - probeOrcadSlotReadiness: mocks.readiness -})) -vi.mock('../../ssh/orcad-gc-transaction-pins', () => ({ readOrcadGcTransactionPins: mocks.pins })) -vi.mock('./wsl-orcad-slot-process-probe', () => ({ isWslOrcadSlotInUse: mocks.inUse })) -// One activation fence per host: a second taker is told it is held, as the real lock does after its wait. -vi.mock('../../managed-server/activation/orcad-activation-lock', () => ({ - withOrcadActivationLock: async (_slot: unknown, run: () => Promise, held: () => T) => { - if (mocks.fenceHeld) { - return held() - } - mocks.fenceHeld = true - try { - return await run() - } finally { - mocks.fenceHeld = false - } - } -})) -vi.mock('../../managed-server/install/remote-install-gc', () => ({ - removeRemoteInstallVersionDir: mocks.remove -})) -// The install itself runs for real against a host whose only state is which slots are complete. -vi.mock('../../managed-server/install/remote-versioned-install', async (importOriginal) => ({ - ...(await importOriginal()), - isRemoteInstallComplete: async (_conn: unknown, _model: unknown, dir: string) => - mocks.installed.has(dir), - finalizeInstall: async (_conn: unknown, dir: string) => void mocks.installed.add(dir), - abandonInstall: async () => true -})) -vi.mock('../../managed-server/install/remote-install-lock', () => ({ - acquireInstallLock: vi.fn(async () => {}) -})) -vi.mock('../../managed-server/install/remote-install-transfers', () => ({ - uploadRemoteInstallDirectory: vi.fn(async () => {}), - writeRemoteInstallFile: vi.fn(async () => {}) -})) -vi.mock('../../managed-server/install/orcad-remote-node-runtime', () => ({ - ensureRemoteOrcadNodeRuntime: vi.fn(async () => {}) -})) -vi.mock('../../ssh/remote-exec/remote-exec-command', () => ({ - execCommand: vi.fn(async () => ''), - isUnconfirmedSshCommandTermination: () => false -})) - -import { removeFailedFreshWslOrcadInstall } from './wsl-orcad-failed-install-removal' -import { withOrcadActivationLock } from '../../managed-server/activation/orcad-activation-lock' -import { installOrcadBundle } from '../../managed-server/install/orcad-remote-install' -import { uploadRemoteInstallDirectory } from '../../managed-server/install/remote-install-transfers' -import { - emptyOrcadActivationRecord, - withActivatedVersion -} from '../../managed-server/activation/orcad-activation-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import type { OrcadDeployResult } from '../../ssh/orcad-remote-deploy' - -const NEW = '1.6.0+bb01' -const OLD = '1.5.0+aa01' -const NEW_DIR = `/home/u/.orca-remote/orcad-${NEW}` -const host = getRemoteHostPlatform('linux-x64') -const slot = { - conn: Object.create(null), - host, - remoteHome: '/home/u', - nodePath: '/usr/bin/node', - userDataDir: '/home/u/.orca', - bindHost: '127.0.0.1', - port: 6768 -} -const failedFresh: OrcadDeployResult = { - outcome: 'installed-not-activated', - fullVersion: NEW, - code: 'orcad_activation_daemon_degraded', - reason: 'the candidate failed its readiness check', - startCheckFailed: true, - freshlyInstalled: true -} - -function install(): Promise<'uploaded' | 'reused'> { - return installOrcadBundle( - { - ...slot, - localOrcadDir: '/local/orcad', - target: 'linux-x64-glibc', - nodeRuntimeArchive: async () => '/cache/node.tar.gz' - }, - NEW, - NEW_DIR - ) -} - -function daemon(state: 'live' | 'absent' | 'degraded', buildVersion = OLD) { - return { health: { terminalDaemon: { state, buildVersion } } } -} - -describe('removeFailedFreshWslOrcadInstall', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.installed.clear() - mocks.fenceHeld = false - mocks.record.mockResolvedValue( - withActivatedVersion(emptyOrcadActivationRecord(), OLD, null, new Date(0)) - ) - mocks.readiness.mockResolvedValue(daemon('live')) - mocks.pins.mockResolvedValue({ state: 'pinned', dirNames: [] }) - mocks.remove.mockImplementation(async (_conn: unknown, _model: unknown, dir: string) => - mocks.installed.delete(dir) - ) - }) - - it('removes a slot this connect uploaded once its candidate fails, so the retry uploads again', async () => { - expect(await install()).toBe('uploaded') - - await removeFailedFreshWslOrcadInstall(slot, failedFresh) - - expect(mocks.remove).toHaveBeenCalledWith(slot.conn, expect.anything(), NEW_DIR, host, { - isDirLive: expect.any(Function) - }) - expect(mocks.installed.has(NEW_DIR)).toBe(false) - expect(await install()).toBe('uploaded') - expect(uploadRemoteInstallDirectory).toHaveBeenCalledTimes(2) - }) - - it('checks and deletes under the activation fence, so a concurrent activator waits and re-uploads', async () => { - await install() - let resume = (): void => {} - mocks.record.mockImplementationOnce(async () => { - await new Promise((resolve) => { - resume = resolve - }) - return emptyOrcadActivationRecord() - }) - const removal = removeFailedFreshWslOrcadInstall(slot, failedFresh) - await vi.waitFor(() => expect(mocks.record).toHaveBeenCalled()) - - // Another connect reaching activation between the check and the delete finds the fence held. - const activator = await withOrcadActivationLock( - slot, - async () => 'launched', - () => 'held' - ) - expect(activator).toBe('held') - resume() - await removal - - expect(mocks.pins).toHaveBeenCalledWith(slot, { callerHoldsFence: true }) - expect(mocks.installed.has(NEW_DIR)).toBe(false) - expect(await install()).toBe('uploaded') - }) - - it('keeps the copy when another activator already holds the fence', async () => { - await install() - mocks.fenceHeld = true - - await removeFailedFreshWslOrcadInstall(slot, failedFresh) - - expect(mocks.record).not.toHaveBeenCalled() - expect(mocks.remove).not.toHaveBeenCalled() - expect(await install()).toBe('reused') - }) - - it('asks the slot process probe, which also sees a daemon the candidate left there', async () => { - await removeFailedFreshWslOrcadInstall(slot, failedFresh) - const [, , , , { isDirLive }] = mocks.remove.mock.calls[0] - mocks.inUse.mockResolvedValueOnce(true) - - await expect(isDirLive(NEW_DIR)).resolves.toBe(true) - expect(mocks.inUse).toHaveBeenCalledWith(slot, NEW_DIR) - }) - - it('also removes a failed first install, where nothing is active', async () => { - mocks.record.mockResolvedValue(emptyOrcadActivationRecord()) - await install() - - await removeFailedFreshWslOrcadInstall(slot, failedFresh) - - expect(mocks.readiness).not.toHaveBeenCalled() - expect(mocks.installed.has(NEW_DIR)).toBe(false) - }) - - it('never touches a slot that was already installed before this connect', async () => { - mocks.installed.add(NEW_DIR) - expect(await install()).toBe('reused') - - await removeFailedFreshWslOrcadInstall(slot, { ...failedFresh, freshlyInstalled: undefined }) - - expect(mocks.record).not.toHaveBeenCalled() - expect(mocks.remove).not.toHaveBeenCalled() - expect(await install()).toBe('reused') - }) - - it('keeps a deferred update staged for later', async () => { - await removeFailedFreshWslOrcadInstall(slot, { ...failedFresh, startCheckFailed: undefined }) - await removeFailedFreshWslOrcadInstall(slot, { outcome: 'already-active', fullVersion: NEW }) - - expect(mocks.remove).not.toHaveBeenCalled() - }) - - it.each([ - [ - 'is the active version', - withActivatedVersion(emptyOrcadActivationRecord(), NEW, null, new Date(0)) - ], - [ - 'is the rollback target', - withActivatedVersion( - withActivatedVersion(emptyOrcadActivationRecord(), NEW, null, new Date(0)), - OLD, - null, - new Date(1) - ) - ] - ])('never removes a slot that %s', async (_label, record) => { - mocks.record.mockResolvedValue(record) - - await removeFailedFreshWslOrcadInstall(slot, failedFresh) - - expect(mocks.remove).not.toHaveBeenCalled() - }) - - it.each([ - ['runs a live terminal daemon from it', daemon('live', NEW)], - ['cannot name its terminal daemon build', daemon('degraded')] - ])('keeps the slot while the serving version %s', async (_label, readiness) => { - mocks.readiness.mockResolvedValue(readiness) - - await removeFailedFreshWslOrcadInstall(slot, failedFresh) - - expect(mocks.remove).not.toHaveBeenCalled() - }) - - it.each([ - ['a held fence or unreadable journal', { state: 'keep-all' }], - ['a journaled activation', { state: 'pinned', dirNames: [`orcad-${NEW}`] }] - ])('keeps the slot that %s may still need', async (_label, pins) => { - mocks.pins.mockResolvedValue(pins) - - await removeFailedFreshWslOrcadInstall(slot, failedFresh) - - expect(mocks.remove).not.toHaveBeenCalled() - }) - - it('leaves the failed connect to report its own reason when cleanup fails', async () => { - mocks.readiness.mockRejectedValue(new Error('probe timed out')) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - await expect(removeFailedFreshWslOrcadInstall(slot, failedFresh)).resolves.toBeUndefined() - - expect(mocks.remove).not.toHaveBeenCalled() - warn.mockRestore() - }) -}) diff --git a/src/renderer/src/components/native-chat/composer/controls/use-native-chat-steer-chord-preview.test.tsx b/src/renderer/src/components/native-chat/composer/controls/use-native-chat-steer-chord-preview.test.tsx deleted file mode 100644 index 7496e908796..00000000000 --- a/src/renderer/src/components/native-chat/composer/controls/use-native-chat-steer-chord-preview.test.tsx +++ /dev/null @@ -1,104 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, fireEvent, render } from '@testing-library/react' -import { useRef } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import type { NativeChatFollowUpBehavior } from '../../../../../../shared/native-chat/input/native-chat-follow-up-behavior' -import { NATIVE_CHAT_STEER_CHORD_HOLD_MS } from '../../../../../../shared/native-chat/input/use-native-chat-steer-chord-preview' -import { useNativeChatSteerChordPreview } from './use-native-chat-steer-chord-preview' - -vi.mock('../../pane/routing/native-chat-shortcut', () => ({ isMacPlatform: () => true })) - -type Props = { - alternateSend: NativeChatFollowUpBehavior | undefined - hasDraft: boolean - chordSteersHead: boolean - steerHead: (() => boolean) | undefined - send: () => void - pickerOpen: boolean -} - -function Composer(props: Props): React.JSX.Element { - const root = useRef(null) - const { alternateSend, hasDraft, chordSteersHead, steerHead, send, pickerOpen } = props - const { preview, runPreview } = useNativeChatSteerChordPreview( - root, - { alternateSend, hasDraft, chordSteersHead }, - steerHead, - send, - pickerOpen - ) - return ( -
-