From 7fec805e8940208ffd53e06c9bb6002c11da40e3 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 7 Nov 2026 18:24:44 -0800 Subject: [PATCH] test: remove 559 low-value tests (#39661) * test: remove 247 low-value tests * test: remove 559 low-value tests --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/flaky-test-pattern-baseline.txt | 5 - config/reliability-gates.jsonc | 151 +++++---- .../scripts/ci/sharding/ci-shard-timings.json | 62 ---- .../pr-refresh-coordinator-watch.test.ts | 159 ---------- .../pr-watch/pr-chat-action-recorder.test.ts | 71 ----- .../pr-watch/pr-head-evaluation.test.ts | 11 +- .../github/pr-watch/pr-watch-service.test.ts | 33 +- .../headless-snapshots-part-02.spec.ts | 219 +------------ ...le-session-tabs-cold-serve-hydrate.spec.ts | 229 -------------- ...session-tabs-headless-chat-rebuild.spec.ts | 239 -------------- .../mobile-session-tabs-part-14.spec.ts | 228 ------------- ...terminal-side-effect-facts-part-03.spec.ts | 163 +--------- .../terminal-spawn-dispatch.spec.ts | 299 ------------------ .../worktree-removal-execution-host.spec.ts | 268 ---------------- .../worktree-removal-failed-retry.spec.ts | 132 +------- src/main/runtime/orca-runtime.test.ts | 5 - ...worker-release-authority-contracts.test.ts | 2 - .../worker-release-ownership-guard.spec.ts | 207 ------------ ...worktree-teardown-daemon-inventory.test.ts | 181 ----------- .../worktree-terminal-sleep-host-twin.test.ts | 143 --------- ...me-local-worktree-terminal-startup.test.ts | 288 ----------------- ...ime-worktree-terminal-provisioning.test.ts | 234 -------------- .../wsl-host-agent-terminal-launch.test.ts | 161 +--------- src/main/skills/skill-bundle-creation.test.ts | 140 +------- .../skills/skill-package-identity.test.ts | 145 +-------- ...ed-review-creation-shared-symlinks.test.ts | 234 -------------- .../hosted-review-project-account.test.ts | 216 ------------- .../speech/stt-service-model-warmup.test.ts | 202 ------------ .../legacy-relay-bridge-connections.test.ts | 169 ---------- .../ssh-host-relay-endpoint-census.test.ts | 230 -------------- .../legacy-relay/ssh-relay-sentinel.test.ts | 182 +---------- ...d-migration-automation-run-history.test.ts | 25 +- .../ssh/orcad-retained-source-lists.test.ts | 230 -------------- .../remote-host-failure-producers.test.ts | 150 +-------- ...odex-launch-per-agent-hook-opt-out.test.ts | 212 ------------- .../login-shell-environment-cache.test.ts | 152 --------- .../startup/run-electron-vite-dev-web.test.ts | 245 -------------- .../pull-request-context-errors.test.ts | 269 ---------------- .../source-control-agent-launch.test.ts | 185 +---------- .../appimage-runtime-identity.test.ts | 153 +-------- .../updater.startup-scheduling.test.ts | 218 ------------- .../usage/usage-scan-worker-client.test.ts | 263 --------------- .../clipboard-macos-image-paste.test.ts | 90 +----- .../terminal-pane-move-request-relay.test.ts | 36 --- .../window/terminal-pane-reveal-relay.test.ts | 127 -------- ...reated-worktree-setup-trust-parity.test.ts | 147 +-------- .../catalog/worktree-lineage-pruning.test.ts | 226 ------------- .../worktree-name-retirement.test.ts | 218 ------------- .../worktree-retirement-discovery.test.ts | 225 ------------- ...orktree-background-removal-records.test.ts | 137 +------- .../worktree-removal-home-guard.test.ts | 226 ------------- .../wsl-background-distro-gate.test.ts | 177 +---------- .../wsl-background-exec-gate.test.ts | 117 +------ .../wsl/execution/wsl-interop-health.test.ts | 233 -------------- .../wsl-drive-project-windows-git.test.ts | 246 -------------- .../wsl-drive-unc-project-scope.test.ts | 212 ------------- .../wsl-sh-cwd-report.node-pty.test.ts | 85 +---- .../host-lifecycle/wsl-host-connector.test.ts | 198 ------------ .../wsl-hosts-policy-live-update.test.ts | 136 +------- .../wsl/orcad/wsl-orcad-account-env.test.ts | 215 ------------- .../wsl/orcad/wsl-orcad-held-context.test.ts | 186 +---------- .../wsl/orcad/wsl-orcad-incumbent.test.ts | 224 ------------- .../orcad/wsl-orcad-stdio-bridge-e9.test.ts | 87 +---- .../native-chat-selection-quote-draft.test.ts | 12 - .../native-chat-workspace-selection.test.ts | 78 ----- .../use-native-chat-history-retention.test.ts | 73 ----- ...nnection-ssh-hook-status-authority.spec.ts | 79 ----- .../startup/in-place-resume-hold.test.ts | 47 --- ...ection-completion-and-notification.test.ts | 2 - ...y-pre-handler-buffer-warn-eviction.test.ts | 61 ---- .../pty-renderer-delivery-claims.test.ts | 62 ---- .../ssh-session-gone-verdict.test.ts | 43 --- .../pty-preconnect-input-retention.test.ts | 26 -- .../pty-transport-agent-trust-hold.test.ts | 78 ----- .../ipc/pty-transport-spawn-intent.test.ts | 55 ---- ...-new-tab-disposed-spawn-kill.repro.test.ts | 48 --- .../output/terminal-output-visibility.test.ts | 47 --- .../remote-server-notice-claims.test.tsx | 73 ----- ...te-runtime-error-surface-dismissal.test.ts | 70 ---- ...ty-transport-host-absence-evidence.test.ts | 90 ------ .../pty-shutdown-output-queue.test.ts | 64 ---- .../merge-captured-leaf-state.test.ts | 60 ---- .../use-host-terminal-scrollback-hold.test.ts | 53 ---- .../remote-desktop-viewport-claim.test.ts | 60 ---- ...-running-work-probe-child-evidence.test.ts | 89 ------ .../use-terminal-browser-retention.test.tsx | 83 ----- ...alled-agent-skill-runtime-eviction.test.ts | 76 ----- ...-request-ipc-bridge.profile-switch.test.ts | 96 ------ ...acy-worker-terminal-recovery-event.test.ts | 97 ------ .../theme/use-system-prefers-dark.test.ts | 89 ------ .../use-window-stream-visibility.test.ts | 21 -- .../agent-hibernation-twin-host.test.ts | 98 ------ .../agent-hibernation-visibility.test.ts | 65 ---- ...ephemeral-vm-failed-create-cleanup.test.ts | 74 ----- .../markdown-textmate-tokens.test.ts | 70 ---- .../src/lib/pending-worktree-creation.test.ts | 107 ------- .../lib/settled-worker-wake-policy.test.ts | 54 ---- .../lib/typing-latency/input-events.test.ts | 90 ------ .../src/lib/worker-auto-close.test.ts | 65 ---- .../worktree-activation-leave-visit.test.ts | 68 ---- ...orktree-activation-shown-tab-focus.test.ts | 73 ----- ...ktree-host-connection-phase.recipe.test.ts | 63 ---- .../src/lib/wsl-host-availability.test.ts | 56 ---- .../runtime-file-client-watch.test.ts | 75 ----- ...inal-orphan-recovery-prior-removal.test.ts | 68 ---- ...abortable-runtime-environment-call.test.ts | 20 -- ...ow-visibility-subscription-parking.test.ts | 84 ----- ...bs-late-merged-predecessor-lockout.test.ts | 70 ---- .../checks/check-actions-errors.test.ts | 63 ---- .../github-pr-refresh-wsl-host-off.test.ts | 90 ------ .../nested-repository-operations.test.ts | 66 ---- ...se-presets-repo-removal-purge-leak.test.ts | 63 ---- .../worktree-listing-branch-switch.test.ts | 71 ----- .../foreign-host-status-guard.test.ts | 40 +-- .../legacy-relay-bridged-tab-close.test.ts | 84 ----- .../selection/workspace-host-target.test.ts | 55 ---- 116 files changed, 140 insertions(+), 13982 deletions(-) delete mode 100644 src/main/github/pr-refresh-coordinator-watch.test.ts delete mode 100644 src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts delete mode 100644 src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts delete mode 100644 src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts delete mode 100644 src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts delete mode 100644 src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts delete mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-release-ownership-guard.spec.ts delete mode 100644 src/main/runtime/workspaces/removal/worktree-teardown-daemon-inventory.test.ts delete mode 100644 src/main/runtime/workspaces/sleep/worktree-terminal-sleep-host-twin.test.ts delete mode 100644 src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.test.ts delete mode 100644 src/main/runtime/workspaces/startup/runtime-worktree-terminal-provisioning.test.ts delete mode 100644 src/main/source-control/hosted-review-creation-shared-symlinks.test.ts delete mode 100644 src/main/source-control/hosted-review-project-account.test.ts delete mode 100644 src/main/speech/stt-service-model-warmup.test.ts delete mode 100644 src/main/ssh/legacy-relay/legacy-relay-bridge-connections.test.ts delete mode 100644 src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.test.ts delete mode 100644 src/main/ssh/orcad-retained-source-lists.test.ts delete mode 100644 src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts delete mode 100644 src/main/startup/run-electron-vite-dev-web.test.ts delete mode 100644 src/main/text-generation/pull-request-context-errors.test.ts delete mode 100644 src/main/updater/updater.startup-scheduling.test.ts delete mode 100644 src/main/usage/usage-scan-worker-client.test.ts delete mode 100644 src/main/workspaces/catalog/worktree-lineage-pruning.test.ts delete mode 100644 src/main/workspaces/removal/retirement/worktree-name-retirement.test.ts delete mode 100644 src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts delete mode 100644 src/main/workspaces/removal/worktree-removal-home-guard.test.ts delete mode 100644 src/main/wsl/execution/wsl-interop-health.test.ts delete mode 100644 src/main/wsl/filesystem/wsl-drive-project-windows-git.test.ts delete mode 100644 src/main/wsl/filesystem/wsl-drive-unc-project-scope.test.ts delete mode 100644 src/main/wsl/host-lifecycle/wsl-host-connector.test.ts delete mode 100644 src/main/wsl/orcad/wsl-orcad-account-env.test.ts delete mode 100644 src/main/wsl/orcad/wsl-orcad-incumbent.test.ts delete mode 100644 src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.test.ts delete mode 100644 src/renderer/src/components/native-chat/viewport/history/use-native-chat-history-retention.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-pre-handler-buffer-warn-eviction.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-renderer-delivery-claims.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/host-ownership/ssh-session-gone-verdict.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/ipc/scan22-ssh-new-tab-disposed-spawn-kill.repro.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/output/terminal-output-visibility.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/recovery/server-outage/remote-server-notice-claims.test.tsx delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-error-surface-dismissal.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-absence-evidence.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/pty-transport/shutdown/pty-shutdown-output-queue.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/snapshots/merge-captured-leaf-state.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/snapshots/use-host-terminal-scrollback-hold.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/viewport/remote-desktop-viewport-claim.test.ts delete mode 100644 src/renderer/src/components/terminal/pty-running-work-probe-child-evidence.test.ts delete mode 100644 src/renderer/src/components/use-terminal-browser-retention.test.tsx delete mode 100644 src/renderer/src/hooks/installed-agent-skill-runtime-eviction.test.ts delete mode 100644 src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.profile-switch.test.ts delete mode 100644 src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts delete mode 100644 src/renderer/src/hooks/theme/use-system-prefers-dark.test.ts delete mode 100644 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-twin-host.test.ts delete mode 100644 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts delete mode 100644 src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts delete mode 100644 src/renderer/src/lib/monaco-languages/markdown-textmate-tokens.test.ts delete mode 100644 src/renderer/src/lib/pending-worktree-creation.test.ts delete mode 100644 src/renderer/src/lib/settled-worker-wake-policy.test.ts delete mode 100644 src/renderer/src/lib/typing-latency/input-events.test.ts delete mode 100644 src/renderer/src/lib/worker-auto-close.test.ts delete mode 100644 src/renderer/src/lib/workspace/activation/worktree-activation-leave-visit.test.ts delete mode 100644 src/renderer/src/lib/workspace/activation/worktree-activation-shown-tab-focus.test.ts delete mode 100644 src/renderer/src/lib/workspace/ownership/worktree-host-connection-phase.recipe.test.ts delete mode 100644 src/renderer/src/lib/wsl-host-availability.test.ts delete mode 100644 src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts delete mode 100644 src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-prior-removal.test.ts delete mode 100644 src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking.test.ts delete mode 100644 src/renderer/src/runtime/web-session-tabs-late-merged-predecessor-lockout.test.ts delete mode 100644 src/renderer/src/store/github/checks/check-actions-errors.test.ts delete mode 100644 src/renderer/src/store/github/repositories/github-pr-refresh-wsl-host-off.test.ts delete mode 100644 src/renderer/src/store/project-groups/nested-repository-operations.test.ts delete mode 100644 src/renderer/src/store/repos/sparse-presets-repo-removal-purge-leak.test.ts delete mode 100644 src/renderer/src/store/slices/worktrees/listing/worktree-listing-branch-switch.test.ts delete mode 100644 src/renderer/src/store/terminals/legacy-relay-bridged-tab-close.test.ts delete mode 100644 src/renderer/src/store/workspaces/selection/workspace-host-target.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 6af959f41e0..0306edb0a31 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -78,7 +78,6 @@ 1 test-no-polling-loop:src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts 1 test-no-polling-loop:src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts 2 test-no-polling-loop:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts -1 test-no-polling-loop:src/main/startup/run-electron-vite-dev-web.test.ts 1 test-no-polling-loop:src/main/startup/run-electron-vite-dev.test.ts 2 test-no-polling-loop:src/main/windows/windows-host-job.win32.test.ts 1 test-no-polling-loop:src/main/windows/windows-pty-job.win32.test.ts @@ -283,7 +282,6 @@ 2 test-no-real-time-wait:src/main/ssh/ssh-quit-abort-upload.test.ts 2 test-no-real-time-wait:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts 1 test-no-real-time-wait:src/main/startup/main-process-ready-duplicate-pty-repair.test.ts -3 test-no-real-time-wait:src/main/startup/run-electron-vite-dev-web.test.ts 3 test-no-real-time-wait:src/main/startup/run-electron-vite-dev.test.ts 2 test-no-real-time-wait:src/main/startup/windows-install-dir-acl-recovery.test.ts 1 test-no-real-time-wait:src/main/updater/lifecycle/serve-supervisor-install-park.test.ts @@ -317,7 +315,6 @@ 1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts 1 test-no-real-time-wait:src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts 2 test-no-real-time-wait:src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts -1 test-no-real-time-wait:src/renderer/src/store/terminals/legacy-relay-bridged-tab-close.test.ts 2 test-no-real-time-wait:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts 1 test-no-real-time-wait:src/shared/darwin-process-table-capture.test.ts 1 test-no-real-time-wait:src/shared/darwin-terminal-names-real-ps.test.ts @@ -686,7 +683,6 @@ 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 -2 test-no-wall-clock:src/main/startup/run-electron-vite-dev-web.test.ts 2 test-no-wall-clock:src/main/startup/run-electron-vite-dev.test.ts 13 test-no-wall-clock:src/main/startup/windows-install-dir-acl-recovery.test.ts 4 test-no-wall-clock:src/main/updater/lifecycle/serve-supervisor-install-park.test.ts @@ -731,7 +727,6 @@ 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts 2 test-no-wall-clock:src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts 1 test-no-wall-clock:src/renderer/src/lib/paired-runtime-closed-tab-resume.test.ts -2 test-no-wall-clock:src/renderer/src/lib/settled-worker-wake-policy.test.ts 2 test-no-wall-clock:src/renderer/src/lib/use-tab-agent-observed-signal-dispatch.test.tsx 2 test-no-wall-clock:src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts 1 test-no-wall-clock:src/renderer/src/lib/workspace-terminal-host-authority.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index ddef38e51c4..65179b77e49 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1696,22 +1696,21 @@ "surfaces": ["automatic agent hibernation", "remote terminal liveness"], "platforms": ["macos", "linux", "windows"], "providers": ["local", "remote-runtime"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": ["linux"], "coveredProviders": ["local", "remote-runtime"], - "coverageNotes": "Local hibernation, remote inventory authority and folder-workspace identity are covered by coordinator/model contracts on macOS. Daemon, SSH, WSL, relay and native platform execution boundaries and existing RPC payloads are unchanged. Current assertions cover shutdown safety and owning-host selection; historical inventory-count and performance evidence below is retained for provenance and is not current count coverage.", + "coverageNotes": "Audit2058 intentionally retires the standalone visibility subscription/callback-count alarm without replacement. The remaining five-source hibernation selector was freshly run on Linux:54 tests pass. Its prior macOS execution receipt/current-command association is archived verbatim in knownGaps and is not current execution evidence for the reduced selector. Current covered platform is Linux; remote replies remain scripted, with no live SSH/WSL/native provider or p95 claim. Historical prior account (preserved verbatim): Local hibernation, remote inventory authority and folder-workspace identity are covered by coordinator/model contracts on macOS. Daemon, SSH, WSL, relay and native platform execution boundaries and existing RPC payloads are unchanged. Current assertions cover shutdown safety and owning-host selection; historical inventory-count and performance evidence below is retained for provenance and is not current count coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/blob/main/src/renderer/src/lib/agent-hibernation-coordinator.test.ts" ], "invariant": "Automatic hibernation must retain two stable confirmations and fresh execution-host evidence before shutdown. Skipping a workspace with no completed agent must not authorize a newly completed pane using stale client PTYs.", - "oracle": "Working and waiting agents across remote workspaces must not be shut down. A skipped workspace completing while another inventory awaits remains ineligible until two later host-confirmed passes, and so does a workspace that only becomes runtime-owned while an inventory is outstanding — a pass carrying no host evidence for a workspace never counts as one of its two confirmations. Folder and git workspaces hibernate the exact host PTY; rejected/truncated inventories and intervening input/output or state changes block shutdown.", + "oracle": "Audit2058 intentionally retires the standalone visibility subscription/callback-count alarm without replacement. The remaining five-source hibernation selector was freshly run on Linux:54 tests pass. Its prior macOS execution receipt/current-command association is archived verbatim in knownGaps and is not current execution evidence for the reduced selector. Current covered platform is Linux; remote replies remain scripted, with no live SSH/WSL/native provider or p95 claim. Historical prior account (preserved verbatim): Working and waiting agents across remote workspaces must not be shut down. A skipped workspace completing while another inventory awaits remains ineligible until two later host-confirmed passes, and so does a workspace that only becomes runtime-owned while an inventory is outstanding — a pass carrying no host evidence for a workspace never counts as one of its two confirmations. Folder and git workspaces hibernate the exact host PTY; rejected/truncated inventories and intervening input/output or state changes block shutdown.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts" + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts --maxWorkers=2" ], "testFiles": [ "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts", "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts", "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts", - "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts", "src/renderer/src/lib/foreground-terminal-tabs.test.ts", "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts" ], @@ -1735,14 +1734,13 @@ ], "evidenceRuns": [ { - "date": "2026-09-07", + "date": "2026-11-08", "runner": "local", - "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-hibernation-confirmation.test.ts src/renderer/src/lib/agent-hibernation-pane-age.test.ts src/renderer/src/lib/agent-hibernation-output-activity.test.ts src/renderer/src/lib/agent-hibernation-visibility.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-hibernation-runtime-liveness-race.test.ts", - "currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts", + "platform": "linux", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts --maxWorkers=2", "result": "passed", - "durationSeconds": 48.18, - "summary": "93 tests passed across eight coordinator, liveness-race, planner, confirmation, age, activity and visibility files." + "durationSeconds": 7.377, + "summary": "54 tests across five unchanged coordinator/planner/age/foreground/liveness-race files passed on the actual39644 squash plus test-removal candidate. Reduced selector only; scripted runtime contracts, no live SSH/native WSL, soak or measured p95 claim." } ], "runtimeBudget": { @@ -1763,7 +1761,9 @@ }, "knownGaps": [ "Remote contracts use mocked runtime replies; no live SSH/network-fault, Windows/Linux/WSL or relay run.", - "This improves the experimental automatic hibernation path only; it does not remove inventories for workspaces that contain completed agents." + "This improves the experimental automatic hibernation path only; it does not remove inventories for workspaces that contain completed agents.", + "Audit2058 intentionally retires the standalone visibility subscription/callback-count alarm without replacement. The remaining five-source hibernation selector was freshly run on Linux:54 tests pass. Its prior macOS execution receipt/current-command association is archived verbatim in knownGaps and is not current execution evidence for the reduced selector. Current covered platform is Linux; remote replies remain scripted, with no live SSH/WSL/native provider or p95 claim.", + "Audit2058 archives this exact historical receipt after deleting a selector in its currentCommand; historical provenance only, not current execution evidence:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-hibernation-confirmation.test.ts src/renderer/src/lib/agent-hibernation-pane-age.test.ts src/renderer/src/lib/agent-hibernation-output-activity.test.ts src/renderer/src/lib/agent-hibernation-visibility.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-hibernation-runtime-liveness-race.test.ts\",\n \"currentCommand\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts src/renderer/src/lib/foreground-terminal-tabs.test.ts src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 48.18,\n \"summary\": \"93 tests passed across eight coordinator, liveness-race, planner, confirmation, age, activity and visibility files.\"\n }" ], "promotionCriteria": [ "Complete CI soak with zero unexplained flakes and preserve the observable oracle." @@ -2229,13 +2229,13 @@ "providers": ["local", "daemon", "wsl", "ssh", "remote-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": [], - "coverageNotes": "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": "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": "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": "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", @@ -2312,7 +2312,9 @@ "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. Existing exact primary-selector receipts remain unchanged.", "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. Existing exact primary-selector receipts remain unchanged.", "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.", - "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. Exact retired authored alarms: 'bounds a startup title storm to one extra read ladder and never adopts the title as identity'; 'leaves untrackable providers free of client process scans'; 'keeps a legacy remote process hint unverifiable after a startup title'; 'releases a retained capability when disposed mid-read'; 'releases a retained capability when an exit schedules no successor read'; 'releases a retained capability when an untrackable $exit ends the read'; 'does not release when the cancelled read has a successor'; 'settles the visible confirmation when the pty id is gone before the read runs'; 'reports a read in flight when a command-finished read owns the pane'; 'reads the foreground once after a command starts and publishes the recognized agent'; 'does not replace known foreground identity with typed command inference'; 'revokes stale routing immediately while a known pane confirms a new command'; 'reads the foreground for a visible PTY so restored running Codex panes regain identity'; 'does not retry or publish visible PTY reads for an idle shell foreground'; 'retries visible PTY reads only while a foreground wrapper may resolve to an agent'; 'stops after the ladder and publishes no identity for a persistent unknown process'; 'does not treat a nested shell seen mid-command as prompt proof'; 'recognizes an agent started from a nested shell on a ladder re-read'; 'marks shell foreground on command finished without any foreground read'; 'trusts a rapid ordinary command finish without forcing a fresh scan'; 'still marks shell without a read for a duplicate D pair on an idle pane'; 'marks shell on a rapid command start->finish when the foreground is a shell'; 'marks shell foreground when the confirming read shows the agent is gone'; 'confirms a command finished for a launch-known agent pane before any read'; 'accepts a fresh shell result for a launch-known Droid pane'; 'marks a confirmed shell without repeating a post-boundary scan'; 'never reads or publishes for remote or ssh panes'; 'does not let forged OSC 133/777 output assert remote identity'; 'keeps command-only pane inference bounded for large pasted scripts'; 'skips jcode colors for command-only startup %s'; 'keeps explicit pane ownership ahead of a delayed command hint'; 'does not infer a TUI from %s'; 'survives a launch config registered before its identity lands'; 'prefers the tab launch agent over every later signal'; 'falls back through startup, then initial status, then the registered config'; 'ignores a registered agent name that is not a known TUI agent'; 'skips the OSC color answer for jcode and no one else'; 'drops a Done that landed before the command-finished fact'; 'keeps a program Done reported before the command-finished fact'; 'dismisses the kept result when the next command starts'; 'keeps a facet-less OSC Done from a non-agent program'; 'still drops a real agent Done'; 'still drops an interrupted program Done'; 'retires a hook-identified row the foreground tracker never read'; 'leaves a pane with an armed command-finished drop to its own confirming read'; 'leaves a remote pane to its execution host'; 'keeps the row when the host can verify the owner process itself'; 'keeps a row that belongs to a different agent'; 'does not watch the store for an owner it can never name'; 'control: a fresh host image repaints the pane without resizing the program'; 'asks the program to repaint when the image is %s'; 'asks the program to repaint when the host never answers the snapshot request'; 'repaints a full-screen TUI on the alternate screen the same way'; 'leaves the size alone while a phone or another desktop holds it'; 'grows a pane at the host minimum height instead of asking for the same clamped size'; 'does not nudge while the stream is still reconnecting'; 'mounts and remounts the tab owner while an unrelated workspace is active (%s)'; 'continues a recorded live folder owner despite ambiguous inventory (%s)'; 'resolves an encoded split surface using its parent tab and active leaf'; 'does not capture a remote revision for a local terminal'; 'omits incarnation and length for older runtime responses'; 'refuses %s owner before RPC'; 'refuses a resolved terminal belonging to another native PTY'; 'refuses a foreign remote terminal handle despite a matching native PTY ID'; 'refuses a remote handle owned by another environment'; 'refuses a remote terminal with no live native PTY'; 'does not fall back locally when remote lacks RPC'; 'rejects malformed or oversized encoded response %#'; 'maps a unified terminal tab id to its legacy owner id'; 'keeps non-terminal and unknown ids unchanged'; 'keeps an exact terminal owner ahead of a stale unified alias'; 'stays inert on a host that was not kept for the bridge'; 'stays inert for a pane main does not list, so it still dials the host'." + "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. Exact retired authored alarms: 'bounds a startup title storm to one extra read ladder and never adopts the title as identity'; 'leaves untrackable providers free of client process scans'; 'keeps a legacy remote process hint unverifiable after a startup title'; 'releases a retained capability when disposed mid-read'; 'releases a retained capability when an exit schedules no successor read'; 'releases a retained capability when an untrackable $exit ends the read'; 'does not release when the cancelled read has a successor'; 'settles the visible confirmation when the pty id is gone before the read runs'; 'reports a read in flight when a command-finished read owns the pane'; 'reads the foreground once after a command starts and publishes the recognized agent'; 'does not replace known foreground identity with typed command inference'; 'revokes stale routing immediately while a known pane confirms a new command'; 'reads the foreground for a visible PTY so restored running Codex panes regain identity'; 'does not retry or publish visible PTY reads for an idle shell foreground'; 'retries visible PTY reads only while a foreground wrapper may resolve to an agent'; 'stops after the ladder and publishes no identity for a persistent unknown process'; 'does not treat a nested shell seen mid-command as prompt proof'; 'recognizes an agent started from a nested shell on a ladder re-read'; 'marks shell foreground on command finished without any foreground read'; 'trusts a rapid ordinary command finish without forcing a fresh scan'; 'still marks shell without a read for a duplicate D pair on an idle pane'; 'marks shell on a rapid command start->finish when the foreground is a shell'; 'marks shell foreground when the confirming read shows the agent is gone'; 'confirms a command finished for a launch-known agent pane before any read'; 'accepts a fresh shell result for a launch-known Droid pane'; 'marks a confirmed shell without repeating a post-boundary scan'; 'never reads or publishes for remote or ssh panes'; 'does not let forged OSC 133/777 output assert remote identity'; 'keeps command-only pane inference bounded for large pasted scripts'; 'skips jcode colors for command-only startup %s'; 'keeps explicit pane ownership ahead of a delayed command hint'; 'does not infer a TUI from %s'; 'survives a launch config registered before its identity lands'; 'prefers the tab launch agent over every later signal'; 'falls back through startup, then initial status, then the registered config'; 'ignores a registered agent name that is not a known TUI agent'; 'skips the OSC color answer for jcode and no one else'; 'drops a Done that landed before the command-finished fact'; 'keeps a program Done reported before the command-finished fact'; 'dismisses the kept result when the next command starts'; 'keeps a facet-less OSC Done from a non-agent program'; 'still drops a real agent Done'; 'still drops an interrupted program Done'; 'retires a hook-identified row the foreground tracker never read'; 'leaves a pane with an armed command-finished drop to its own confirming read'; 'leaves a remote pane to its execution host'; 'keeps the row when the host can verify the owner process itself'; 'keeps a row that belongs to a different agent'; 'does not watch the store for an owner it can never name'; 'control: a fresh host image repaints the pane without resizing the program'; 'asks the program to repaint when the image is %s'; 'asks the program to repaint when the host never answers the snapshot request'; 'repaints a full-screen TUI on the alternate screen the same way'; 'leaves the size alone while a phone or another desktop holds it'; 'grows a pane at the host minimum height instead of asking for the same clamped size'; 'does not nudge while the stream is still reconnecting'; 'mounts and remounts the tab owner while an unrelated workspace is active (%s)'; 'continues a recorded live folder owner despite ambiguous inventory (%s)'; 'resolves an encoded split surface using its parent tab and active leaf'; 'does not capture a remote revision for a local terminal'; 'omits incarnation and length for older runtime responses'; 'refuses %s owner before RPC'; 'refuses a resolved terminal belonging to another native PTY'; 'refuses a foreign remote terminal handle despite a matching native PTY ID'; 'refuses a remote handle owned by another environment'; 'refuses a remote terminal with no live native PTY'; 'does not fall back locally when remote lacks RPC'; 'rejects malformed or oversized encoded response %#'; 'maps a unified terminal tab id to its legacy owner id'; 'keeps non-terminal and unknown ids unchanged'; 'keeps an exact terminal owner ahead of a stale unified alias'; 'stays inert on a host that was not kept for the bridge'; 'stays inert for a pane main does not list, so it still dials the host'.", + "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.", + "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." ], "demotionRule": "Keep experimental or demote if adoption duplicates covered output, drops newer or unproven output, changes terminal ownership, or flakes without explanation." }, @@ -2679,17 +2681,17 @@ "providers": ["orca-server", "direct-ssh"], "coveredPlatforms": ["macos"], "coveredProviders": ["orca-server", "direct-ssh"], - "coverageNotes": "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. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): 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. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4274", "https://github.com/stablyai/orca/pull/14352", "https://github.com/stablyai/orca/issues/13044" ], "invariant": "A sidecar written by the new build cannot make the previous production build lose otherwise compatible VM runtimes. Downgrade lifecycle writes remain authoritative after re-upgrade, provisioned-root metadata remains recoverable, and corrupt or future feature metadata is preserved without poisoning the rollback-readable v1 store. Destroy attempts have no automatic wall-clock cutoff; a user stop terminates the process tree, retains cleanup ownership, and permits a fresh retry. Provider failure retains the SSH/project context needed for safe cleanup. Unrecoverable recipe context releases only the hidden SSH registration while preserving lifecycle/provider metadata. Provisioned-root create receives the source ref's pinned commit, adoption verifies the requested branch/ref, and resume preserves the connection mode plus stable SSH ownership identity while allowing endpoint rotation.", - "oracle": "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): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", + "oracle": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } 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): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", "commands": [ "node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/shared/ephemeral-vm-runtime-store.test.ts src/shared/ephemeral-vm-runtime-store-rollback.test.ts src/shared/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts src/main/ipc/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts src/main/ipc/ephemeral-vm.test.ts src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/shared/ephemeral-vm-runtime-store.test.ts src/shared/ephemeral-vm-runtime-store-rollback.test.ts src/shared/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts src/main/ipc/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts src/main/ipc/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts", "pnpm exec playwright test tests/e2e/ephemeral-vm-cleanup-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ @@ -2705,7 +2707,6 @@ "src/main/ipc/ephemeral-vm-provision-cancel.test.ts", "src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts", "src/main/ipc/ephemeral-vm.test.ts", - "src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts", "src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts", "tests/e2e/ephemeral-vm-cleanup-retry.spec.ts" ], @@ -2745,10 +2746,6 @@ "unrecoverable recipe context releases the hidden SSH registration but preserves failed lifecycle state" ] }, - { - "file": "src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts", - "assertions": ["failed or unconfirmed project-host rollback prevents provider destroy"] - }, { "file": "src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts", "assertions": [ @@ -2791,7 +2788,7 @@ }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The same pinned oracle passes the pre-#14352 ordinary store, fails the affected-main mixed store with file-is-invalid, passes the candidate mixed store plus old-service destroy and re-upgrade, and fails again when the candidate compatibility files are reverted to affected main." + "evidence": "Audit2056 retires the exact deleted-source assertion alarms recorded in knownGaps; prior changed-source red/green claims are historical. Unrelated retained-source evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The same pinned oracle passes the pre-#14352 ordinary store, fails the affected-main mixed store with file-is-invalid, passes the candidate mixed store plus old-service destroy and re-upgrade, and fails again when the candidate compatibility files are reverted to affected main." }, "performanceBudget": { "required": true, @@ -2817,7 +2814,8 @@ "Audit1342 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts\",\n \"assertions\": [\n \"provider failure retains runtime-owned SSH targets and confirmed success releases them\",\n \"unknown runtime inventory retains an explicitly requested target\"\n ]\n }\n]", "Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed.", "Audit1853 accepts removal of the runtime-ssh-cleanup.test.ts alarm for repairing cleanup_failed/provider-succeeded records that already lack a target ID. No equivalent replacement coverage is claimed. Keep the surviving cleanup selector and unchanged cross-version rollback receipt; the historical 2026-08-14 122-case cleanup receipt remains archived verbatim in knownGaps.", - "Audit1863 removes the standalone default-source-ref provisioning example. Its direct default-ref pinning alarm is intentionally lost; selected-ref pinning and invalid-ref cases remain without an equivalent replacement claim. Focused survivor execution does not validate the broad rollback selector or physical cross-version provisioning. Existing receipts retain their original commands and counts." + "Audit1863 removes the standalone default-source-ref provisioning example. Its direct default-ref pinning alarm is intentionally lost; selected-ref pinning and invalid-ref cases remain without an equivalent replacement claim. Focused survivor execution does not validate the broad rollback selector or physical cross-version provisioning. Existing receipts retain their original commands and counts.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n }" ], "demotionRule": "Demote if a new write fails the pinned rollback reader, a downgrade lifecycle mutation is lost after re-upgrade, malformed/future metadata overwrites recoverable bytes, ordinary v1 bytes change, user stop cannot settle a destroy process tree, cleanup loses retry ownership, an unrecoverable context leaves a permanent hidden SSH registration, or the focused gate flakes without an identified harness defect." }, @@ -4090,7 +4088,9 @@ "Audit2020 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence:\n{\n \"file\": \"src/cli/runtime/launch.test.ts\",\n \"assertions\": [\n \"waits past startup status lines for valid recipe JSON\",\n \"preserves UTF-8 recipe JSON split across Buffer chunks\",\n \"rejects when the server exits without valid recipe JSON\",\n \"accepts valid recipe JSON at exit without a trailing newline\"\n ]\n }", "Audit2020 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence:\n{\n \"file\": \"src/cli/runtime-client.test.ts\",\n \"assertions\": [\n \"local open activates a reachable headless owner and waits for a desktop window\",\n \"unsafe promotion returns an explicit blocked error instead of launching a second owner\"\n ]\n }", "Audit2020 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence:\n{\n \"file\": \"src/cli/runtime/websocket-transport.test.ts\",\n \"assertions\": [\n \"remote-paired open reports remote desktop state without launching a local app\"\n ]\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Quarantine the Electron journey only with a linked product or harness defect; demote if activation changes the owner/runtime/daemon/PTY identity, loses prior output, opens before provider readiness, or fails to honor a committed quit." }, @@ -4247,7 +4247,9 @@ "Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed.", "Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Historical removed assertion inventory: []", "Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Historical removed assertion inventory: [{\"file\":\"src/main/runtime/orca-runtime.test.ts\",\"assertions\":[\"only the newest reload owns the terminal timeout\",\"a superseded renderer-document generation cannot settle a reload\",\"cancelled navigation restores only the renderer or headless authority that actually survived\",\"cancellation after an earlier document commit stays fenced until its restarted timeout\",\"failed headless promotion remains pinned to its originating window\",\"successful desktop publication retires headless fallback\"]}]", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Demote if a reload revision settles more than once, a stale document or competing window can publish, a timer survives settlement, desktop failure stays indefinitely reloading, headless fallback returns after successful promotion, or either isolated Electron journey loses runtime or PTY identity." }, @@ -5081,7 +5083,9 @@ "Audit2043 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence:\n{\n \"file\": \"src/main/browser/document-preview/doc-preview-grant-registry.test.ts\",\n \"assertions\": [\n \"keeps silent authority over a document directory strictly inside the workspace, and only there\",\n \"authorizes only the requested sibling directory\",\n \"uses Windows semantics when authorizing a sibling directory\",\n \"keeps an approved SSH directory inside the canonical workspace boundary\"\n ]\n }", "Audit2043 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence:\n{\n \"file\": \"src/main/window/main-window-webview-security.test.ts\",\n \"assertions\": [\n \"an orca-preview src is admitted only on the preview partition with a live grant\",\n \"preview guests receive their own policy instead of the browser guest policies\",\n \"a preview attach is pinned to the preview preload over any renderer-supplied value, and a browsing attach never receives it\",\n \"grants a renderer can no longer release are cleared at window creation and on reload, and survive an in-document navigation\"\n ]\n }", "Audit2043 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence:\n{\n \"file\": \"src/main/ipc/doc-preview-grant-ipc.test.ts\",\n \"assertions\": [\n \"a sender that is not the trusted renderer mints no grant and revokes none\",\n \"a reported link click reaches the guest policy with its own sender, and a non-string report reaches nothing\"\n ]\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Demote if a paired HTML preview creates a browser workspace on either side, renders from anything other than the orca-preview scheme, serves a read the host reported as truncated or over-cap, serves a document without the self-only content security policy, lets the preview session carry an off-machine request, reads an SSH path that canonicalizes outside its grant root, steals focus from the source editor when it opens, removes unrelated editor or terminal state on close, hides a document that rendered because one subresource was refused, leaves a grant readable after the tab or renderer that owns it is gone, mints one for a sender that is not the trusted renderer, opens a browser tab for a navigation the document started with no one at the keyboard, or lets the guest gather an ICE candidate; or if a paired browser creation this gate still owns produces duplicate client or host identities or loses its requested split." }, @@ -6261,7 +6265,9 @@ "Audit1417 intentionally 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. No equivalent replacement coverage or fresh result is claimed.", "Audit1878 removes only the direct over-cap abandonment example from terminal-partial-escape-tail.test.ts. The unchanged fixed-sequence split/fold sweep is retained; it is not an independent parser oracle or a new execution of the historical 25.6M-case sweep. Its current seventeen sequences do not substantiate the full alphabet inventory described by the older assertion reference. No equivalent replacement coverage or fresh whole-gate execution is claimed.", "Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. 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. Exact retired authored alarms: 'starts idle for unknown PTY'; 'handleMobileSubscribe in auto mode transitions idle → mobile{clientId}'; 'handleMobileSubscribe in desktop mode is passive — does NOT take floor'; 'reclaimTerminalForDesktop transitions mobile → desktop and is idempotent'; 'mobileTookFloor after reclaim re-applies phone-fit and flips driver back to mobile'; 'restores the pre-write driver after overlapping claims from one phone both fail'; 'keeps a successful overlapping claim as the rollback baseline'; 'does not let an older phone-fit completion retake a newer writer floor'; 'a superseded mobile input %s preserves a newer phone claim'; 'mobile input without an active subscriber cannot create an orphaned floor lock'; 'a %s phone-fit completion after disconnect cannot recreate the mobile lock'; 'admits a soft-leaving client to reserve the input floor within the grace window'; 'handleMobileUnsubscribe last leaver flips driver to idle after soft-leave grace'; 'resubscribe within soft-leave grace cancels idle without driver flap'; 'onPtyExit clears driver state and emits idle'; 'elects one query responder and promotes the survivor on unsubscribe'; 'keeps the earliest subscriber authoritative after a soft-leave resubscribe'; 'excludes an older passive desktop-mode subscriber from reply authority'; 'most-recent actor wins active phone-fit dims (B subscribes after A)'; 'B unsubscribes — A still present, driver re-elects to A'; 'A then B unsubscribes — peer survives; final unsubscribe goes idle'; 'terminal.send by phone-B updates lastActedAt — applyMobileDisplayMode picks B viewport'; 'mobile mode change marks the caller before applying phone-fit'; 'updateMobileViewport re-fits PTY without flipping the driver'; 'updateMobileViewport late-binds a viewport-less mobile subscriber'; 'updateMobileViewport records viewport without applying layout in desktop mode'; 'updateMobileViewport reports applied=false when phone-fit resize fails'; 'updateMobileViewport then disconnect restores PTY to original baseline'; 'legacy unsubscribe → resubscribe within grace preserves baseline (regression)'; 'earliest-subscribe restore target is preserved when peers churn'; 'second Restore click after success returns true with no new resize or fit-override event'; 'driving take-back still converges: driver → desktop, override cleared, both channels notified'; 'held restore with a failing resize still releases and clears the override'; 'active-subscriber take-back with a failing resize still releases the lock'; 'phone-initiated setDisplayMode(desktop) against a stale held override converges'; 'orphan cleanup: reclaim on a held override with no layout entry converges'; 'a still-subscribed phone reporting its viewport does not undo a desktop take-back'; 'a deliberate mobile gesture still re-takes the floor after a desktop take-back'; 'a replayed subscribe after a reconnect does not undo a desktop take-back'; 'a foreground resubscribe inside the soft-leave grace does not undo a desktop take-back'; 'typing on the phone after a reconnect re-takes the floor and phone-fits again'; 'take-back of a held phone-fit with no subscriber also keeps the next subscribe passive'.", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Keep experimental or demote if missing ownership proof changes incumbent behavior, a live TUI loses mouse/focus modes, foreground inspection enters ordinary output/reveal paths, or the focused Electron journey flakes without an identified product or harness fault." }, @@ -6876,7 +6882,9 @@ "Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Historical removed assertion inventory: [{\"file\":\"src/main/runtime/orca-runtime.test.ts\",\"assertions\":[\"workspace-wide close force-retires pinned and unpinned tabs, clears resume/incarnation state, awaits both target PTYs, preserves the sibling worktree, and reports an unconfirmed stop as unverifiable\"]}]", "Audit1863 removes the standalone local pane-to-PTY equality example. Its direct local-PTY authority alarm is intentionally lost; retained canonical runtime-handle tests do not replace it or prove physical pane/session retirement. Existing E2E and continuity receipts remain scoped to their original commands and counts.", "Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Lost direct alarms: 'remaps legacy SSH lease leaf ids by PTY when the layout is already normalized'; 'promotes an empty tab layout to a durable UUID root when persisting the first PTY binding'.", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Keep experimental or demote to protection none if exact PTY disappearance flakes, a sibling/detached pane is retired, late hooks can recreate closed authority, or a renderer graph sync retires a host-created tab that no explicit close retired." }, @@ -7041,7 +7049,9 @@ "Audit1983 historical original testFiles object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n\"src/main/runtime/rpc/runtime-close-attribution-topology.test.ts\"", "Audit1983 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/rpc/runtime-close-attribution-topology.test.ts\",\n \"assertions\": [\n \"remote, legacy, reconnect, stale, concurrent, cross-worktree, and unowned close spans retain authoritative runtime, target, requester, decision, and outcome identities without serializing the bearer credential\",\n \"close attribution adds no terminal inventory scan or provider fanout\"\n ]\n }", "Audit2020: The CLI WebSocket source retains old-protocol refusal only; its paired-open, capability, timeout and admission projection examples are removed. No daemon-generation coverage is transferred to that callback. Both independent daemon E2E receipts remain unchanged at their original commands; the reduced unit selector has no fresh result.", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Keep experimental or quarantine if reconnect emits session-killed for a live canary, an exact root/descendant dies, an old server receives fallback destructive close, cleanup leaks a fixture process/pipe, or the gate flakes without a proven harness defect." }, @@ -7610,7 +7620,9 @@ "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. Existing exact primary-selector receipts remain unchanged.", "Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Historical removed assertion inventory: []", "Audit1417 intentionally 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. No equivalent replacement coverage or fresh result is claimed.", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Demote or quarantine if failures are non-actionable or if a duplicate resume escape occurs outside the modeled matrix." }, @@ -7896,7 +7908,9 @@ "Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed.", "Audit2003 historical original commands object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/terminal/adoption/terminal-orphan-topology.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1\"", "Audit2003 historical original testFiles object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n\"src/main/runtime/terminal/adoption/terminal-orphan-topology.test.ts\"", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). 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(). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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. 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." ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if a retry can physically spawn twice, if a stale exit/publication can replace or resurrect a terminal, or if mixed-version fallback occurs after an authority side effect." }, @@ -7920,16 +7934,16 @@ "providers": ["local", "remote-runtime", "ssh", "wsl"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "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. Historical scope before this audit: Audit1488 deletes NonGitFolderDialog tests. The hand-assembled scan/import pipelines, supplied host and folder outcomes, registration callback receipts and static host confirmation alarms are retired. No equivalent replacement coverage or fresh routing validation is claimed. Historical receipts and assertions describe their original sources only. Audit1487 deletes AddProjectFromFolderDialog and project-added-default-checkout tests and reduces AddRepoStartSteps to custom ArrowDown navigation. Mocked admission/activation and static host-control assertions are retired. No equivalent replacement coverage or fresh routing validation is claimed. Historical receipts and assertions below describe their original sources only. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/store/slices/repos-stale-fetch.spec.ts: Loses startup catalog admission/reconnect preservation and settlement failure gating alarms. 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): Audits1342 and1337 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): Audit1320 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): This audit removes browser generic Active Server settings isolation and unknown-choice examples; their direct preference and rejection alarms are lost. Other routing evidence is not an equivalent replacement. Historical commands and results remain historical. Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, Add Project, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, Add Project eligibility/owner capture/stale-result fencing, host-qualified group/folder/worktree identity, and restart reset of transient routing are covered. A visible macOS Orca desktop server plus separate paired Electron and web clients prove selected-runtime Add Project operations and disabled creation when the only listed host is blocked or unavailable; headless-server parity also passed. Live Linux, Windows, WSL, and SSH Add Project journeys remain uncollected. The static wrapper-rendering suite was removed during the low-value-test audit; its supplied-prop host-browser and control-visibility output assertions are no longer checked by that suite. This removal supplies no new runtime-routing evidence. The fake-React Clone hook unit suite was also retired: its captured-owner and same-ID sibling assertions no longer supply unit evidence. Historical run commands and counts remain historical; this retirement adds no runtime-routing, cross-platform, or mobile evidence. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit narrowed worktree-runtime-owner.test.ts to deterministic owner-lookup work bounds with correct worktree/folder results and changed-collection invalidation. Its separate host/default/folder/mirror inventory alarms are lost; these retained in-memory checks establish no actual host delivery, restart or equivalent replacement coverage. Historical run commands and results remain historical. web-runtime-session.test.ts no longer supplies the terminal/browser/staged-browser explicit-host collision assertions formerly referenced here. Those direct routing alarms are lost; the remaining selector and live routing evidence does not establish equivalent replacement coverage. The test-value audit removes the direct host/provider/project-setup selector tables. selectors.test.ts retains only floating-tab/unread scan-cost checks, which supply no current Active Server routing evidence. Its separate missing-runtime/no-local-fallback and owner-choice alarms are lost; other gate evidence is not an equivalent replacement. Historical executed commands and results remain historical. browser.test.ts no longer supplies the host/profile projection examples. Current routing commands and references name the retained deferred host-list/import completion tests in browser-session-host-selection.test.ts instead. Its actual source supports stale-completion fencing; it does not establish the formerly listed multi-client selection or restart-reset claims. Other evidence is not an equivalent replacement; historical executed commands/counts/results remain historical. The test-value audit deletes repos-paired-runtime-add.test.ts. Its supplied-result assertion that an explicitly selected paired host receives repo.add with the selected path, folder kind and 15000ms timeout while native repos.add and pickFolder remain unused is intentionally lost. Other gate evidence is not an equivalent replacement. Historical executed commands, counts and results remain unchanged. The test-value audit narrows repos-selected-owner-routing.test.ts to an overlapping selected-runtime import/local refresh, reversed same-host folder replies, and group/folder replies crossing an actual pairing revision. Its separate same-ID host-partition, desktop-only pruning, sequential explicit-runtime preservation, and SSH scan/cancel forwarding alarms are intentionally lost. The stale-response case overwrites its group result before the final assertion, so it supplies only a folder stale-response alarm. The catalog-reconciliation caller also retires the refresh-identity and runtime-visibility-default registrars: their immediate reference/field/count, filter/dismissal, readoption-inventory, timestamp and settings/capability-copy/retention alarms are lost. No equivalent replacement or new live host, restart, platform or mobile evidence is claimed; historical executed commands, counts and results remain unchanged. The test-value audit removes the reversed-order direct worktree lookup example from selected-host-active-workspace-identity.test.ts. Its explicit-runtime path lookup with reversed same-ID catalog rows is intentionally lost; that example did not activate a workspace. After the subsequent audit, current assertions in this suite name only the retained local-first worktree activation; the selected-runtime folder/group host-echo example was removed. They are not equivalent replacements for the reversed-order lookup alarm. Historical executed commands, counts and results remain unchanged; no new live host, restart, platform or mobile evidence is claimed. The test-value audit narrows renderer store settings.test.ts by removing immediate authoritative-settings/response rebasing, checked-failure forwarding, best-effort logging, mobile-address/provider normalization, successful catalog-start, hand-seeded partial-status coverage and ghost-status filtering examples. Those direct response, normalization, error and catalog-projection alarms are intentionally lost. The runtime focus-switch resource/draft preservation, unreachable/incompatible refusal and held catalog coalescing/retry/staleness cases remain; they are not equivalent replacements for the removed alarms. Historical executed commands, counts and results remain unchanged; no new live host, restart, platform or mobile evidence is claimed. The test-value audit narrows worktrees-fetch-owner-routing.test.ts by removing default-local transport selection, ownerless runtime stamping, isolated force-local routing, and mocked mobile-denial/toast examples. Those direct routing, field and presentation alarms are lost. Retained concurrency and authority-fencing cases do not establish equivalent replacement coverage or live host, platform, restart or mobile evidence. Historical commands, counts and results remain unchanged. The test-value audit removes the separate paired-web host-switch resource-preservation example from renderer store settings.test.ts. Its explicit web-mode terminal/browser no-close and retained PTY/remote-browser-handle alarms are intentionally lost. The surviving desktop host-merge, resource/draft preservation, refusal and catalog retry/coalescing/staleness cases are not equivalent replacement coverage. Historical executed commands, counts and results remain unchanged; no new live host, restart, platform or mobile evidence is claimed. The test-value audit removes the selected-runtime folder/group activation example from selected-host-active-workspace-identity.test.ts. That large same-ID fixture only asserted that the explicit host argument was stored and read back; it did not check the chosen folder path, group or delivered operation. Its narrow non-rejection/host-echo alarm is intentionally lost. Only the local-first worktree case that independently checks the returned runtime path remains in this suite. Historical executed commands, counts and results remain unchanged; no equivalent replacement or new live-host evidence is claimed. The continued test-value audit narrows worktrees-fetch-owner-routing.test.ts by retiring the simple explicit-local duplicate-repo request and runtime-only host-stamping examples. Those exact request-option and supplied-row alarms are intentionally lost. The retained force-local sibling-preservation and project-setup stamping cases use different inputs and are not equivalent replacements. Historical commands, counts and results remain unchanged; no live-host, restart, platform or mobile evidence is added. The test-value audit removes the browser-settings host-option fallback helper suite. Its direct selected/default/empty-option preference alarms are lost; no browser session, host delivery or persistence was exercised there. Remaining routing evidence is not an equivalent replacement. Historical commands, counts and results remain historical. The test-value audit deletes paired-web-add-project-unavailable-host.spec.ts. Its injected blocked/unavailable-host disabled-action and no-local-option presentation alarms are intentionally lost. The snapshot sequence and null transport do not prove actual version negotiation or operation rejection. Other routing evidence is not an equivalent replacement; no new runtime, platform or mobile evidence is claimed. The two retired historical receipts and assertion reference are archived below with their original fields and results. Audit1320: src/renderer/src/components/settings/runtime-environments/catalog/RuntimeEnvironmentsPane.test.ts removed. Transport-up/runtime-down, failed-probe ready/reconnect/handshake and stale compatibility label/button state inventories lose alarms. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/sidebar/worktree-list/listing/host-filtering.test.ts removed. Runtime/SSH/default row ownership and folder/project path-status routing samples disappear. src/renderer/src/store/slices/repos-catalog-reconciliation.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1337: src/renderer/src/components/sidebar/project-admission/dialog/add-repo-browse-authority.test.ts removed. Removes paired-host browse versus native picker callback flags and SSH no-browse predicate samples. src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialog.default-checkout.test.ts removed. Removes explicit local/runtime versus missing owner selector examples. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1391: src/renderer/src/lib/worktree-runtime-owner.test.ts reduced. Lose explicit repeated-lookup work/read budget and standalone initial owner lookup alarms. Retained production resolver proves changed ownership is visible, using synthetic catalogs rather than server publication. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/store/project-groups/nested-repository-operations.test.ts: routes local nested scan progress by scanId and unsubscribes after completion. 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): 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. Historical scope before this audit: Audit1488 deletes NonGitFolderDialog tests. The hand-assembled scan/import pipelines, supplied host and folder outcomes, registration callback receipts and static host confirmation alarms are retired. No equivalent replacement coverage or fresh routing validation is claimed. Historical receipts and assertions describe their original sources only. Audit1487 deletes AddProjectFromFolderDialog and project-added-default-checkout tests and reduces AddRepoStartSteps to custom ArrowDown navigation. Mocked admission/activation and static host-control assertions are retired. No equivalent replacement coverage or fresh routing validation is claimed. Historical receipts and assertions below describe their original sources only. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/store/slices/repos-stale-fetch.spec.ts: Loses startup catalog admission/reconnect preservation and settlement failure gating alarms. 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): Audits1342 and1337 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): Audit1320 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): This audit removes browser generic Active Server settings isolation and unknown-choice examples; their direct preference and rejection alarms are lost. Other routing evidence is not an equivalent replacement. Historical commands and results remain historical. Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, Add Project, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, Add Project eligibility/owner capture/stale-result fencing, host-qualified group/folder/worktree identity, and restart reset of transient routing are covered. A visible macOS Orca desktop server plus separate paired Electron and web clients prove selected-runtime Add Project operations and disabled creation when the only listed host is blocked or unavailable; headless-server parity also passed. Live Linux, Windows, WSL, and SSH Add Project journeys remain uncollected. The static wrapper-rendering suite was removed during the low-value-test audit; its supplied-prop host-browser and control-visibility output assertions are no longer checked by that suite. This removal supplies no new runtime-routing evidence. The fake-React Clone hook unit suite was also retired: its captured-owner and same-ID sibling assertions no longer supply unit evidence. Historical run commands and counts remain historical; this retirement adds no runtime-routing, cross-platform, or mobile evidence. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit narrowed worktree-runtime-owner.test.ts to deterministic owner-lookup work bounds with correct worktree/folder results and changed-collection invalidation. Its separate host/default/folder/mirror inventory alarms are lost; these retained in-memory checks establish no actual host delivery, restart or equivalent replacement coverage. Historical run commands and results remain historical. web-runtime-session.test.ts no longer supplies the terminal/browser/staged-browser explicit-host collision assertions formerly referenced here. Those direct routing alarms are lost; the remaining selector and live routing evidence does not establish equivalent replacement coverage. The test-value audit removes the direct host/provider/project-setup selector tables. selectors.test.ts retains only floating-tab/unread scan-cost checks, which supply no current Active Server routing evidence. Its separate missing-runtime/no-local-fallback and owner-choice alarms are lost; other gate evidence is not an equivalent replacement. Historical executed commands and results remain historical. browser.test.ts no longer supplies the host/profile projection examples. Current routing commands and references name the retained deferred host-list/import completion tests in browser-session-host-selection.test.ts instead. Its actual source supports stale-completion fencing; it does not establish the formerly listed multi-client selection or restart-reset claims. Other evidence is not an equivalent replacement; historical executed commands/counts/results remain historical. The test-value audit deletes repos-paired-runtime-add.test.ts. Its supplied-result assertion that an explicitly selected paired host receives repo.add with the selected path, folder kind and 15000ms timeout while native repos.add and pickFolder remain unused is intentionally lost. Other gate evidence is not an equivalent replacement. Historical executed commands, counts and results remain unchanged. The test-value audit narrows repos-selected-owner-routing.test.ts to an overlapping selected-runtime import/local refresh, reversed same-host folder replies, and group/folder replies crossing an actual pairing revision. Its separate same-ID host-partition, desktop-only pruning, sequential explicit-runtime preservation, and SSH scan/cancel forwarding alarms are intentionally lost. The stale-response case overwrites its group result before the final assertion, so it supplies only a folder stale-response alarm. The catalog-reconciliation caller also retires the refresh-identity and runtime-visibility-default registrars: their immediate reference/field/count, filter/dismissal, readoption-inventory, timestamp and settings/capability-copy/retention alarms are lost. No equivalent replacement or new live host, restart, platform or mobile evidence is claimed; historical executed commands, counts and results remain unchanged. The test-value audit removes the reversed-order direct worktree lookup example from selected-host-active-workspace-identity.test.ts. Its explicit-runtime path lookup with reversed same-ID catalog rows is intentionally lost; that example did not activate a workspace. After the subsequent audit, current assertions in this suite name only the retained local-first worktree activation; the selected-runtime folder/group host-echo example was removed. They are not equivalent replacements for the reversed-order lookup alarm. Historical executed commands, counts and results remain unchanged; no new live host, restart, platform or mobile evidence is claimed. The test-value audit narrows renderer store settings.test.ts by removing immediate authoritative-settings/response rebasing, checked-failure forwarding, best-effort logging, mobile-address/provider normalization, successful catalog-start, hand-seeded partial-status coverage and ghost-status filtering examples. Those direct response, normalization, error and catalog-projection alarms are intentionally lost. The runtime focus-switch resource/draft preservation, unreachable/incompatible refusal and held catalog coalescing/retry/staleness cases remain; they are not equivalent replacements for the removed alarms. Historical executed commands, counts and results remain unchanged; no new live host, restart, platform or mobile evidence is claimed. The test-value audit narrows worktrees-fetch-owner-routing.test.ts by removing default-local transport selection, ownerless runtime stamping, isolated force-local routing, and mocked mobile-denial/toast examples. Those direct routing, field and presentation alarms are lost. Retained concurrency and authority-fencing cases do not establish equivalent replacement coverage or live host, platform, restart or mobile evidence. Historical commands, counts and results remain unchanged. The test-value audit removes the separate paired-web host-switch resource-preservation example from renderer store settings.test.ts. Its explicit web-mode terminal/browser no-close and retained PTY/remote-browser-handle alarms are intentionally lost. The surviving desktop host-merge, resource/draft preservation, refusal and catalog retry/coalescing/staleness cases are not equivalent replacement coverage. Historical executed commands, counts and results remain unchanged; no new live host, restart, platform or mobile evidence is claimed. The test-value audit removes the selected-runtime folder/group activation example from selected-host-active-workspace-identity.test.ts. That large same-ID fixture only asserted that the explicit host argument was stored and read back; it did not check the chosen folder path, group or delivered operation. Its narrow non-rejection/host-echo alarm is intentionally lost. Only the local-first worktree case that independently checks the returned runtime path remains in this suite. Historical executed commands, counts and results remain unchanged; no equivalent replacement or new live-host evidence is claimed. The continued test-value audit narrows worktrees-fetch-owner-routing.test.ts by retiring the simple explicit-local duplicate-repo request and runtime-only host-stamping examples. Those exact request-option and supplied-row alarms are intentionally lost. The retained force-local sibling-preservation and project-setup stamping cases use different inputs and are not equivalent replacements. Historical commands, counts and results remain unchanged; no live-host, restart, platform or mobile evidence is added. The test-value audit removes the browser-settings host-option fallback helper suite. Its direct selected/default/empty-option preference alarms are lost; no browser session, host delivery or persistence was exercised there. Remaining routing evidence is not an equivalent replacement. Historical commands, counts and results remain historical. The test-value audit deletes paired-web-add-project-unavailable-host.spec.ts. Its injected blocked/unavailable-host disabled-action and no-local-option presentation alarms are intentionally lost. The snapshot sequence and null transport do not prove actual version negotiation or operation rejection. Other routing evidence is not an equivalent replacement; no new runtime, platform or mobile evidence is claimed. The two retired historical receipts and assertion reference are archived below with their original fields and results. Audit1320: src/renderer/src/components/settings/runtime-environments/catalog/RuntimeEnvironmentsPane.test.ts removed. Transport-up/runtime-down, failed-probe ready/reconnect/handshake and stale compatibility label/button state inventories lose alarms. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/sidebar/worktree-list/listing/host-filtering.test.ts removed. Runtime/SSH/default row ownership and folder/project path-status routing samples disappear. src/renderer/src/store/slices/repos-catalog-reconciliation.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1337: src/renderer/src/components/sidebar/project-admission/dialog/add-repo-browse-authority.test.ts removed. Removes paired-host browse versus native picker callback flags and SSH no-browse predicate samples. src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialog.default-checkout.test.ts removed. Removes explicit local/runtime versus missing owner selector examples. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1391: src/renderer/src/lib/worktree-runtime-owner.test.ts reduced. Lose explicit repeated-lookup work/read budget and standalone initial owner lookup alarms. Retained production resolver proves changed ownership is visible, using synthetic catalogs rather than server publication. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/9687", "https://linear.app/stably/issue/STA-4024/p1-paired-web-add-project-enables-unavailable-host-fallback-after-pr" ], "invariant": "Only an explicit user change in Settings > Remote Orca Servers > Advanced > Active Server may mutate activeRuntimeEnvironmentId. Connecting, pairing, disconnecting, selecting or revealing a workspace or terminal, browser/mobile handoff, remote navigation, and reconnect must use transient or target-owner routing and must never rewrite the durable preference. Every Add Project selected host must satisfy canSelectAddRepoHost; paired web has no local filesystem fallback, so no valid host means Browse, Clone, and Create remain disabled. Every operation stays on the host selected when it began, even if preference or catalog state changes. Generic settings mutation cannot bypass the dedicated preference IPC.", - "oracle": "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): Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat transient routing and selected-runtime Add Project operations with exact-ID host decoys and completion reordering. Separately pair the real web client to an isolated headed host, then make its sole still-listed runtime compatibility-blocked and unavailable. Require a null authoritative selection, a disabled host option, and disabled Browse, Clone, and Create actions with no local fallback. Repeat against headless serve. Run the byte-identical selector/action contract on latest main, candidate, and candidate with the eligibility seam disabled.", + "oracle": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/store/project-groups/nested-repository-operations.test.ts: routes local nested scan progress by scanId and unsubscribes after completion. 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): 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): Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat transient routing and selected-runtime Add Project operations with exact-ID host decoys and completion reordering. Separately pair the real web client to an isolated headed host, then make its sole still-listed runtime compatibility-blocked and unavailable. Require a null authoritative selection, a disabled host option, and disabled Browse, Clone, and Create actions with no local fallback. Repeat against headless serve. Run the byte-identical selector/action contract on latest main, candidate, and candidate with the eligibility seam disabled.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts src/renderer/src/store/slices/settings/settings.test.ts src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/project-groups/nested-repository-operations.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx --maxWorkers=1", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" @@ -7950,7 +7964,6 @@ "src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts", "src/renderer/src/store/repos/repos-stale-fetch.test.ts", "src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts", - "src/renderer/src/store/project-groups/nested-repository-operations.test.ts", "src/renderer/src/store/repos/repos-selected-owner-routing.test.ts", "src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts", "src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts", @@ -8110,7 +8123,8 @@ "Audit1487 retires this complete dated receipt because its source changed; not current execution evidence: {\"date\":\"2026-11-04\",\"runner\":\"local\",\"platform\":\"linux\",\"result\":\"passed\",\"command\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm --config.verifyDepsBeforeRun=false test src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx --maxWorkers=2\",\"currentCommand\":\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx --maxWorkers=1\",\"durationSeconds\":3.6,\"summary\":\"Test Files 1 passed (1); Tests 14 passed (14). Focused Linux unit execution; no physical-provider, p95 or cross-platform claim. Source head 415c9cffc2d10024131ec4b6721767a22195de6d.\"}", "Audit1487 historical assertion inventory; not current validated assertions: [{\"file\":\"src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx\",\"assertions\":[\"host-scoped Add Project actions remain disabled until a paired runtime is selectable\"]},{\"file\":\"src/renderer/src/components/sidebar/project-admission/completion/project-added-default-checkout.test.ts\",\"assertions\":[\"filters loaded, detected, refreshed, and activated default checkouts by the captured execution host when repo IDs collide\"]}]", "Audit1488 deletes NonGitFolderDialog tests. The hand-assembled scan/import pipelines, supplied host and folder outcomes, registration callback receipts and static host confirmation alarms are retired. No equivalent replacement coverage or fresh routing validation is claimed. Historical receipts and assertions describe their original sources only.", - "Audit1488 historical assertion inventory; not current validated assertions: []" + "Audit1488 historical assertion inventory; not current validated assertions: []", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/store/project-groups/nested-repository-operations.test.ts: routes local nested scan progress by scanId and unsubscribes after completion. 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." ], "demotionRule": "Demote or block release if any non-Advanced path mutates Active Server, if local reveal or Add Project depends on the durable default instead of captured workspace/host ownership, if an Add Project operation reaches a different host after it begins, or if transient host state survives restart." }, @@ -9314,7 +9328,9 @@ "Audit1991 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\n \"assertions\": [\n \"omits an unknown snapshot output sequence instead of publishing the layout version\"\n ]\n }", "Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. 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.", "Audit2003 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 4.29,\n \"summary\": \"All 10 subscriber-driven attach contracts passed. With two authoritative inventories overlapping one refused in-flight attach, removing only the post-settlement retry made the byte-identical focused assertion fail with one attach instead of two; restoring it retained one bounded waiter, retried once, and resumed live output on the existing stream.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts\"\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Keep experimental or demote to protection none if decorative title frequency changes paired client-event or session-tabs publication volume after convergence, a semantic fact is dropped, paired first paint is blank, passive work reconnects after manual disconnect, a capable hidden paired manager survives ordinary parking, a legacy hidden pane schedules raw xterm output or bypasses its fallback, reveal loses requested bounded history or live PTY identity, retained buffer cells do not fall, or either headed/headless scenario flakes." }, @@ -9630,7 +9646,9 @@ "Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Historical removed assertion inventory: [{\"file\":\"src/main/runtime/orca-runtime.test.ts\",\"assertions\":[\"returns a blocked wait result for Codex update prompts\",\"returns a blocked wait result for Codex workspace trust prompts\",\"returns a blocked wait result for generic Codex interactive prompts\",\"resolves tui-idle when a stale Codex prompt is followed by the ready header\"]}]", "Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. 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. Exact retired authored alarms: 'computeTerminalTailWaitState reports fromTail and blocked signals'.", "Audit1931 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/orca-runtime-tail-wait-memo.test.ts\",\n \"assertions\": [\n \"does not rebuild or repeatedly scan an ordinary saturated tail\",\n \"memoized stamping matches recompute reference: blocked prompt split across chunks\",\n \"stays equivalent across tail eviction beyond the retained cap\"\n ]\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -10953,7 +10971,9 @@ "Audit1383 historical assertion inventory for changed sources:\n[\n {\n \"file\": \"src/main/runtime/rpc/terminal-agent-prompt-send.test.ts\",\n \"assertions\": [\n \"a freshly proven Claude or Codex desktop target uses settled prompt delivery\",\n \"a non-target agent or shell preserves the existing direct send\"\n ]\n }\n]", "Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Historical removed assertion inventory: [{\"file\":\"src/main/runtime/orca-runtime.test.ts\",\"assertions\":[\"Claude and Codex wait for marker-gated composer quiescence before submit\",\"every other configured TUI agent retains the legacy platform delay\",\"a speculative CLI prompt check does not poll wrapper foregrounds\",\"the PTY write boundary retains bracketed framing and one delayed submit\"]}]", "Audit1991: Remove partial-runtime terminal-send micro-alarms; the reduced RPC source retains held viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences. Preserve the3 unrelated historical repro and source-built end-to-end receipts at their original exact commands; do not transfer their counts or physical platform claims to reduced unit callbacks. 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.", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Keep experimental or demote to protection none if direct shell/mobile/query input is reframed, an unrecognized target receives bracketed paste, a prompt can emit duplicate Enter, mixed-version decoding rejects the optional field, or the deterministic fake-composer candidate requires a rescue send." }, @@ -11091,7 +11111,9 @@ "Audit1943 (sources1934/1935/1938): Pruned coordinator suite retains actual dispatch-failure circuit breaking through SQLite and an actual drift-threshold silent-skip. Both existing prompt-injection aliases remain backed within injected send/terminal/probe scope. Other scalar admission, identity attribution, stop flag and prompt-section/fallback projections are intentionally lost; independent runtime writer and worker-start receipts remain limited to their original selectors, without transferred execution or replacement claims. 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. Exact retired authored alarms: 'throws if no tasks exist'; 'records the assignee pane key when the runtime can resolve one'; 'records authenticated process authority for automatic dispatch'; 'can be stopped'; 'threads drift into the preamble when behind > 0 and under threshold'; 'proceeds with stripped spec + drift section when allow-stale-base overrides'; 'proceeds without drift section when probeWorktreeDrift returns null'; 'does not call probeWorktreeDrift when coordinator has no worktree selector'; 'proceeds without drift when probeWorktreeDrift throws'.", "Audit1973: Remove mocked injected-preamble forwarding and raw terminal.send absence aliases. Retain the real database rollback alias for failed injection and both unrelated dated receipts. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result.", "Audit1973 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/rpc/methods/orchestration/runs/tasks-dispatch.test.ts\",\n \"assertions\": [\n \"orchestration.dispatch uses the agent prompt path for injected preambles\",\n \"raw terminal.send is not called for injected task prompts\",\n \"failed prompt injection rolls back the active dispatch\"\n ]\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Demote or quarantine if the live harness flakes without a product bug or harness bug filed to the terminal-input owner." }, @@ -11301,7 +11323,9 @@ "Audit1948 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/orchestration/federation/synchronization/federation-sync.test.ts\",\n \"assertions\": [\n \"an acknowledged duplicate replay does not wake a waiter\",\n \"overlapping syncs preserve one durable forward-only checkpoint\"\n ]\n }", "Audit1973: Remove scalar, private-shape and projection examples and check cases whose reconciler runs manually before check. Retain actual federation lost-ack/gap and lifecycle completion-ack/replay alarms; unrelated message-delivery-identity receipt remains exact. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result.", "Audit2003: Remove simpler proven-absent/unknown-delivery, synchronous double-trigger and exit-cleanup examples from the stale-leaf source. Retain controlled waiter-versus-probe races, queued-row progression, same-ID stale-Enter cancellation and orphaned-snapshot fences. Provider/process observations and database rows in this source are supplied, not actual process absence or SQLite delivery durability. Preserve the independent five-case SQLite/CLI receipt only at its unchanged command. 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.", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Demote or quarantine if the deterministic oracle flakes without a product or harness bug owned by orchestration." }, @@ -11593,7 +11617,9 @@ "Audit1983 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-03\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot\",\n \"result\": \"passed\",\n \"durationSeconds\": 3.13,\n \"summary\": \"The same byte-identical oracle passed 5 tests on candidate@2748b0b29b, exercising the production verifier and fresh-runtime replay while preserving exact DB identity and unchanged fixture bytes.\"\n }", "Audit1983 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-03\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot\",\n \"result\": \"failed\",\n \"durationSeconds\": 3.14,\n \"summary\": \"With current-authority propagation actually disabled in candidate child 08a7db37bf, the same byte-identical oracle failed 2 of 5 rows: completion remained dispatched and remote attachment authority was rejected.\"\n }", "Audit1983 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-03\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts --reporter=dot\",\n \"result\": \"passed\",\n \"durationSeconds\": 3.1,\n \"summary\": \"After reverting the intentional break in d2a4e2e024, the same byte-identical oracle passed all 5 tests.\"\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox." }, @@ -13391,23 +13417,23 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. 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): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): 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. Historical scope before this audit: 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. Historical scope before this audit: 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. Historical scope before this audit: 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. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. 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): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): 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. Historical scope before this audit: 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. Historical scope before this audit: 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. Historical scope before this audit: 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. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/5308", "https://github.com/stablyai/orca/issues/7547", "https://github.com/stablyai/orca/issues/8212" ], "invariant": "Local runtime and SSH relay roots share one watcher child per host process while healthy and use at most four quarantine children after shard failure; native desktop, paired-runtime, and direct WSL snapshot children consume the same process-wide eight-child reservation and retry transient exhaustion without permanently disabling a root. Cancellation remains owned by its child generation and settles only after acknowledgement or bounded physical exit; paired-web retains cleanup ownership and can cancel before readiness even while capacity is exhausted, retries a failed unwatch after already-resolved or late physical exit without duplicating stream termination, replacements never overlap a still-retiring generation, and aborted or timed-out callers detach immediately even while queued behind same-root relay teardown. Destructive local and SSH cleanup holds one containment-aware watcher/terminal removal fence through descendant watcher and PTY physical exit plus parent Git/filesystem deletion; daemon and relay kill requests retain ownership until the actual subprocess exit callback or an equivalent positive dead-PID proof and propagate rejected signals or a bounded failure otherwise. A crash-fused shared shard moves affected roots into the bounded quarantine pool, a second fused quarantine ends those watch lifetimes, interrupted setup emits overflow after recovery, metadata work stays bounded, and the SSH relay, PTYs, Git, and other filesystem operations never load the watcher native addon or share its fault boundary.", - "oracle": "Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. 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): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", + "oracle": "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. 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): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. 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): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/file-watcher-host.test.ts src/main/runtime/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts", "pnpm run build:electron-vite", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs", "node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs", @@ -13444,7 +13470,6 @@ "src/main/runtime/orca-runtime.test.ts", "src/main/runtime/rpc/methods/files/files.test.ts", "src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts", - "src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts", "src/renderer/src/web/web-runtime-client.test.ts", "src/shared/cross-platform-path.test.ts", "src/shared/physical-exit-tracker.test.ts", @@ -13585,14 +13610,6 @@ "WSL Linux-tail comparisons remain case-sensitive and relative suffix bytes remain exact" ] }, - { - "file": "src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts", - "assertions": [ - "terminal watcher error and setup failure evict the shared entry before retrying callbacks run", - "an old stream end cannot evict the replacement stream, which still delivers to its listener", - "two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch" - ] - }, { "file": "src/renderer/src/web/web-runtime-client.test.ts", "assertions": [ @@ -13757,7 +13774,7 @@ }, "redGreenEvidence": { "status": "partial", - "evidence": "Red tests reproduced the reviewed failures: IPC disconnect-before-exit orphaned existing roots, queue-admission deadlines cascaded shard replacement, a fused shard created one child per root, a standard SSH repository created three healthy watcher supervisors, destructive desktop cleanup waited indefinitely for native setup, and synchronous renderer retry joined a terminal stream. Earlier red coverage also reproduced missing-entry fail-open, terminal recovery loss, stale same-root lease deletion, and unbounded per-child stat lanes. The bounded quarantine and cancellation rewrite passes those contracts, the relay-specific healthy width test reduces the three-root case to one supervisor, and the real-supervisor built-entry harness survives SIGSEGV with automatic replacement. CI/soak history is still absent." + "evidence": "Audit2056 retires the exact deleted-source assertion alarms recorded in knownGaps; prior changed-source red/green claims are historical. Unrelated retained-source evidence keeps its original scope. Historical prior account (preserved verbatim): Red tests reproduced the reviewed failures: IPC disconnect-before-exit orphaned existing roots, queue-admission deadlines cascaded shard replacement, a fused shard created one child per root, a standard SSH repository created three healthy watcher supervisors, destructive desktop cleanup waited indefinitely for native setup, and synchronous renderer retry joined a terminal stream. Earlier red coverage also reproduced missing-entry fail-open, terminal recovery loss, stale same-root lease deletion, and unbounded per-child stat lanes. The bounded quarantine and cancellation rewrite passes those contracts, the relay-specific healthy width test reduces the three-root case to one supervisor, and the real-supervisor built-entry harness survives SIGSEGV with automatic replacement. CI/soak history is still absent." }, "performanceBudget": { "required": true, @@ -13811,7 +13828,9 @@ "Audit1973 historical original testFiles object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n\"src/main/runtime/rpc/methods/files/files-watch-cleanup.test.ts\"", "Audit1973 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/rpc/methods/files/files-watch-cleanup.test.ts\",\n \"assertions\": [\n \"a failed paired-web unwatch retries after already-resolved or late physical exit and emits stream end exactly once\"\n ]\n }", "Audit1973 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/rpc/methods/files/files.test.ts\",\n \"assertions\": [\n \"pre-ready transport abort reaches RuntimeFileCommands as the owning AbortSignal\",\n \"terminal watcher loss flushes a final overflow change before error/end and unregisters cleanup\"\n ]\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n }", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process." }, @@ -15581,7 +15600,9 @@ "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.", "Audit1991 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/runtime-legacy-worker-terminal-recovery-retry.test.ts\",\n \"assertions\": [\n \"late provider availability recovers automatically after two minutes\",\n \"ten minutes of unresolved retries never revisit settled workers or persist empty batches\",\n \"every host timer remains cancellable during extended recovery\"\n ]\n }", "Audit1991 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/runtime-legacy-worker-missing-workspace-recovery.test.ts\",\n \"assertions\": [\n \"100 deleted git or folder workspace candidates use one owning-provider inventory\",\n \"100 workers sharing a workspace resolve it once per pass; the next pass rechecks both git and folder workspaces\",\n \"live PTYs without scoped membership or verified incarnation remain deferred\",\n \"local inventory and restarted relay inventory never prove SSH worker exit\",\n \"SSH cleanup requires an explicit owning-host absence verdict; probe failures preserve uncertainty\",\n \"foreign provider identities do not start local recovery timers\"\n ]\n }", - "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed." + "Audit2052 (source2049): The ordinary orca-runtime.test.ts registrar drops seven imports of deliberately deleted low-value runtime suites. Their mock capability/agent-presence/environment/title/deduplication and batching alarms are intentionally lost without replacement; remaining imports retain their original order. The runtime handle-contract registrar separately drops the deleted tab-collision registration. Unrelated dated evidenceRuns remain unchanged and do not validate reduced-source bytes or selectors. No fresh gate execution or historical import-closure equivalence is claimed.", + "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. 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.", + "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. 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." ], "promotionCriteria": [ "Collect cross-platform and provider soak evidence with no weakened identity, transaction or bounded-work assertions." diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 87f340f60f1..6b52c88cc76 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -3953,7 +3953,6 @@ "src/main/runtime/integrations/linear/runtime-linear-write-lifetime.test.ts": 512, "src/main/runtime/workspaces/creation/runtime-local-worktree-create-pr-conflict.test.ts": 462, "src/main/runtime/workspaces/creation/runtime-local-worktree-create.test.ts": 693, - "src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.test.ts": 79, "src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata-sweep.test.ts": 1812, "src/main/runtime/workspaces/metadata/runtime-managed-worktree-metadata-wsl-move.test.ts": 1812, "src/main/runtime/workspaces/catalog/runtime-managed-worktree-queries.test.ts": 1074, @@ -4012,7 +4011,6 @@ "src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.test.ts": 1027, "src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts": 289, "src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts": 1412, - "src/main/runtime/workspaces/startup/runtime-worktree-terminal-provisioning.test.ts": 84, "src/main/runtime/serve-browser-tabs-layout-owner.test.ts": 321, "src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts": 5010, "src/main/runtime/session-lifecycle/close/close-mobile-row-in-main-layout.test.ts": 4514, @@ -4174,10 +4172,8 @@ "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-daemon-inventory.test.ts": 463, "src/main/runtime/workspaces/removal/worktree-teardown-unstopped-pty.test.ts": 419, "src/main/runtime/workspaces/removal/worktree-teardown.test.ts": 862, - "src/main/runtime/workspaces/sleep/worktree-terminal-sleep-host-twin.test.ts": 4345, "src/main/runtime/wsl-distro-loss-exit-retention.test.ts": 5519, "src/main/runtime/wsl-guest-drive-mountinfo.test.ts": 38, "src/main/runtime/wsl-host-agent-launch-paths.test.ts": 4079, @@ -4285,13 +4281,11 @@ "src/main/source-control/hosted-review-branch-cache.test.ts": 205, "src/main/source-control/hosted-review-creation-eligibility.test.ts": 549, "src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts": 500, - "src/main/source-control/hosted-review-creation-shared-symlinks.test.ts": 503, "src/main/source-control/hosted-review-creation.test.ts": 574, "src/main/source-control/hosted-review-execution-host-routing.test.ts": 478, "src/main/source-control/hosted-review-gitea.integration.test.ts": 1304, "src/main/source-control/hosted-review-inflight-invalidation.test.ts": 188, "src/main/source-control/hosted-review-inflight-lookups.test.ts": 44, - "src/main/source-control/hosted-review-project-account.test.ts": 543, "src/main/source-control/hosted-review.test.ts": 555, "src/main/source-control/repo-default-branch.test.ts": 139, "src/main/source-control/repo-remote-head-branch.test.ts": 147, @@ -4369,7 +4363,6 @@ "src/main/ssh/legacy-relay/legacy-relay-target-bridge.test.ts": 167, "src/main/ssh/legacy-relay/orcad-migration-bridged-panes.test.ts": 322, "src/main/ssh/legacy-relay/ssh-host-relay-census-for-target.test.ts": 53, - "src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.test.ts": 111, "src/main/ssh/legacy-relay/ssh-host-relay-windows-census.test.ts": 232, "src/main/ssh/legacy-relay/ssh-host-relay-windows-inventory.test.ts": 178, "src/main/ssh/legacy-relay/ssh-host-relay-windows-pipe-access.test.ts": 211, @@ -4411,7 +4404,6 @@ "src/main/ssh/orcad-remote-deploy.test.ts": 537, "src/main/ssh/orcad-retained-fence-takeover.test.ts": 210, "src/main/ssh/orcad-retained-source-changes.test.ts": 2185, - "src/main/ssh/orcad-retained-source-lists.test.ts": 426, "src/main/ssh/orcad-runtime-maintenance.test.ts": 916, "src/main/ssh/orcad-snapshot-room.test.ts": 402, "src/main/ssh/orcad-stdio-bridge.test.ts": 627, @@ -4507,7 +4499,6 @@ "src/main/startup/browser-process-user-agent-ordering.test.ts": 3231, "src/main/startup/cli-launch-redirect.test.ts": 128, "src/main/startup/codex-account-restart-resume.test.ts": 465, - "src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts": 204, "src/main/startup/codex-session-resume-daemon-guard.test.ts": 161, "src/main/startup/configure-process-dev-parent-shutdown.test.ts": 182, "src/main/startup/configure-process-macports-path.test.ts": 159, @@ -4542,7 +4533,6 @@ "src/main/startup/profile-state-recovery-preflight.test.ts": 696, "src/main/startup/profile-state-save-delay.test.ts": 45, "src/main/startup/profile-state-write-failure.test.ts": 487, - "src/main/startup/run-electron-vite-dev-web.test.ts": 756, "src/main/startup/run-electron-vite-dev.test.ts": 944, "src/main/startup/serve-desktop-activation.test.ts": 42, "src/main/startup/serve-mode-argv.test.ts": 85, @@ -4605,7 +4595,6 @@ "src/main/text-generation/jira-issue-summary-requests.test.ts": 276, "src/main/text-generation/jira-issue-summary-text-generation.test.ts": 543, "src/main/text-generation/kimi-generation-failure.test.ts": 151, - "src/main/text-generation/pull-request-context-errors.test.ts": 78, "src/main/text-generation/pull-request-context.test.ts": 97, "src/main/text-generation/source-control-agent-cli-path.test.ts": 615, "src/main/text-generation/source-control-agent-launch.test.ts": 1879, @@ -4639,7 +4628,6 @@ "src/main/updater/updater.prerelease-fallback.test.ts": 2731, "src/main/updater/updater.publishing-window-feed.test.ts": 2992, "src/main/updater/updater.quit-and-install.test.ts": 2296, - "src/main/updater/updater.startup-scheduling.test.ts": 1326, "src/main/updater/updater.wsl-move-install-hold-driver.test.ts": 3175, "src/main/updater/mac-install/mac-browser-sidecar-recovery.test.ts": 87, "src/main/updater/lifecycle/serve-supervisor-install-park.test.ts": 173, @@ -4659,7 +4647,6 @@ "src/main/usage/usage-provider-store-initialization.test.ts": 586, "src/main/usage/usage-provider-store-lifecycle.test.ts": 769, "src/main/usage/usage-scan-worker-cache-cleanup.test.ts": 153, - "src/main/usage/usage-scan-worker-client.test.ts": 107, "src/main/usage/usage-source-cache-file.test.ts": 94, "src/main/usage/usage-worktree-resolver.test.ts": 269, "src/main/warp-themes/discovery.test.ts": 58, @@ -4763,20 +4750,16 @@ "src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts": 393, "src/main/workspaces/removal/worktree-failed-removal.test.ts": 749, "src/main/workspaces/catalog/worktree-identity-persistence.test.ts": 1994, - "src/main/workspaces/catalog/worktree-lineage-pruning.test.ts": 524, - "src/main/workspaces/removal/retirement/worktree-name-retirement.test.ts": 401, "src/main/workspaces/catalog/worktree-path-comparison-key.test.ts": 227, "src/main/workspaces/creation/preparation/worktree-preparation-discard-retry.test.ts": 357, "src/main/workspaces/creation/preparation/worktree-preparation-fetch-barrier.test.ts": 439, "src/main/workspaces/creation/preparation/worktree-preparation-tip-refresh.test.ts": 574, "src/main/workspaces/removal/worktree-removal-close-records.test.ts": 1941, - "src/main/workspaces/removal/worktree-removal-home-guard.test.ts": 90, "src/main/workspaces/removal/worktree-removal-safety.test.ts": 290, "src/main/workspaces/removal/worktree-removal-session-partition-fencing.test.ts": 2627, "src/main/workspaces/removal/retirement/worktree-retirement-backfill-scan.test.ts": 55, "src/main/workspaces/removal/retirement/worktree-retirement-backfill-stall.test.ts": 365, "src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts": 355, - "src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts": 345, "src/main/workspaces/removal/retirement/worktree-retirement-namespace.test.ts": 235, "src/main/workspaces/creation/worktree-root-preparation.test.ts": 180, "src/main/workspaces/removal/worktree-trash.test.ts": 126, @@ -4803,12 +4786,10 @@ "src/main/wsl/discovery/wsl-distro-holder-script.test.ts": 28870, "src/main/wsl/discovery/wsl-distro-holder.test.ts": 328, "src/main/wsl/discovery/wsl-distro-registry-id.test.ts": 77, - "src/main/wsl/filesystem/wsl-drive-project-windows-git.test.ts": 249, "src/main/wsl/filesystem/wsl-drive-unc-conversion-renderer.test.ts": 123, "src/main/wsl/filesystem/wsl-drive-unc-conversion-run.test.ts": 621, "src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.test.ts": 1265, "src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.test.ts": 123, - "src/main/wsl/filesystem/wsl-drive-unc-project-scope.test.ts": 123, "src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.test.ts": 299, "src/main/wsl/execution/wsl-executable-path.win32.test.ts": 38, "src/main/wsl/execution/wsl-guest-environment.test.ts": 120, @@ -4816,7 +4797,6 @@ "src/main/wsl/execution/wsl-guest-pane-processes.test.ts": 48, "src/main/wsl/execution/wsl-guest-process-identity.test.ts": 54, "src/main/wsl/host-lifecycle/wsl-host-automation-wake.test.ts": 288, - "src/main/wsl/host-lifecycle/wsl-host-connector.test.ts": 826, "src/main/wsl/host-lifecycle/wsl-host-gate.test.ts": 156, "src/main/wsl/host-lifecycle/wsl-host-kept-for-peers.test.ts": 159, "src/main/wsl/host-lifecycle/wsl-host-pending-removal.test.ts": 955, @@ -4825,10 +4805,8 @@ "src/main/wsl/host-lifecycle/wsl-host-service.test.ts": 1436, "src/main/wsl/host-lifecycle/wsl-host-uninstall-server-stop.test.ts": 751, "src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.test.ts": 239, - "src/main/wsl/execution/wsl-interop-health.test.ts": 234, "src/main/wsl/execution/wsl-interop-registration.test.ts": 52, "src/main/wsl/execution/wsl-node-runtime-prefetch.test.ts": 102, - "src/main/wsl/orcad/wsl-orcad-account-env.test.ts": 117, "src/main/wsl/orcad/wsl-orcad-active-probe.test.ts": 347, "src/main/wsl/orcad/wsl-orcad-bridge-activity.test.ts": 668, "src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.test.ts": 392, @@ -4839,7 +4817,6 @@ "src/main/wsl/orcad/wsl-orcad-host-environments.test.ts": 47, "src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts": 312, "src/main/wsl/orcad/wsl-orcad-host-transport.test.ts": 272, - "src/main/wsl/orcad/wsl-orcad-incumbent.test.ts": 529, "src/main/wsl/orcad/wsl-orcad-instance-adoption.test.ts": 273, "src/main/wsl/orcad/wsl-orcad-liveness-building-blocks.test.ts": 132, "src/main/wsl/orcad/wsl-orcad-liveness-supervisor.test.ts": 249, @@ -6162,7 +6139,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/startup/launch-parity-window-tab.test.ts": 17426, "src/renderer/src/components/terminal-pane/layout-serialization.test.ts": 109, "src/renderer/src/components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-transport.test.ts": 358, - "src/renderer/src/components/terminal-pane/snapshots/merge-captured-leaf-state.test.ts": 45, "src/renderer/src/components/terminal-pane/session-restore/newer-daemon/newer-daemon-hold-banner.test.tsx": 477, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts": 1040, "src/renderer/src/components/terminal-pane/pty-connection/agent-identity/foreground-process/pane-delayed-agent-startup.test.ts": 285, @@ -6217,14 +6193,12 @@ "src/renderer/src/components/terminal-pane/pty-connection/output/foreground-renderer-risk-scan-tail.test.ts": 111, "src/renderer/src/components/terminal-pane/pty-connection/spawn/hidden-agent-resume-deferral.test.ts": 55, "src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold-wiring.test.ts": 2484, - "src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts": 47, "src/renderer/src/components/terminal-pane/pty-connection/startup/main-pane-resume-banner.test.ts": 59, "src/renderer/src/components/terminal-pane/pty-connection/spawn/main-pane-start-wait.test.ts": 76, "src/renderer/src/components/terminal-pane/pty-connection/serialization/pane-serializer-register.test.ts": 123, "src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-kitty-file-reader.test.ts": 297, "src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts": 1882, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/snapshot-covered-terminal-queries.test.ts": 150, - "src/renderer/src/components/terminal-pane/pty-transport/host-ownership/ssh-session-gone-verdict.test.ts": 46, "src/renderer/src/components/terminal-pane/pty-connection/output/terminal-input-echo-delay.test.ts": 132, "src/renderer/src/components/terminal-pane/pty-connection/spawn/unbound-pane-spawn-recovery.test.ts": 53, "src/renderer/src/components/terminal-pane/pty-connection/host-ownership/unserved-ssh-pane-bridge.test.ts": 70, @@ -6237,14 +6211,11 @@ "src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-processor-program-activity.test.ts": 160, "src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-reentrancy.test.ts": 49, "src/renderer/src/components/terminal-pane/pty-transport/output/pty-output-side-effect-queue-retention.test.ts": 117, - "src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-pre-handler-buffer-warn-eviction.test.ts": 65, "src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-pre-handler-buffer.test.ts": 89, "src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts": 77, "src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-retention.test.ts": 86, - "src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-renderer-delivery-claims.test.ts": 64, "src/renderer/src/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension.test.ts": 60, "src/renderer/src/components/terminal-pane/pty-transport/shutdown/pty-shutdown-exit-deferral.test.ts": 121, - "src/renderer/src/components/terminal-pane/pty-transport/shutdown/pty-shutdown-output-queue.test.ts": 790, "src/renderer/src/components/terminal-pane/pty-transport/output/pty-side-effect-pending-census.test.ts": 152, "src/renderer/src/components/terminal-pane/viewport/pty-size-reassertion.test.ts": 58, "src/renderer/src/components/terminal-pane/viewport/pty-size-reconcile.test.ts": 68, @@ -6259,10 +6230,8 @@ "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, - "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts": 640, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-user-input.test.ts": 953, "src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.test.ts": 208, - "src/renderer/src/components/terminal-pane/viewport/remote-desktop-viewport-claim.test.ts": 45, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/remote-hidden-output-restore-outcomes.test.ts": 2794, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/remote-hidden-output-restore-unavailable-banner.repro.test.ts": 2355, "src/renderer/src/components/terminal-pane/layout/persistence/remote-pane-layout-push.test.ts": 77, @@ -6270,7 +6239,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/geometry/remote-reconnect-unimaged-pane-redraw.test.ts": 3122, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-connect-failure-recovery.test.ts": 989, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-disconnected-input-grace-retry.test.ts": 1366, - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-error-surface-dismissal.test.ts": 956, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/input/remote-runtime-input-journal.test.ts": 69, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-outage-toast-flood-and-stuck-reconnect.test.ts": 1269, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts": 108, @@ -6286,7 +6254,6 @@ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-end-verdict.test.ts": 942, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts": 1763, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-healthy-link-reattach.test.ts": 1595, - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-absence-evidence.test.ts": 737, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-exit-record.test.ts": 4078, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts": 2248, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts": 4276, @@ -6316,13 +6283,11 @@ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-resubscribe-failure-recovery-routing.test.ts": 1896, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-saved-result-consumer.test.ts": 3650, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-ssh-sign-in-recovery.test.ts": 6038, - "src/renderer/src/components/terminal-pane/pty-transport/recovery/server-outage/remote-server-notice-claims.test.tsx": 276, "src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts": 31916, "src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-replay.test.ts": 3010, "src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-history-seam.test.ts": 2093, "src/renderer/src/components/terminal-pane/snapshots/replay-guard.test.ts": 371, "src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts": 56, - "src/renderer/src/components/terminal-pane/pty-transport/ipc/scan22-ssh-new-tab-disposed-spawn-kill.repro.test.ts": 577, "src/renderer/src/components/terminal-pane/viewport/split-right-white-screen.test.ts": 53, "src/renderer/src/components/terminal-pane/viewport/visibility/stale-document-visibility.test.ts": 88, "src/renderer/src/components/terminal-pane/input/paste/terminal-agent-paste-bracketing.test.ts": 329, @@ -6385,7 +6350,6 @@ "src/renderer/src/components/terminal-pane/links/files/terminal-link-same-id-ssh-file-host.test.ts": 879, "src/renderer/src/components/terminal-pane/layout/reconciliation/terminal-live-layout-reconciliation.test.ts": 74, "src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts": 52, - "src/renderer/src/components/terminal-pane/pty-transport/output/terminal-output-visibility.test.ts": 44, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-pane-element-file-drop.test.tsx": 1748, "src/renderer/src/components/terminal-pane/layout/reconciliation/terminal-pane-frame-reconciliation.test.ts": 903, "src/renderer/src/components/terminal-pane/host-state/terminal-pane-host-state-memo.test.ts": 4534, @@ -6420,16 +6384,13 @@ "src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts": 1669, "src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts": 48, "src/renderer/src/components/terminal-pane/links/files/terminal-worktree-path-link.test.ts": 1878, - "src/renderer/src/components/terminal-pane/snapshots/use-host-terminal-scrollback-hold.test.ts": 256, "src/renderer/src/components/terminal-pane/mobile-driver/use-mobile-overlay-ticks-desktop-fit.test.tsx": 371, - "src/renderer/src/hooks/theme/use-system-prefers-dark.test.ts": 40, "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-pane-global-effects-visibility-resume.test.ts": 1951, "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-pane-global-effects-window-focus-recovery.test.ts": 1836, "src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts": 1806, "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-scroll-visibility-memory.test.ts": 79, "src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts": 752, "src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-window-wake-recovery.test.ts": 494, - "src/renderer/src/lib/wsl-host-availability.test.ts": 1885, "src/renderer/src/components/terminal-pane/links/http/wrapped-terminal-http-link-limits.test.ts": 108, "src/renderer/src/components/terminal-pane/links/http/wrapped-terminal-http-link-provider.test.ts": 606, "src/renderer/src/components/terminal-parked-watcher-sync-entries.test.tsx": 1104, @@ -6446,7 +6407,6 @@ "src/renderer/src/components/terminal/cold-activation-deferral-stranding.test.ts": 2149, "src/renderer/src/components/terminal/initial-terminal-admission-wait.test.tsx": 2444, "src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx": 786, - "src/renderer/src/components/terminal/pty-running-work-probe-child-evidence.test.ts": 56, "src/renderer/src/components/terminal/running-terminal-close-guard.test.ts": 99, "src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts": 2118, "src/renderer/src/components/terminal/tab-type-cycle.test.ts": 60, @@ -6469,7 +6429,6 @@ "src/renderer/src/components/use-jira-project-inventory.test.tsx": 358, "src/renderer/src/components/use-quick-open-interaction.test.tsx": 1987, "src/renderer/src/components/use-task-creation-draft-retention.test.ts": 3185, - "src/renderer/src/components/use-terminal-browser-retention.test.tsx": 395, "src/renderer/src/components/use-terminal-bulk-close-actions.frame-flush.test.tsx": 2300, "src/renderer/src/components/use-terminal-create-actions.test.tsx": 302, "src/renderer/src/components/use-terminal-editor-close-foundation.window-close.test.tsx": 2105, @@ -6535,12 +6494,10 @@ "src/renderer/src/hooks/editor-runtime-file-watch.test.ts": 58, "src/renderer/src/hooks/installed-agent-skill-discovery-cache.test.ts": 53, "src/renderer/src/hooks/installed-agent-skill-discovery.test.ts": 74, - "src/renderer/src/hooks/installed-agent-skill-runtime-eviction.test.ts": 54, "src/renderer/src/hooks/ipc-events/agent-status-pane-routing-index-retention.test.ts": 4878, "src/renderer/src/hooks/ipc-events/agent-status-pending-retry-gate.test.ts": 466, "src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts": 2247, "src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.owner.test.ts": 623, - "src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.profile-switch.test.ts": 570, "src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.split.test.ts": 699, "src/renderer/src/hooks/ipc-events/browser-state-open-link-profile.test.ts": 934, "src/renderer/src/hooks/ipc-events/direct-ssh-hydration-fanout.test.ts": 1825, @@ -6566,7 +6523,6 @@ "src/renderer/src/hooks/ipc-events/wsl-host-ipc-bridge-capability.test.ts": 1917, "src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts": 797, "src/renderer/src/hooks/ipc-tab-switch.test.ts": 839, - "src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts": 57, "src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts": 52, "src/renderer/src/hooks/metadata-request-cache.test.ts": 144, "src/renderer/src/hooks/programmatic-scroll-marks.test.ts": 47, @@ -6664,8 +6620,6 @@ "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-pane-age.test.ts": 41, "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-planner.test.ts": 341, "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-runtime-liveness-race.test.ts": 1914, - "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-twin-host.test.ts": 1711, - "src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts": 2056, "src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-permissions.test.ts": 1267, "src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-prompt-transport.test.ts": 1326, "src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts": 1266, @@ -6756,7 +6710,6 @@ "src/renderer/src/lib/emulator-error-copy.test.ts": 415, "src/renderer/src/lib/ensure-hooks-confirmed.test.ts": 799, "src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts": 3601, - "src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts": 40, "src/renderer/src/lib/execute-open-editor-path-move.test.ts": 2458, "src/renderer/src/lib/execution-host-facts.test.ts": 1796, "src/renderer/src/lib/feature-education-telemetry.test.ts": 52, @@ -6808,7 +6761,6 @@ "src/renderer/src/lib/linked-work-item-context.test.ts": 64, "src/renderer/src/lib/monaco-editor-gutter-disposal.test.ts": 295, "src/renderer/src/lib/monaco-languages/markdown-heading-outline.test.ts": 70, - "src/renderer/src/lib/monaco-languages/markdown-textmate-tokens.test.ts": 364, "src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts": 697, "src/renderer/src/lib/monaco-languages/plugin-grammar-tokenization.test.ts": 282, "src/renderer/src/lib/monaco-languages/plugin-grammar-worker-client.test.ts": 198, @@ -6897,7 +6849,6 @@ "src/renderer/src/lib/paste-payload-metadata.test.ts": 53, "src/renderer/src/lib/path-head-elision.test.ts": 53, "src/renderer/src/lib/path.test.ts": 55, - "src/renderer/src/lib/pending-worktree-creation.test.ts": 222, "src/renderer/src/lib/plugin-command-keybindings.test.ts": 1909, "src/renderer/src/lib/plugin-command-replacements.test.ts": 95, "src/renderer/src/lib/plugin-icons/plugin-icon-svg.test.ts": 231, @@ -6941,7 +6892,6 @@ "src/renderer/src/lib/session-write-subscriber-acknowledgment.test.ts": 1823, "src/renderer/src/lib/session-write-subscriber-allocation.test.ts": 427, "src/renderer/src/lib/session-write-subscriber.test.ts": 1882, - "src/renderer/src/lib/settled-worker-wake-policy.test.ts": 1787, "src/renderer/src/lib/setup-split-activation-single-owner.test.ts": 2324, "src/renderer/src/lib/shutdown-checkpoint-guard.test.ts": 209, "src/renderer/src/lib/sidebar-ended-creations.test.ts": 1889, @@ -6973,7 +6923,6 @@ "src/renderer/src/lib/text-control-paste.test.ts": 222, "src/renderer/src/lib/text-generation-error-copy.test.ts": 466, "src/renderer/src/lib/typing-latency/echo-instrumentation.test.ts": 145, - "src/renderer/src/lib/typing-latency/input-events.test.ts": 189, "src/renderer/src/lib/typing-latency/renderer-long-tasks.test.ts": 75, "src/renderer/src/lib/typing-latency/sample-window.test.ts": 77, "src/renderer/src/lib/unread-badge-count-selector.test.ts": 1930, @@ -6987,7 +6936,6 @@ "src/renderer/src/lib/windows-terminal-capabilities-race.test.ts": 450, "src/renderer/src/lib/windows-terminal-capabilities.test.ts": 585, "src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts": 198, - "src/renderer/src/lib/worker-auto-close.test.ts": 387, "src/renderer/src/lib/workspace-activation-path-gate.test.ts": 2107, "src/renderer/src/lib/browser/workspace/workspace-browser-tab-open-placement.test.ts": 1996, "src/renderer/src/lib/workspace-doc-address-input.test.ts": 470, @@ -7004,7 +6952,6 @@ "src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts": 2295, "src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts": 3630, "src/renderer/src/lib/workspace/activation/worktree-activation-launch-awaiting-host.test.ts": 2161, - "src/renderer/src/lib/workspace/activation/worktree-activation-leave-visit.test.ts": 2037, "src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts": 2043, "src/renderer/src/lib/workspace/activation/worktree-activation-web-runtime.test.ts": 2768, "src/renderer/src/lib/workspace/activation/worktree-agent-activation-seam.test.ts": 3440, @@ -7065,7 +7012,6 @@ "src/renderer/src/runtime/rpc/environment-revisions/runtime-environment-pairing-refresh.test.ts": 109, "src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts": 1810, "src/renderer/src/runtime/files/search/runtime-file-client-search-listing.test.ts": 577, - "src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts": 497, "src/renderer/src/runtime/files/reads/runtime-file-client.test.ts": 582, "src/renderer/src/runtime/files/imports/runtime-file-import-pairing-revision.test.ts": 471, "src/renderer/src/runtime/files/reads/runtime-file-range-client.test.ts": 444, @@ -7118,7 +7064,6 @@ "src/renderer/src/runtime/web-session-open-files-batch-equivalence.test.ts": 1478, "src/renderer/src/runtime/web-session-restored-placeholder-identity.test.ts": 985, "src/renderer/src/runtime/web-session-tabs-agent-completion-notifications.test.ts": 1953, - "src/renderer/src/runtime/web-session-tabs-late-merged-predecessor-lockout.test.ts": 779, "src/renderer/src/runtime/web-session-tabs-removed-frame-retires-live-publisher.test.ts": 854, "src/renderer/src/runtime/web-session-tabs-stream-end-resubscribe.test.tsx": 2282, "src/renderer/src/runtime/web-session-tabs-sync-agent-status.test.ts": 987, @@ -7145,7 +7090,6 @@ "src/renderer/src/runtime/hosted-terminals/recovery/inventory/web-session-terminal-orphan-absence-across-republication.test.ts": 678, "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts": 923, "src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-adoption-regressions.test.ts": 1214, - "src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-prior-removal.test.ts": 709, "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts": 1029, "src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-sleep.test.ts": 1066, "src/renderer/src/runtime/hosted-terminals/recovery/surfaces/web-session-terminal-orphan-recovery-topology-fence.test.ts": 868, @@ -7153,7 +7097,6 @@ "src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts": 723, "src/renderer/src/runtime/hosted-terminals/recovery/evidence/web-session-terminal-retirement-proof-ledger.test.ts": 685, "src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking-stream-end.test.ts": 225, - "src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking.test.ts": 255, "src/renderer/src/runtime/workspace-layout-frame-binding.test.ts": 2155, "src/renderer/src/runtime/workspace-layout-frame-editor-views.test.ts": 2098, "src/renderer/src/runtime/workspace-layout-frame-held-tabs.test.ts": 2519, @@ -7165,7 +7108,6 @@ "src/renderer/src/startup/startup-ssh-connection-restore.test.ts": 71, "src/renderer/src/store/slices/editor/buffers/editor-buffer-record-lifecycle.test.ts": 1794, "src/renderer/src/store/folder-workspaces/folder-path-status-ownership.test.ts": 1809, - "src/renderer/src/store/github/checks/check-actions-errors.test.ts": 520, "src/renderer/src/store/github/checks/check-details-failure-mapping.test.ts": 887, "src/renderer/src/store/github/projects/project-field-mutations.test.ts": 2100, "src/renderer/src/store/github/requests/provider-request-coalescing.test.ts": 969, @@ -7278,7 +7220,6 @@ "src/renderer/src/store/github/pull-requests/github-pr-host-scope.test.ts": 1030, "src/renderer/src/store/github/refresh/github-pr-manual-refresh-broadcast.test.ts": 693, "src/renderer/src/store/github/refresh/github-pr-refresh-states-leak.test.ts": 1327, - "src/renderer/src/store/github/repositories/github-pr-refresh-wsl-host-off.test.ts": 791, "src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts": 1458, "src/renderer/src/store/github/projects/github-project-view-tables.test.ts": 656, "src/renderer/src/store/github/repositories/github-repo-lookup-index.test.ts": 51, @@ -7341,7 +7282,6 @@ "src/renderer/src/store/slices/settings/settings-owner-hydration-write-fence.test.ts": 1860, "src/renderer/src/store/slices/settings/settings-terminal-quick-commands.test.ts": 1734, "src/renderer/src/store/slices/settings/settings.test.ts": 1938, - "src/renderer/src/store/repos/sparse-presets-repo-removal-purge-leak.test.ts": 1612, "src/renderer/src/store/slices/worktrees/create/sparse-presets.test.ts": 217, "src/renderer/src/store/slices/ssh/ssh.test.ts": 1843, "src/renderer/src/lib/active-worktree-removal-successor.test.ts": 1867, @@ -7450,7 +7390,6 @@ "src/renderer/src/store/slices/worktrees/teardown/worktree-delete-state.test.ts": 1160, "src/renderer/src/store/repos/wsl-moved-project-chat-purge.test.ts": 1222, "src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts": 67, - "src/renderer/src/store/terminals/legacy-relay-bridged-tab-close.test.ts": 310, "src/renderer/src/store/terminals/restored-relay-session-identity.test.ts": 2196, "src/renderer/src/store/terminals/restored-terminal-rebind-restarts.test.ts": 1886, "src/renderer/src/store/terminals/structured-chat-tab-rename.test.ts": 3154, @@ -7462,7 +7401,6 @@ "src/renderer/src/store/slices/runtime-status/views/use-runtime-status-view.test.tsx": 1979, "src/renderer/src/store/workspace-layout/workspace-layout-cache.test.ts": 63, "src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.test.ts": 2284, - "src/renderer/src/store/workspaces/selection/workspace-host-target.test.ts": 93, "src/renderer/src/store/slices/worktrees/listing/worktree-host-collision-index.test.ts": 1875, "src/renderer/src/web/preload-api/web-agent-session-attachment-upload.test.ts": 1588, "src/renderer/src/web/preload-api/web-chat-permission-normalization.test.ts": 293, diff --git a/src/main/github/pr-refresh-coordinator-watch.test.ts b/src/main/github/pr-refresh-coordinator-watch.test.ts deleted file mode 100644 index c6345bc6042..00000000000 --- a/src/main/github/pr-refresh-coordinator-watch.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) - -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' - -const { getPRForBranchOutcomeMock } = coordinatorMocks -const WATCHED = '/watched-repo' -// Fake time starts here; reads stamp `fetchedAt` from the fake clock as it advances. -const START_AT = 1_000 - -function watchReads(): number { - return getPRForBranchOutcomeMock.mock.calls.filter(([repoPath]) => repoPath === WATCHED).length -} - -async function startWatch(): Promise { - const { schedulePRWatchRead, setPRWatchJobHooks } = await import('./pr-refresh-coordinator') - setPRWatchJobHooks({ isWatched: () => true, readHeadChecks: async () => null }) - schedulePRWatchRead( - { prKey: 'github.com/acme/watched#7' }, - makeCandidate({ repoPath: WATCHED, cacheKey: 'watch', linkedPRNumber: 7 }), - START_AT - ) -} - -describe('pr-refresh watch jobs', () => { - beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - vi.setSystemTime(START_AT) - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'found', - pr: makePR({ checksStatus: 'pending' }), - fetchedAt: Date.now() - })) - }) - - it('re-reads an open PR every background interval with no window showing it', async () => { - await startWatch() - await vi.advanceTimersByTimeAsync(0) - expect(watchReads()).toBe(1) - await vi.advanceTimersByTimeAsync(119_000) - expect(watchReads()).toBe(1) - await vi.advanceTimersByTimeAsync(2_000) - expect(watchReads()).toBe(2) - await vi.advanceTimersByTimeAsync(10 * 120_000) - expect(watchReads()).toBe(12) - }) - - it('stops once the PR is merged with its checks settled', async () => { - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'found', - pr: makePR({ - state: 'merged', - checksStatus: 'success', - checksReadComplete: true, - checksFinal: true - }), - fetchedAt: Date.now() - })) - await startWatch() - await vi.advanceTimersByTimeAsync(60 * 60_000) - expect(watchReads()).toBe(1) - }) - - it('keeps reading a merged PR whose failure sits beside a check still running', async () => { - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'found', - pr: makePR({ - state: 'merged', - checksStatus: 'failure', - checksReadComplete: true, - checksFinal: false - }), - fetchedAt: Date.now() - })) - await startWatch() - await vi.advanceTimersByTimeAsync(5 * 60_000) - expect(watchReads()).toBeGreaterThan(1) - }) - - it('gives saturating watches and visible rows each a share of the budget', async () => { - const { reportVisiblePRRefreshCandidates, schedulePRWatchRead, setPRWatchJobHooks } = - await import('./pr-refresh-coordinator') - setPRWatchJobHooks({ isWatched: () => true, readHeadChecks: async () => null }) - for (let index = 0; index < 25; index++) { - schedulePRWatchRead( - { prKey: `github.com/acme/watched#${index}` }, - makeCandidate({ repoPath: `${WATCHED}-${index}`, cacheKey: `watch-${index}` }), - START_AT - ) - } - reportVisiblePRRefreshCandidates( - Array.from({ length: 25 }, (_, index) => - makeCandidate({ - repoPath: `/visible-${index}`, - cacheKey: `visible-${index}`, - worktreeId: `wt-${index}` - }) - ), - 1, - 1 - ) - const counts = () => { - const paths = getPRForBranchOutcomeMock.mock.calls.map(([path]) => String(path)) - return { - watch: paths.filter((path) => path.startsWith(WATCHED)).length, - visible: paths.filter((path) => path.startsWith('/visible-')).length - } - } - await vi.advanceTimersByTimeAsync(15 * 60_000) - const early = counts() - await vi.advanceTimersByTimeAsync(30 * 60_000) - const late = counts() - // Past the first passes both kinds stay overdue; each must still get starts. - expect(late.watch - early.watch).toBeGreaterThanOrEqual(20) - expect(late.visible - early.visible).toBeGreaterThanOrEqual(20) - }) - - it('shares the background budget and still reads a watch while visible rows saturate it', async () => { - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - const visible = Array.from({ length: 30 }, (_, index) => - makeCandidate({ - repoPath: `/visible-${index}`, - cacheKey: `visible-${index}`, - worktreeId: `wt-${index}` - }) - ) - reportVisiblePRRefreshCandidates(visible, 1, 1) - await startWatch() - await vi.advanceTimersByTimeAsync(5 * 60_000 - 1_000) - // Twenty background starts per five minutes, watch reads included. - expect(getPRForBranchOutcomeMock.mock.calls.length).toBeLessThanOrEqual(20) - await vi.advanceTimersByTimeAsync(10 * 60_000) - // Aged past one interval, the watch outranks the visible rows that keep the budget full. - expect(watchReads()).toBeGreaterThanOrEqual(2) - }) - - it('bounds the check pages of watch reads only, never a visible read', async () => { - const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') - await startWatch() - reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) - await vi.advanceTimersByTimeAsync(30_000) - const options = (repoPath: string) => - getPRForBranchOutcomeMock.mock.calls.find(([path]) => path === repoPath)?.[5] - expect(watchReads()).toBe(1) - expect(options(WATCHED)).toMatchObject({ checkPageLimit: 10 }) - expect(options('/repo')?.checkPageLimit).toBeUndefined() - }) -}) diff --git a/src/main/github/pr-watch/pr-chat-action-recorder.test.ts b/src/main/github/pr-watch/pr-chat-action-recorder.test.ts index 920fc920da2..7aefc97dac9 100644 --- a/src/main/github/pr-watch/pr-chat-action-recorder.test.ts +++ b/src/main/github/pr-watch/pr-chat-action-recorder.test.ts @@ -64,36 +64,11 @@ describe('push updates from recorded tool calls', () => { expect(pushedBranches(codex)).toEqual([{ branch: 'ci-lines', newSha: '5d6e7f8' }]) }) - it('reads a push that merges its stderr into the output, and still skips a dry run', () => { - expect(pushBy('git push -u origin HEAD 2>&1', REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) - expect(pushBy('git push --dry-run 2>&1', REVIEW_PUSHED)).toEqual([]) - }) - it("reads a push after a heredoc's declaration, past `;`", () => { const command = "cat <<'EOF' > notes.md; git push -u origin HEAD 2>&1\nnotes\nEOF" expect(pushBy(command, REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) }) - it("reads a push after a heredoc's declaration, past `&&`", () => { - const command = "cat <<'EOF' > notes.md && git push -u origin HEAD 2>&1\nnotes\nEOF" - expect(pushBy(command, REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) - }) - - it("reads an unredirected push after a heredoc's declaration", () => { - const command = "cat <<'EOF' > notes.md; git push -u origin HEAD\nnotes\nEOF" - expect(pushBy(command, REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) - }) - - it("reads a piped push after a heredoc's declaration", () => { - const command = "cat <<'EOF' > notes.md && git push -u origin HEAD 2>&1 | tail -5\nnotes\nEOF" - expect(pushBy(command, REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) - }) - - it("skips a quoted dry run after a heredoc's declaration", () => { - const command = "cat <<'EOF' > notes.md; git push '--dry-run' -u origin HEAD 2>&1\nnotes\nEOF" - expect(pushBy(command, REVIEW_PUSHED)).toEqual([]) - }) - it('takes nothing from a heredoc that prints a push and its update lines', () => { const printed = 'git push -u origin HEAD 2>&1\nTo github.com:acme/repo.git\n 1234567..89abcde HEAD -> review\n' @@ -104,55 +79,9 @@ describe('push updates from recorded tool calls', () => { expect(pushBy(`cat <<-EOF\n${indented}\tEOF`, printed)).toEqual([]) }) - it("reads a push after a heredoc's delimiter", () => { - const command = "cat <<'EOF' > notes.md\nnotes\nEOF\ngit push -u origin HEAD 2>&1" - expect(pushBy(command, REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) - }) - it("doesn't let an escaped `>` before a real pipe hide the push after it", () => { expect(pushBy('printf x \\>|git push origin HEAD', REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) }) - - it('takes new branches and porcelain lines, and nothing from pushes that updated nothing', () => { - const push = (command: string, output: string) => - pushedBranches(toolCallRow({ name: 'Bash', input: { command }, output })) - expect( - push( - 'git push -u origin feature', - "remote: Create a pull request for 'feature' on GitHub by visiting:\nTo github.com:acme/repo.git\n * [new branch] feature -> feature\n" - ) - ).toEqual([{ branch: 'feature', newSha: null }]) - expect( - push( - 'git push --porcelain', - 'To github.com:acme/repo.git\n \trefs/heads/feature:refs/heads/feature\t8d5f74b..c512e75\nDone\n' - ) - ).toEqual([{ branch: 'feature', newSha: 'c512e75' }]) - expect( - push( - 'git push', - 'To github.com:acme/repo.git\n ! [rejected] feature -> feature (fetch first)\n' - ) - ).toEqual([]) - expect(push('git push', 'Everything up-to-date\n')).toEqual([]) - expect(push('git push -q', '')).toEqual([]) - // Dry runs print real-looking updates however the option is written. - for (const command of ["git push origin feature '--dry-run'", 'git push -nv origin feature']) { - expect(push(command, `${TO_ORIGIN} 8d5f74b..c512e75 feature -> feature\n`)).toEqual([]) - } - expect( - push( - 'git push --dry-run', - 'To github.com:acme/repo.git\n 8d5f74b..c512e75 feature -> feature\n' - ) - ).toEqual([]) - expect( - push( - 'echo "git push"', - 'To github.com:acme/repo.git\n 8d5f74b..c512e75 feature -> feature\n' - ) - ).toEqual([]) - }) }) describe('pushedPullRequestHead', () => { diff --git a/src/main/github/pr-watch/pr-head-evaluation.test.ts b/src/main/github/pr-watch/pr-head-evaluation.test.ts index 880a966e953..5a33fc9704a 100644 --- a/src/main/github/pr-watch/pr-head-evaluation.test.ts +++ b/src/main/github/pr-watch/pr-head-evaluation.test.ts @@ -15,7 +15,7 @@ import { } from './pr-head-evaluation' import { PRPendingActionResume } from './pr-pending-action-resume' import { capturePRPendingActions } from './pr-pending-actions' -import { deletePRWatchChats } from './pr-watch-tables' +import './pr-watch-tables' import { prInfoFixture, shellCallRow } from './pr-watch-test-fixtures' import { prWatchCandidate } from './pr-watch-types' @@ -77,15 +77,6 @@ describe('recordPRHeadObservation over saved state', () => { expect(read(HEAD_B, green(31002), 30)).toEqual(['chat-1']) expect(read(HEAD_A, green(31001), 40)).toEqual([]) }) - - it('drops heads and context memory with the PR’s last owning chat', () => { - read(HEAD_A, [{ ...green(31001)[0], status: 'IN_PROGRESS', conclusion: null }]) - expect(readPRPendingHeads(database.db, PR_KEY)).toHaveLength(1) - database.transaction((db) => deletePRWatchChats(db, ['chat-1'])) - expect(readPRPendingHeads(database.db, PR_KEY)).toEqual([]) - const contexts = database.db.prepare('SELECT COUNT(*) AS n FROM pr_check_contexts').get() - expect(contexts?.n).toBe(0) - }) }) const FULL_A = '89abcde0000000000000000000000000000000ff' diff --git a/src/main/github/pr-watch/pr-watch-service.test.ts b/src/main/github/pr-watch/pr-watch-service.test.ts index c4567e236af..355747d1573 100644 --- a/src/main/github/pr-watch/pr-watch-service.test.ts +++ b/src/main/github/pr-watch/pr-watch-service.test.ts @@ -14,11 +14,7 @@ import { } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { assemblePRRefreshFoundOutcome } from '../client/lookup/pr-refresh-outcome-assembly' import type { PRWatchJob } from '../pr-refresh-watch-jobs' -import { - readPRPendingDeliveryChatIds, - readPRPendingHeads, - upsertPRPendingHead -} from './pr-check-event-tables' +import { readPRPendingDeliveryChatIds, readPRPendingHeads } from './pr-check-event-tables' import { readPRHeadCheckRollup } from './pr-head-check-read' import { capturePRPendingActions } from './pr-pending-actions' import { shellCallRow } from './pr-watch-test-fixtures' @@ -233,31 +229,4 @@ describe('PRWatchService startup retirement', () => { ]) next.stop() }) - - it('starts nothing from a workspace that resolves after the service stopped', async () => { - // R's action is past the action window, so retirement, had it run, would delete R's head. - vi.setSystemTime(1_800_000_000_000 - 30 * 24 * 60 * 60_000) - await seedOpenedPR('chat-r', 9) - vi.setSystemTime(1_800_000_000_000) - const database = await seedOpenedPR() - const STALE_KEY = 'github.com/acme/repo#9' - database.transaction((db) => - upsertPRPendingHead(db, { - prKey: STALE_KEY, - headSha: HEAD_A, - now: Date.now(), - movedAt: null, - ttlMs: 60_000 - }) - ) - let releaseQ = (_workspace: PRWatchWorkspace) => {} - const qWorkspace = new Promise((resolve) => (releaseQ = resolve)) - const stopping = service(() => qWorkspace) - const starting = stopping.start() - stopping.stop() - releaseQ(WORKSPACE) - await starting - expect(queue.scheduled).toEqual([]) - expect(readPRPendingHeads(database.db, STALE_KEY)).toHaveLength(1) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts index a8ccaac0ac4..d01a7500876 100644 --- a/src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts @@ -1,147 +1,11 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' -import { setPlatform } from '../orca-runtime-test-mocks/setup.spec' -import type { RuntimeTerminalAgentStatusEvent } from '../terminal/output/terminal-agent-status-events' -import { TEST_REPO_ID, TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' +import '../orca-runtime-test-mocks/setup.spec' + +import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('replaces a cwd parsed before late WSL context with the provider cwd', async () => { - setPlatform('win32') - const runtime = new OrcaRuntimeService(store) - const ptyId = 'pty-late-wsl-context' - const providerCwd = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - getSize: () => ({ cols: 80, rows: 24 }), - serializeProviderBuffer: vi.fn().mockResolvedValue({ - data: 'restored screen', - cols: 80, - rows: 24, - cwd: providerCwd, - seq: 1, - source: 'headless' - }) - }) - runtime.registerPty(ptyId, TEST_WORKTREE_ID) - runtime.seedHeadlessTerminal(ptyId, '\x1b]7;file://DESKTOP/home/me/repo\x07') - - const internals = runtime as unknown as { - headlessTerminals: Map }> - terminalCwdByPtyId: Map - } - await internals.headlessTerminals.get(ptyId)?.writeChain - expect(internals.terminalCwdByPtyId.get(ptyId)).toBe('\\\\desktop\\home\\me\\repo') - - runtime.preparePtyExecutionContext(ptyId, 'Ubuntu') - await internals.headlessTerminals.get(ptyId)?.writeChain - - expect(internals.terminalCwdByPtyId.get(ptyId)).toBe(providerCwd) - }) - - it('keeps a live WSL cwd that arrives during late-context snapshot recovery', async () => { - setPlatform('win32') - const runtime = new OrcaRuntimeService(store) - const ptyId = 'pty-late-wsl-context-race' - type ProviderSnapshot = { - data: string - cols: number - rows: number - cwd: string - seq: number - source: 'headless' - } - let resolveProviderSnapshot: ((snapshot: ProviderSnapshot) => void) | undefined - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - getSize: () => ({ cols: 80, rows: 24 }), - serializeProviderBuffer: vi.fn( - () => - new Promise((resolve) => { - resolveProviderSnapshot = resolve - }) - ) - }) - runtime.registerPty(ptyId, TEST_WORKTREE_ID) - runtime.seedHeadlessTerminal(ptyId, '\x1b]7;file://DESKTOP/home/me/old\x07') - const internals = runtime as unknown as { - headlessTerminals: Map }> - terminalCwdByPtyId: Map - } - await internals.headlessTerminals.get(ptyId)?.writeChain - - runtime.preparePtyExecutionContext(ptyId, 'Ubuntu') - await vi.waitFor(() => expect(resolveProviderSnapshot).toBeDefined()) - runtime.onPtyData(ptyId, '\x1b]7;file://DESKTOP/home/me/live\x07', 1) - resolveProviderSnapshot?.({ - data: 'older restored screen', - cols: 80, - rows: 24, - cwd: '\\\\wsl.localhost\\Ubuntu\\home\\me\\old', - seq: 1, - source: 'headless' - }) - await internals.headlessTerminals.get(ptyId)?.writeChain - - expect(internals.terminalCwdByPtyId.get(ptyId)).toBe( - '\\\\wsl.localhost\\Ubuntu\\home\\me\\live' - ) - }) - - it('infers local reconstructed WSL context from a WSL UNC worktree', () => { - setPlatform('win32') - const runtime = new OrcaRuntimeService(store) - runtime.registerPty( - 'pty-reconstructed', - `${TEST_REPO_ID}::\\\\wsl.localhost\\Ubuntu\\home\\me\\repo` - ) - - runtime.onPtyData('pty-reconstructed', '\x1b]7;file://DESKTOP/home/me/repo/src\x07', 1) - - const cwd = ( - runtime as unknown as { terminalCwdByPtyId: Map } - ).terminalCwdByPtyId.get('pty-reconstructed') - expect(cwd).toBe('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo\\src') - }) - - it('clears stale terminal file URI hostnames after empty-host OSC7 cwd updates', () => { - const runtime = new OrcaRuntimeService(store) - runtime.registerPty('pty-ssh', TEST_WORKTREE_ID, 'ssh-conn-1') - - runtime.onPtyData('pty-ssh', '\x1b]7;file://remote-host/home/me/repo/src\x07', 123) - runtime.onPtyData('pty-ssh', '\x1b]7;file:///home/me/repo/src\x07', 124) - - const internals = runtime as unknown as { - terminalCwdByPtyId: Map - terminalFileUriHostnameByPtyId: Map - } - expect(internals.terminalCwdByPtyId.get('pty-ssh')).toBe('/home/me/repo/src') - expect(internals.terminalFileUriHostnameByPtyId.has('pty-ssh')).toBe(false) - }) - - it('serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows', async () => { - setPlatform('win32') - const runtime = new OrcaRuntimeService(store) - runtime.registerPty('pty-ssh', TEST_WORKTREE_ID, 'ssh-conn-1') - - runtime.onPtyData('pty-ssh', '\x1b]7;file://remote-host/home/me/repo/src\x07hello', 123) - - const snapshot = await ( - runtime as unknown as { - serializeHeadlessTerminalBuffer: ( - ptyId: string, - opts: { includeEmpty?: boolean } - ) => Promise<{ cwd?: string | null } | null> - } - ).serializeHeadlessTerminalBuffer('pty-ssh', { includeEmpty: true }) - - expect(snapshot?.cwd).toBe('/home/me/repo/src') - }) - it('projects frame-independent live state through main buffer snapshots', async () => { const runtime = new OrcaRuntimeService(store) runtime.registerPty('pty-frame-state', TEST_WORKTREE_ID) @@ -154,79 +18,4 @@ describe('OrcaRuntimeService', () => { expect(snapshot?.frameRestoreAnsi).not.toContain('STATIC-FRAME') expect(snapshot?.data).toContain('STATIC-FRAME') }) - - it('keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX', () => { - setPlatform('darwin') - const runtime = new OrcaRuntimeService(store) - runtime.registerPty('pty-ssh-win', `${TEST_REPO_ID}::C:/Users/me/repo`, 'ssh-conn-1') - - runtime.onPtyData('pty-ssh-win', '\x1b]7;file:///C:/Users/me/repo/src\x07', 123) - - const internals = runtime as unknown as { - terminalCwdByPtyId: Map - } - expect(internals.terminalCwdByPtyId.get('pty-ssh-win')).toBe('C:/Users/me/repo/src') - }) - - it('serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops', async () => { - setPlatform('darwin') - const runtime = new OrcaRuntimeService(store) - runtime.registerPty('pty-ssh-win', `${TEST_REPO_ID}::C:/Users/me/repo`, 'ssh-conn-1') - - runtime.onPtyData('pty-ssh-win', '\x1b]7;file:///C:/Users/me/repo/src\x07hello', 123) - - const snapshot = await ( - runtime as unknown as { - serializeHeadlessTerminalBuffer: ( - ptyId: string, - opts: { includeEmpty?: boolean } - ) => Promise<{ cwd?: string | null } | null> - } - ).serializeHeadlessTerminalBuffer('pty-ssh-win', { includeEmpty: true }) - - expect(snapshot?.cwd).toBe('C:/Users/me/repo/src') - }) - - it('infers restored SSH connection identity from app-scoped PTY ids', () => { - const statuses: RuntimeTerminalAgentStatusEvent[] = [] - const runtime = new OrcaRuntimeService(store, undefined, { - onTerminalAgentStatus: (event) => statuses.push(event) - }) - const ptyId = 'ssh:ssh-restored@@relay-pty' - const leafId = '11111111-1111-4111-8111-111111111111' - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - title: 'Terminal', - activeLeafId: leafId, - layout: null - } - ], - leaves: [ - { - tabId: 'tab-1', - worktreeId: TEST_WORKTREE_ID, - leafId, - paneRuntimeId: 1, - ptyId - } - ] - }) - - runtime.onPtyData(ptyId, '\x1b]9999;{"state":"working","agentType":"codex"}\x07', 123) - - expect(statuses).toEqual([ - expect.objectContaining({ - ptyId, - connectionId: 'ssh-restored', - payload: expect.objectContaining({ - state: 'working', - agentType: 'codex' - }) - }) - ]) - }) }) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts deleted file mode 100644 index 6e3de6a6bee..00000000000 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { - HEADLESS_LEAF_ID, - HEADLESS_SECOND_LEAF_ID, - TEST_WORKTREE_ID, - makeHeadlessTerminalLayout, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} from './orca-runtime-test-fixtures.spec' - -const SERVE_PTY_ID = 'serve-mobile-created-pty' -const DAEMON_PTY_ID = 'daemon-agent-launch-pty' - -function makeTerminalTab(id: string, ptyId: string, sortOrder: number) { - return { - id, - ptyId, - worktreeId: TEST_WORKTREE_ID, - title: id, - customTitle: null, - color: null, - sortOrder, - createdAt: sortOrder + 1 - } -} - -// Restart fixture holds phone-created serve ids and CLI-created daemon ids, with no rebuilt memory state. -function makeRestartedServeRuntime(overrides: Partial = {}) { - const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - activeTabId: 'serve-tab', - activeTabIdByWorktree: { [TEST_WORKTREE_ID]: 'serve-tab' }, - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - makeTerminalTab('serve-tab', SERVE_PTY_ID, 0), - makeTerminalTab('daemon-tab', DAEMON_PTY_ID, 1) - ] - }, - terminalLayoutsByTabId: { - 'serve-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: SERVE_PTY_ID }), - 'daemon-tab': makeHeadlessTerminalLayout({ [HEADLESS_SECOND_LEAF_ID]: DAEMON_PTY_ID }) - }, - ...overrides - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'unexpected-pty' }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - return runtime -} - -const SPLIT_GROUPS = [ - { - id: 'group-left', - worktreeId: TEST_WORKTREE_ID, - activeTabId: 'serve-tab', - tabOrder: ['serve-tab'] - }, - { - id: 'group-right', - worktreeId: TEST_WORKTREE_ID, - activeTabId: 'daemon-tab', - tabOrder: ['daemon-tab'] - } -] - -// Client projection repairs activeGroupId; inspect host storage to avoid masking errors. -function storedActiveGroupId(runtime: OrcaRuntimeService): string | null | undefined { - const snapshots: Map = - runtime['mobileSessionTabsByWorktree'] - return snapshots.get(TEST_WORKTREE_ID)?.activeGroupId -} - -function terminalPtyIds(tabs: readonly { type: string; ptyId?: string | null }[]): string[] { - return tabs.flatMap((tab) => (tab.type === 'terminal' && tab.ptyId ? [tab.ptyId] : [])).sort() -} - -describe('OrcaRuntimeService', () => { - it('lists every persisted terminal of a windowless host after a cold restart', async () => { - const runtime = makeRestartedServeRuntime() - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(terminalPtyIds(listed.tabs)).toEqual([DAEMON_PTY_ID, SERVE_PTY_ID].sort()) - }) - - it('lists every persisted terminal in the all-worktrees inventory after a cold restart', async () => { - const runtime = makeRestartedServeRuntime() - - const snapshots = await runtime.listAllMobileSessionTabs() - const listed = snapshots.find((snapshot) => snapshot.worktree === TEST_WORKTREE_ID) - - expect(terminalPtyIds(listed?.tabs ?? [])).toEqual([DAEMON_PTY_ID, SERVE_PTY_ID].sort()) - }) - - it('lists persisted editor tabs beside the terminals after a cold restart', async () => { - const runtime = makeRestartedServeRuntime({ - openFilesByWorktree: { - [TEST_WORKTREE_ID]: [ - { - filePath: '/repo/README.md', - relativePath: 'README.md', - worktreeId: TEST_WORKTREE_ID, - language: 'markdown', - runtimeEnvironmentId: null - } - ] - } - }) - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(terminalPtyIds(listed.tabs)).toEqual([DAEMON_PTY_ID, SERVE_PTY_ID].sort()) - expect(listed.tabs.filter((tab) => tab.type === 'markdown').map((tab) => tab.id)).toEqual([ - '/repo/README.md' - ]) - }) - - it('restores a persisted split group layout on the cold rebuild', async () => { - const runtime = makeRestartedServeRuntime({ - activeGroupIdByWorktree: { [TEST_WORKTREE_ID]: 'group-left' }, - tabGroups: { [TEST_WORKTREE_ID]: SPLIT_GROUPS } - }) - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(listed.tabGroups?.map((group) => group.tabOrder)).toEqual([ - ['serve-tab'], - ['daemon-tab'] - ]) - expect(storedActiveGroupId(runtime)).toBe('group-left') - }) - - it('restores the saved active group of a split even when it is not the first group', async () => { - const runtime = makeRestartedServeRuntime({ - activeTabId: 'daemon-tab', - activeTabIdByWorktree: { [TEST_WORKTREE_ID]: 'daemon-tab' }, - activeGroupIdByWorktree: { [TEST_WORKTREE_ID]: 'group-right' }, - tabGroups: { [TEST_WORKTREE_ID]: SPLIT_GROUPS } - }) - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(storedActiveGroupId(runtime)).toBe('group-right') - expect(listed.activeGroupId).toBe('group-right') - }) - - it('falls back to the active tab group when the saved active group was not restored', async () => { - const runtime = makeRestartedServeRuntime({ - activeTabId: 'daemon-tab', - activeTabIdByWorktree: { [TEST_WORKTREE_ID]: 'daemon-tab' }, - activeGroupIdByWorktree: { [TEST_WORKTREE_ID]: 'group-gone' }, - tabGroups: { [TEST_WORKTREE_ID]: SPLIT_GROUPS } - }) - - await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(storedActiveGroupId(runtime)).toBe('group-right') - }) - - it('keeps the headless group active when there is no persisted split', async () => { - const runtime = makeRestartedServeRuntime({ - activeGroupIdByWorktree: { [TEST_WORKTREE_ID]: 'group-gone' } - }) - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(listed.tabGroups).toHaveLength(1) - expect(storedActiveGroupId(runtime)).toBe(listed.tabGroups?.[0]?.id) - }) - - it('keeps phone and CLI creates in the group they joined across a cold restart', async () => { - const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal({ - activeTabId: 'serve-tab', - activeTabIdByWorktree: { [TEST_WORKTREE_ID]: 'serve-tab' }, - activeGroupIdByWorktree: { [TEST_WORKTREE_ID]: 'group-left' }, - tabGroups: { [TEST_WORKTREE_ID]: SPLIT_GROUPS }, - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - makeTerminalTab('serve-tab', SERVE_PTY_ID, 0), - makeTerminalTab('daemon-tab', DAEMON_PTY_ID, 1) - ] - }, - terminalLayoutsByTabId: { - 'serve-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: SERVE_PTY_ID }), - 'daemon-tab': makeHeadlessTerminalLayout({ [HEADLESS_SECOND_LEAF_ID]: DAEMON_PTY_ID }) - } - }) - ) - const runtime = new OrcaRuntimeService(runtimeStore) - let ptys = 0 - runtime.setPtyController({ - spawn: vi.fn(async () => ({ id: `created-pty-${++ptys}` })), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [] - }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - const phone = await runtime.createMobileSessionTerminal(`id:${TEST_WORKTREE_ID}`, { - targetGroupId: 'group-right' - }) - const cli = await runtime.createTerminal(`id:${TEST_WORKTREE_ID}`) - const tabOrderOf = (session: WorkspaceSessionState, groupId: string) => - session.tabGroups?.[TEST_WORKTREE_ID]?.find((group) => group.id === groupId)?.tabOrder - expect(tabOrderOf(getSession(), 'group-right')).toContain(phone.tab.parentTabId) - expect(tabOrderOf(getSession(), 'group-left')).toContain(cli.tabId) - - const restarted = new OrcaRuntimeService( - makeRuntimeStoreWithWorkspaceSession(getSession()).runtimeStore - ) - const listed = await restarted.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - expect(listed.tabGroups?.map((group) => group.tabOrder)).toEqual([ - ['serve-tab', cli.tabId], - ['daemon-tab', phone.tab.parentTabId] - ]) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts deleted file mode 100644 index 1ce7c243392..00000000000 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - makeHeadlessTerminalLayout, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} from './orca-runtime-test-fixtures.spec' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' -import { resolveHostId } from '../../persistence/loading-store/session-host-partitions' - -// #29968: chat tabs exist only in runtime snapshots; persisted terminal/editor rebuilds must retain them. -const WORKTREE = `id:${TEST_WORKTREE_ID}` -const README = `${TEST_WORKTREE_PATH}/README.md` -const CHAT_TAB_ID = 'agent-session:claude_29968' -const SERVE_PTY_ID = 'serve-29968-pty' - -function sessionWithTerminalAndEditor(): WorkspaceSessionState { - return makeWorkspaceSessionWithHeadlessTerminal({ - activeTabId: 'serve-tab', - activeTabIdByWorktree: { [TEST_WORKTREE_ID]: 'serve-tab' }, - tabsByWorktree: { - [TEST_WORKTREE_ID]: [ - { - id: 'serve-tab', - ptyId: SERVE_PTY_ID, - worktreeId: TEST_WORKTREE_ID, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'serve-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: SERVE_PTY_ID }) - }, - openFilesByWorktree: { - [TEST_WORKTREE_ID]: [ - { - filePath: README, - relativePath: 'README.md', - worktreeId: TEST_WORKTREE_ID, - language: 'markdown', - runtimeEnvironmentId: null - } - ] - }, - unifiedTabs: { - [TEST_WORKTREE_ID]: [ - { - id: 'tab-readme', - entityId: README, - groupId: 'group-1', - worktreeId: TEST_WORKTREE_ID, - contentType: 'editor', - label: 'README.md', - customLabel: null, - color: null, - sortOrder: 1, - createdAt: 2 - } - ] - } - }) -} - -/** asProfileStore lists host partitions and notifies writes so main-owned layout follows persisted changes. */ -function headlessRuntimeWithChat({ asProfileStore = false } = {}) { - const harness = makeRuntimeStoreWithWorkspaceSession(sessionWithTerminalAndEditor()) - const written = new Set<(hostId: ExecutionHostId | null) => void>() - const setSession = (next: WorkspaceSessionState): void => { - harness.setSession(next) - written.forEach((listener) => listener(LOCAL_EXECUTION_HOST_ID)) - } - const runtime = new OrcaRuntimeService( - asProfileStore - ? { - ...harness.runtimeStore, - getWorkspaceSessionHostIds: () => ['local'], - onWorkspaceSessionWritten: (listener: (hostId: ExecutionHostId | null) => void) => { - written.add(listener) - return () => { - written.delete(listener) - } - }, - setWorkspaceSession: setSession, - applyLayoutCommand: async (command: LayoutCommand, hostIds?: readonly string[]) => { - const change = applyCommandToSession( - resolveHostId(hostIds?.[0] ?? 'local'), - harness.getSession(), - command - ) - if (change.session) { - setSession(change.session) - } - return change.value - } - } - : harness.runtimeStore - ) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: vi.fn(async () => [{ id: SERVE_PTY_ID, cwd: TEST_WORKTREE_PATH, title: 'sh' }]) - }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - return runtime -} - -async function openChat(runtime: OrcaRuntimeService): Promise { - await runtime.listMobileSessionTabs(WORKTREE) - await runtime.publishStructuredAgentSessionTab({ - workspaceId: TEST_WORKTREE_ID, - sessionId: 'claude_29968', - agent: 'claude', - activate: true - }) -} - -describe('a chat tab on a host with no window', () => { - it('survives the rebuild that closing a saved editor tab forces', async () => { - const runtime = headlessRuntimeWithChat() - await openChat(runtime) - expect((await runtime.listMobileSessionTabs(WORKTREE)).tabs.map((tab) => tab.id)).toContain( - CHAT_TAB_ID - ) - - await runtime.closeMobileSessionTab(WORKTREE, 'tab-readme', { reason: 'user' }) - - const listed = await runtime.listMobileSessionTabs(WORKTREE) - expect(listed.tabs.map((tab) => tab.id)).toContain(CHAT_TAB_ID) - expect(listed.tabs.map((tab) => tab.id)).not.toContain('tab-readme') - expect(listed.tabGroups?.flatMap((group) => group.tabOrder)).toContain(CHAT_TAB_ID) - expect(listed.activeTabId).toBe(CHAT_TAB_ID) - expect(listed.tabs.filter((tab) => tab.isActive).map((tab) => tab.id)).toEqual([CHAT_TAB_ID]) - }) - - it('keeps its place in the tab order when the host lists the workspace again', async () => { - const runtime = headlessRuntimeWithChat() - await openChat(runtime) - - const listed = await runtime.listMobileSessionTabs(WORKTREE) - - expect(listed.tabGroups?.flatMap((group) => group.tabOrder)).toEqual([ - 'serve-tab', - 'tab-readme', - CHAT_TAB_ID - ]) - }) - - it('lists tabs to phones in the order desktop clients draw after a rebuild', async () => { - const runtime = headlessRuntimeWithChat({ asProfileStore: true }) - await runtime.listMobileSessionTabs(WORKTREE) - await runtime.publishStructuredAgentSessionTab({ - workspaceId: TEST_WORKTREE_ID, - sessionId: 'claude_29968', - agent: 'claude', - activate: true - }) - const groupId = (await runtime.listMobileSessionTabs(WORKTREE)).tabGroups?.[0]?.id ?? '' - await runtime.moveMobileSessionTab(WORKTREE, { - kind: 'reorder', - tabId: CHAT_TAB_ID, - targetGroupId: groupId, - tabOrder: [CHAT_TAB_ID, 'serve-tab', 'tab-readme'] - }) - - await runtime.closeMobileSessionTab(WORKTREE, 'tab-readme', { reason: 'user' }) - - const listed = await runtime.listMobileSessionTabs(WORKTREE) - expect(listed.tabGroups?.flatMap((group) => group.tabOrder)).toEqual([CHAT_TAB_ID, 'serve-tab']) - expect(listed.tabs.map((tab) => (tab.type === 'terminal' ? tab.parentTabId : tab.id))).toEqual([ - CHAT_TAB_ID, - 'serve-tab' - ]) - }) - - it('keeps the place a window gave a chat across a graph resend before the chat is restored', async () => { - const runtime = headlessRuntimeWithChat() - runtime.syncWindowGraph(0, { - tabs: [], - leaves: [], - mobileSessionTabs: [ - { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer:test', - snapshotVersion: 1, - activeGroupId: 'group-1', - activeTabId: 'win-term::leaf-1', - activeTabType: 'terminal', - tabGroups: [ - { id: 'group-1', activeTabId: 'win-term', tabOrder: [CHAT_TAB_ID, 'win-term'] } - ], - tabs: [ - { - type: 'terminal', - id: 'win-term::leaf-1', - parentTabId: 'win-term', - leafId: 'leaf-1', - title: 'Terminal', - isActive: true - } - ] - } - ] - }) - runtime.syncWindowGraph(0, { - tabs: [], - leaves: [], - unchangedMobileSessionWorktrees: [TEST_WORKTREE_ID] - }) - await runtime.publishStructuredAgentSessionTab({ - workspaceId: TEST_WORKTREE_ID, - sessionId: 'claude_29968', - agent: 'claude', - activate: false - }) - - const listed = await runtime.listMobileSessionTabs(WORKTREE) - // Main-owned order is authoritative; window frames cannot add tabs/order missing from its layout. - const expectedOrder = ORCA_LAYOUT_OWNER_IS_MAIN - ? ['serve-tab', 'tab-readme', CHAT_TAB_ID] - : [CHAT_TAB_ID, 'win-term', 'serve-tab'] - expect(listed.tabGroups?.flatMap((group) => group.tabOrder)).toEqual(expectedOrder) - expect(listed.tabs.map((tab) => (tab.type === 'terminal' ? tab.parentTabId : tab.id))).toEqual( - expectedOrder - ) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts deleted file mode 100644 index 43b1dc52ac5..00000000000 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { withDurableRuntimeStore } from './runtime-durable-store-fixture' -import type { PtyControllerInventory } from '../runtime-pty-controller-contract' -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - makeRuntimeStoreWithWorkspaceSession -} from './orca-runtime-test-fixtures.spec' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' - -const README = `${TEST_WORKTREE_PATH}/README.md` - -function sessionWithMigratedEditor(): WorkspaceSessionState { - return { - ...getDefaultWorkspaceSession(), - openFilesByWorktree: { - [TEST_WORKTREE_ID]: [ - { - filePath: README, - relativePath: 'README.md', - worktreeId: TEST_WORKTREE_ID, - language: 'markdown', - runtimeEnvironmentId: null - } - ] - }, - unifiedTabs: { - [TEST_WORKTREE_ID]: [ - { - id: 'tab-readme', - entityId: README, - groupId: 'group-1', - worktreeId: TEST_WORKTREE_ID, - contentType: 'editor', - label: 'README.md', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - tabGroups: { - [TEST_WORKTREE_ID]: [ - { - id: 'group-1', - worktreeId: TEST_WORKTREE_ID, - activeTabId: 'tab-readme', - tabOrder: ['tab-readme'] - } - ] - }, - activeTabTypeByWorktree: { [TEST_WORKTREE_ID]: 'editor' }, - activeFileIdByWorktree: { [TEST_WORKTREE_ID]: README } - } -} - -function headlessRuntime(session: WorkspaceSessionState) { - const harness = makeRuntimeStoreWithWorkspaceSession(session) - const runtime = new OrcaRuntimeService(harness.runtimeStore) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: vi.fn(async () => []) - }) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - return { runtime, getSession: harness.getSession } -} - -describe('editor tabs a headless host persisted', () => { - it('lists them, so a paired client can mirror a migrated editor', async () => { - const { runtime } = headlessRuntime(sessionWithMigratedEditor()) - - const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - expect(listed.tabs).toEqual([ - expect.objectContaining({ - type: 'markdown', - id: 'tab-readme', - filePath: README, - relativePath: 'README.md', - isActive: true - }) - ]) - expect(listed.activeTabId).toBe('tab-readme') - }) - - it('closes one by retiring it from the host session', async () => { - const { runtime, getSession } = headlessRuntime(sessionWithMigratedEditor()) - await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - await runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'tab-readme') - - expect(getSession().openFilesByWorktree?.[TEST_WORKTREE_ID]).toEqual([]) - expect(getSession().unifiedTabs?.[TEST_WORKTREE_ID]).toEqual([]) - expect((await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)).tabs).toEqual([]) - }) - - it('keeps an unsaved draft unless the close is forced', async () => { - const session = sessionWithMigratedEditor() - const [file] = session.openFilesByWorktree?.[TEST_WORKTREE_ID] ?? [] - session.openFilesByWorktree = { [TEST_WORKTREE_ID]: [{ ...file, dirtyDraftContent: 'draft' }] } - const { runtime, getSession } = headlessRuntime(session) - await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) - - await expect( - runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'tab-readme') - ).rejects.toThrow('editor_tab_has_unsaved_draft') - expect(getSession().openFilesByWorktree?.[TEST_WORKTREE_ID]?.[0]?.dirtyDraftContent).toBe( - 'draft' - ) - - await runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'tab-readme', { force: true }) - expect(getSession().openFilesByWorktree?.[TEST_WORKTREE_ID]).toEqual([]) - }) -}) - -class MobileSessionCycleRuntime extends OrcaRuntimeService { - refreshInventory(target: string | null = null) { - return this.refreshMobileSessionPtyInventory(target) - } - - override performMobileSessionPtyRecordsRefresh(target: string | null) { - return super.performMobileSessionPtyRecordsRefresh(target) - } - - get pendingRefresh() { - return this.pendingMobileSessionPtyAggregateInventoryRefresh - } - - set pendingRefresh(value: Promise | null) { - this.pendingMobileSessionPtyAggregateInventoryRefresh = value - } - - closeHostTab() { - return this.closeTerminalSurface( - TEST_WORKTREE_ID, - { kind: 'tab', tabId: 'mobile-cycle-closed-tab' }, - { allowMissing: true, closedByLayoutOwner: true } - ) - } -} - -function mobileCycleRuntime() { - const harness = makeRuntimeStoreWithWorkspaceSession(getDefaultWorkspaceSession()) - const runtimeStore = withDurableRuntimeStore( - Object.assign(harness.runtimeStore, { flushOrThrow: () => {} }) - ) - return { - runtime: new MobileSessionCycleRuntime(runtimeStore), - harness: { ...harness, runtimeStore } - } -} - -describe('mobile session cycle reentry', () => { - it('shares aggregate work but leaves a replacement pending promise alone', async () => { - const { runtime } = mobileCycleRuntime() - const gate = Promise.withResolvers() - const perform = vi - .spyOn(runtime, 'performMobileSessionPtyRecordsRefresh') - .mockReturnValue(gate.promise) - const first = runtime.refreshInventory() - const stored = runtime.pendingRefresh - const second = runtime.refreshInventory() - expect(perform).toHaveBeenCalledExactlyOnceWith(null) - expect(runtime.pendingRefresh).toBe(stored) - const replacement = Promise.resolve(null) - runtime.pendingRefresh = replacement - gate.resolve(null) - await expect(first).resolves.toBeNull() - await expect(second).resolves.toBeNull() - expect(runtime.pendingRefresh).toBe(replacement) - }) - - it('lets a targeted refresh finish while an aggregate refresh waits', async () => { - const { runtime } = mobileCycleRuntime() - const gate = Promise.withResolvers() - const perform = vi - .spyOn(runtime, 'performMobileSessionPtyRecordsRefresh') - .mockReturnValueOnce(gate.promise) - .mockResolvedValue(null) - const aggregate = runtime.refreshInventory() - await expect(runtime.refreshInventory(TEST_WORKTREE_ID)).resolves.toBeNull() - expect(perform.mock.calls).toEqual([[null], [TEST_WORKTREE_ID]]) - gate.resolve(null) - await expect(aggregate).resolves.toBeNull() - expect(runtime.pendingRefresh).toBeNull() - }) - - it.each(['getWorkspaceSession', 'setWorkspaceSession', 'runDurableMutation'] as const)( - 'refuses a close when the store lacks %s before the guard', - async (method) => { - const { runtime, harness } = mobileCycleRuntime() - Object.defineProperty(harness.runtimeStore, method, { configurable: true, value: undefined }) - await expect(runtime.closeHostTab()).rejects.toThrow('workspace_session_unavailable') - } - ) - - it.each(['getWorkspaceSession', 'setWorkspaceSession'] as const)( - 'keeps a later missing %s on the original caught failure path', - async (method) => { - const { runtime, harness } = mobileCycleRuntime() - const runDurableMutation = harness.runtimeStore.runDurableMutation - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - error.mockClear() - try { - vi.spyOn(harness.runtimeStore, 'runDurableMutation').mockImplementation((mutate) => { - Object.defineProperty(harness.runtimeStore, method, { - configurable: true, - value: undefined - }) - return runDurableMutation(mutate) - }) - await expect(runtime.closeHostTab()).resolves.toEqual([]) - expect(error).toHaveBeenCalledExactlyOnceWith( - '[runtime] failed to persist terminal close:', - expect.any(TypeError) - ) - } finally { - error.mockRestore() - } - } - ) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts index 63a04e4c566..25a048d7a28 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts @@ -1,52 +1,10 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' +import '../orca-runtime' import { TEST_WORKTREE_ID, syncSinglePty } from './orca-runtime-test-fixtures.spec' import { createSideEffectRuntime } from './orca-runtime-test-scenario-builders.spec' describe('terminal side-effect fact channel', () => { - it('arms the stale-title timer for a seeded working title', async () => { - vi.useFakeTimers() - try { - const { runtime, batches } = createSideEffectRuntime() - const serializeBuffer = vi.fn().mockResolvedValue({ - data: 'restored scrollback\n', - cols: 80, - rows: 24, - lastTitle: 'Codex working' - }) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeBuffer, - hasRendererSerializer: () => true, - getSize: () => ({ cols: 80, rows: 24 }) - }) - syncSinglePty(runtime) - - runtime.onPtyData('pty-1', 'plain output\n', 100) - // Settle the async daemon-snapshot hydration that seeds the tracker. - await vi.advanceTimersByTimeAsync(0) - runtime.onPtyData('pty-1', 'still no title\n', 101) - batches.length = 0 - - await vi.advanceTimersByTimeAsync(3_000) - - expect(batches.flatMap((batch) => batch.facts)).toEqual([ - { - kind: 'title', - normalizedTitle: 'Codex', - rawTitle: 'Codex', - staleWorkingTitleClear: true - }, - { kind: 'agent-idle', title: 'Codex', status: 'idle', staleWorkingTitleClear: true } - ]) - } finally { - vi.useRealTimers() - } - }) - it('emits command-code-working facts only after the banner arms the scrape', () => { const { runtime, batches } = createSideEffectRuntime() syncSinglePty(runtime) @@ -81,121 +39,4 @@ describe('terminal side-effect fact channel', () => { expect(batches.at(-1)?.facts).toEqual([{ kind: 'command-code-done', prompt: 'say hi' }]) }) - - it('arms the Command Code scrape from the noted spawn command', () => { - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - // A known spawn command arms detection without a banner, matching the renderer. - runtime.noteTerminalSpawnCommand('pty-1', 'command-code --trust') - runtime.onPtyData('pty-1', '❯ Fix the spinner\r\n✻ Thinking...', 100) - - expect(batches.flatMap((batch) => batch.facts)).toContainEqual({ - kind: 'command-code-working', - prompt: 'Fix the spinner' - }) - }) - - it('prefers the tracked title over a stale renderer lastTitle in the hydration seed', async () => { - const { runtime } = createSideEffectRuntime() - const serializeBuffer = vi.fn().mockResolvedValue({ - data: 'renderer scrollback\n', - cols: 80, - rows: 24, - // The renderer retains its old title because synthetic hook frames bypass pty:data. - lastTitle: 'stale shell title' - }) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - serializeBuffer, - hasRendererSerializer: () => true, - getSize: () => ({ cols: 80, rows: 24 }) - }) - syncSinglePty(runtime) - - runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Claude working\x07') - // The snapshot await settles hydration after the first live chunk. - runtime.onPtyData('pty-1', 'plain output\n', 100) - await runtime.serializeMainTerminalBuffer('pty-1', { scrollbackRows: 10 }) - - const leaves = (runtime as unknown as { leaves: Map }) - .leaves - expect([...leaves.values()][0]?.lastOscTitle).toBe('⠋ Claude working') - }) -}) - -describe('terminal output runtime re-entry', () => { - it('writes recent output into the current runtime output map', () => { - const runtime = new OrcaRuntimeService() - const replacement = new Map(runtime['recentPtyOutputById']) - runtime['recentPtyOutputById'] = replacement - runtime['recordRecentPtyOutput']('pty-provenance', 'wrote artifact.txt\n') - expect(replacement.get('pty-provenance')?.read()).toBe('wrote artifact.txt\n') - }) - - it('uses a later title handler replacement with the runtime receiver', () => { - const runtime = new OrcaRuntimeService() - const ptyId = 'pty-reentry' - runtime['getOrCreatePtyTitleTrackerEntry'](ptyId) - const original = runtime['applyTrackedPtyTitle'] - const receivers: OrcaRuntimeService[] = [] - const titles: string[] = [] - runtime['applyTrackedPtyTitle'] = function ( - this: OrcaRuntimeService, - ...args: Parameters - ): boolean { - receivers.push(this) - titles.push(args[1]) - return false - } - try { - runtime.ingestSyntheticTitleFrame(ptyId, '\x1b]0;Codex working\x07') - expect(receivers).toEqual([runtime]) - expect(titles).toEqual(['Codex working']) - } finally { - runtime['applyTrackedPtyTitle'] = original - runtime.onPtyExit(ptyId, 0) - } - }) - - it('calls the current injected listener with the runtime receiver', () => { - const receivers: OrcaRuntimeService[] = [] - const calls: string[] = [] - const runtime = new OrcaRuntimeService(null, undefined, { - onTerminalSideEffects: function (this: OrcaRuntimeService) { - receivers.push(this) - calls.push('initial') - } - }) - runtime['setTerminalSideEffectConsumerAvailable'](true) - runtime['emitTerminalSideEffectBatch']('pty-reentry', [{ kind: 'bell' }]) - Object.defineProperty(runtime, 'onTerminalSideEffects', { - value: function (this: OrcaRuntimeService) { - receivers.push(this) - calls.push('replacement') - } - }) - runtime['emitTerminalSideEffectBatch']('pty-reentry', [{ kind: 'bell' }]) - expect(receivers).toEqual([runtime, runtime]) - expect(calls).toEqual(['initial', 'replacement']) - }) - - it('keeps optional reconciliation lazy after its callback is removed', () => { - const receivers: OrcaRuntimeService[] = [] - const runtime = new OrcaRuntimeService(null, undefined, { - reconcileAgentStatusForEndedProcess: function (this: OrcaRuntimeService) { - receivers.push(this) - } - }) - const collectPaneKeys = vi.fn(() => new Set()) - runtime['collectAgentStatusPaneKeysForPty'] = collectPaneKeys - runtime['resetTrackedTerminalStateForProviderGeneration']('pty-reentry') - expect(receivers).toEqual([runtime]) - expect(collectPaneKeys).toHaveBeenCalledOnce() - Object.defineProperty(runtime, 'reconcileAgentStatusForEndedProcessFn', { value: null }) - runtime['resetTrackedTerminalStateForProviderGeneration']('pty-reentry') - expect(collectPaneKeys).toHaveBeenCalledOnce() - }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts deleted file mode 100644 index c6eab0acf2a..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { describe, expect, it, vi, afterEach } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { TEST_WORKTREE_PATH, store } from './orca-runtime-test-fixtures.spec' -import { OrchestrationDb } from '../orchestration/db/orchestration-db' - -// `agent.launch` settles a launch as failed only when its create threw before this hook ran. -describe('OrcaRuntimeService createTerminal spawn dispatch', () => { - it('reports the spawn request before it leaves for the pty controller', async () => { - const dispatched = vi.fn() - const spawn = vi.fn(async () => { - expect(dispatched).toHaveBeenCalledOnce() - return { id: 'pty-dispatch' } - }) - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'codex', - onPtySpawnDispatched: dispatched - }) - - expect(spawn).toHaveBeenCalledOnce() - }) - - it('reports it even when the spawn itself then fails', async () => { - const dispatched = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn: vi.fn(async () => { - throw new Error('ssh_channel_closed') - }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - await expect( - runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`, { - command: 'codex', - onPtySpawnDispatched: dispatched - }) - ).rejects.toThrow('ssh_channel_closed') - expect(dispatched).toHaveBeenCalledOnce() - }) - - it('does not report it when the create fails before any spawn request', async () => { - const dispatched = vi.fn() - const spawn = vi.fn() - const runtime = new OrcaRuntimeService(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - await expect( - runtime.createTerminal('path:/no/such/workspace', { - command: 'codex', - onPtySpawnDispatched: dispatched - }) - ).rejects.toThrow() - expect(spawn).not.toHaveBeenCalled() - expect(dispatched).not.toHaveBeenCalled() - }) -}) - -describe('PTY registration dispatch characterization', () => { - type PtyRegistrationBinding = NonNullable[3]> - const TAB_ID = '11111111-1111-4111-8111-111111111111' - const LEAF_ID = '22222222-2222-4222-8222-222222222222' - const PTY_ID = 'pty-dispatch' - const WORKTREE_ID = 'repo::/tmp/dispatch' - const databases: OrchestrationDb[] = [] - - afterEach(() => { - for (const db of databases.splice(0)) { - db.close() - } - }) - - class DispatchRuntime extends OrcaRuntimeService { - constructor() { - super(null) - this.ensurePtyBackedMobileSurfaceForRendererTab = () => null - this.touchMobileSessionSnapshotsForPty = () => {} - } - - replaceAdmission(assertion: (ptyId: string, incarnationId?: string) => void): void { - this.assertPtyDidNotExitBeforeRegistration = assertion - } - - replaceHostScope( - resolve: () => { kind: 'local'; hostId: 'local'; toJSON(): { kind: 'local' } } | null - ): void { - this.getOrchestrationCompatibilityHostScope = resolve - } - - setDatabase(db: OrchestrationDb | null): void { - this._orchestrationDb = db - } - - get record() { - return this.recordPtyWorktree - } - - set record(value: typeof this.recordPtyWorktree) { - this.recordPtyWorktree = value - } - - get pendingCreates() { - return this.pendingMobileTerminalCreatesByKey - } - - get replacementFences() { - return this.pendingPtyHandleReplacementFences - } - } - - function binding(): PtyRegistrationBinding { - return { tabId: TAB_ID, leafId: LEAF_ID, incarnationId: 'dispatch-incarnation' } - } - - function register(runtime: DispatchRuntime, tab: PtyRegistrationBinding): void { - runtime.registerPty(PTY_ID, WORKTREE_ID, null, tab) - } - - describe('PTY runtime dispatch', () => { - it('captures the admission method before reading the incarnation', () => { - const runtime = new DispatchRuntime() - runtime.replaceAdmission(function (this: DispatchRuntime) { - expect(this).toBe(runtime) - throw new Error('captured admission') - }) - const tab = binding() - Object.defineProperty(tab, 'incarnationId', { - get() { - runtime.replaceAdmission(() => { - throw new Error('late admission') - }) - return 'dispatch-incarnation' - } - }) - expect(() => register(runtime, tab)).toThrow('captured admission') - }) - - it('captures the record method before evaluating its state object', () => { - const runtime = new DispatchRuntime() - let reads = 0 - runtime.record = function (this: DispatchRuntime) { - expect(this).toBe(runtime) - throw new Error('captured record') - } - const tab = binding() - Object.defineProperty(tab, 'tabId', { - get() { - if (++reads === 3) { - runtime.record = () => { - throw new Error('late record') - } - } - return TAB_ID - } - }) - expect(() => register(runtime, tab)).toThrow('captured record') - }) - - it('skips database payload serialization when no database exists', () => { - const runtime = new DispatchRuntime() - let serializations = 0 - runtime.replaceHostScope(() => ({ - kind: 'local', - hostId: 'local', - toJSON() { - serializations++ - return { kind: 'local' } - } - })) - register(runtime, binding()) - expect(serializations).toBe(0) - }) - - it('skips a throwing database payload when no database exists', () => { - const runtime = new DispatchRuntime() - runtime.replaceHostScope(() => ({ - kind: 'local', - hostId: 'local', - toJSON() { - throw new Error('absent database payload') - } - })) - expect(() => register(runtime, binding())).not.toThrow() - }) - - it('keeps the database method and receiver captured before its payload', () => { - const runtime = new DispatchRuntime() - const captured = new OrchestrationDb(':memory:') - const replacement = new OrchestrationDb(':memory:') - databases.push(captured, replacement) - const calls: string[] = [] - captured.retainReplacedWorkerTerminalResources = function () { - expect(this).toBe(captured) - calls.push('captured database') - return 0 - } - replacement.retainReplacedWorkerTerminalResources = () => calls.push('late database') - runtime.setDatabase(captured) - runtime.replaceHostScope(() => ({ - kind: 'local', - hostId: 'local', - toJSON() { - runtime.setDatabase(replacement) - return { kind: 'local' } - } - })) - register(runtime, binding()) - expect(calls).toEqual(['captured database']) - }) - - it('captures the canonical map method before a binding getter changes it', () => { - const runtime = new DispatchRuntime() - let reads = 0 - const calls: string[] = [] - const map = runtime.pendingCreates - map.has = () => { - calls.push('captured map') - return true - } - const tab = binding() - Object.defineProperty(tab, 'tabId', { - get() { - if (++reads === 3) { - map.has = () => { - calls.push('late map') - return false - } - } - return TAB_ID - } - }) - runtime.replaceHostScope(() => null) - register(runtime, tab) - expect(calls).toEqual(['captured map']) - }) - - it('completes the captured replacement fence without another map lookup', () => { - const runtime = new DispatchRuntime() - let recorded = false - let captured = false - let reads = 0 - const map = runtime.replacementFences - const originalGet = map.get.bind(map) - const first = { - incarnationId: 'first', - staleHandles: new Set(), - pendingRegistration: false - } - const replacement = { - incarnationId: 'second', - staleHandles: new Set(), - pendingRegistration: true - } - map.set(PTY_ID, first) - map.get = function (id) { - reads++ - const value = originalGet(id) - if (recorded) { - captured = true - } - return value - } - const record = runtime.record - runtime.record = function (...args) { - const value = record.apply(runtime, args) - recorded = true - return value - } - runtime.replaceHostScope(() => null) - const tab = binding() - Object.defineProperty(tab, 'incarnationId', { - get() { - if (captured) { - map.set(PTY_ID, replacement) - } - return undefined - } - }) - register(runtime, tab) - expect(reads).toBe(2) - expect(replacement.pendingRegistration).toBe(true) - }) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts deleted file mode 100644 index b9490b5e6ec..00000000000 --- a/src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts +++ /dev/null @@ -1,268 +0,0 @@ -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { listWorktrees } from '../../git/worktrees/catalog/worktree-scan-cache' -import { listWorktreesStrict } from '../../git/worktrees/catalog/worktree-listing' -import { removeWorktree } from '../../git/worktrees/removal/worktree-removal' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { - TEST_REPO_ID, - TEST_REPO_PATH, - TEST_WORKTREE_ID, - TEST_WORKTREE_PATH, - makeWorktreeMeta, - store -} from './orca-runtime-test-fixtures.spec' -import { createWorktreeRemovalRuntime } from './orca-runtime-test-scenario-builders.spec' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { RuntimeStore } from '../runtime-store-contract' -import type { WorktreeRemovalRecord } from '../../workspaces/removal/worktree-removal-records' -import { - failedWorktreeRemovals, - pendingWorktreeRemovals -} from '../../workspaces/removal/worktree-removal-table' -import { - _resetPendingWorktreeRemovalsForTests, - _settlePendingWorktreeRemovalsForTests -} from '../../workspaces/removal/worktree-background-removal' -import { RuntimeWorktreeRemovalInFlight } from '../workspaces/removal/runtime-worktree-removal-in-flight' -import type { HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' - -const REMOTE_REPO_PATH = '/remote/repo' - -function makeRemoteRepoStore( - executionHostId: ExecutionHostId, - extraRepoFields: Record = {}, - metaOverrides: Partial = {} -) { - const repo = { - ...store.getRepos()[0]!, - path: REMOTE_REPO_PATH, - executionHostId, - ...extraRepoFields - } - const metaById: Record = { - [TEST_WORKTREE_ID]: makeWorktreeMeta({ hostId: executionHostId, ...metaOverrides }) - } - const removeWorktreeMeta = vi.fn(({ id: worktreeId, hostId }: HostWorktreeTarget) => { - if (metaById[worktreeId]?.hostId === hostId) { - delete metaById[worktreeId] - } - }) - return { - repo, - metaById, - removeWorktreeMeta, - runtimeStore: { - ...store, - getRepos: () => [repo], - getRepo: (id: string) => (id === repo.id ? repo : undefined), - getAllWorktreeMeta: () => metaById, - getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], - setWorktreeMeta: ({ id: worktreeId }: HostWorktreeTarget, meta: Partial) => { - metaById[worktreeId] = { ...(metaById[worktreeId] ?? makeWorktreeMeta()), ...meta } - return metaById[worktreeId] - }, - removeWorktreeMeta - } - } -} - -describe('OrcaRuntimeService worktree removal execution host', () => { - beforeEach(() => { - vi.mocked(listWorktrees).mockClear() - vi.mocked(listWorktreesStrict).mockClear() - vi.mocked(removeWorktree).mockClear() - }) - - it('refuses an SSH row whose host is unreachable instead of deleting here', async () => { - const { runtimeStore, metaById } = makeRemoteRepoStore('ssh:target-a') - const runtime = createWorktreeRemovalRuntime(runtimeStore) - - await expect( - runtime.removeManagedWorktree(TEST_WORKTREE_ID, { - force: true, - runHooks: false, - allowUnverifiedPtyStop: false, - hostId: 'ssh:target-a' - }) - ).rejects.toThrow('isn’t served by Orca’s server') - - expect(listWorktreesStrict).not.toHaveBeenCalled() - expect(removeWorktree).not.toHaveBeenCalled() - expect(metaById[TEST_WORKTREE_ID]).toBeDefined() - }) - - it('refuses a runtime row with no nested SSH target rather than deleting locally', async () => { - const { runtimeStore, metaById } = makeRemoteRepoStore('runtime:env-1') - const runtime = createWorktreeRemovalRuntime(runtimeStore) - - await expect( - runtime.removeManagedWorktree(TEST_WORKTREE_ID, { - force: true, - runHooks: false, - allowUnverifiedPtyStop: false, - hostId: 'runtime:env-1' - }) - ).rejects.toThrow('not dispatched by this process') - - expect(listWorktreesStrict).not.toHaveBeenCalled() - expect(removeWorktree).not.toHaveBeenCalled() - expect(metaById[TEST_WORKTREE_ID]).toBeDefined() - }) - - it('refuses a runtime row that also names a nested SSH target', async () => { - // `connectionId: 'target-a'` names a target inside env-1, never one on this machine. - const { runtimeStore, metaById } = makeRemoteRepoStore('runtime:env-1', { - connectionId: 'target-a' - }) - const runtime = createWorktreeRemovalRuntime(runtimeStore) - - await expect( - runtime.removeManagedWorktree(TEST_WORKTREE_ID, { - force: true, - runHooks: false, - allowUnverifiedPtyStop: false, - hostId: 'runtime:env-1' - }) - ).rejects.toThrow('not dispatched by this process') - - expect(removeWorktree).not.toHaveBeenCalled() - expect(metaById[TEST_WORKTREE_ID]).toBeDefined() - }) -}) - -class RemovalRuntime extends OrcaRuntimeService { - protected override readonly removeManagedWorktreeInFlight = new RuntimeWorktreeRemovalInFlight() - readonly helperFailure = new Error('runtime helper override') - stopAtHelper = false - stopAtStore = false - readonly purges: { - store: RuntimeStore - worktreeId: string - repoId: string - hostId?: ExecutionHostId - }[] = [] - - protected override localRemovalJobHost(runtimeStore: RuntimeStore) { - if (this.stopAtHelper) { - throw this.helperFailure - } - return super.localRemovalJobHost(runtimeStore) - } - - override requireStore(): RuntimeStore { - if (this.stopAtStore) { - throw this.helperFailure - } - return super.requireStore() - } - - currentRemovalQueue() { - return this.removeManagedWorktreeInFlight - } - - protected override async purgeRemovedWorktree( - runtimeStore: RuntimeStore, - worktreeId: string, - repoId: string, - hostId?: ExecutionHostId - ): Promise { - this.purges.push({ store: runtimeStore, worktreeId, repoId, hostId }) - } - - recoveryJobHost() { - return this.localRemovalJobHost(store) - } - - retryRemoval(record: WorktreeRemovalRecord) { - return this.retryFailedRemoval( - { kind: 'local' }, - { id: record.worktreeId, path: record.worktreePath }, - [], - {}, - {} - ) - } -} - -describe('workspace removal runtime dispatch', () => { - let runtime: RemovalRuntime - let record: WorktreeRemovalRecord - - beforeEach(() => { - _resetPendingWorktreeRemovalsForTests() - runtime = new RemovalRuntime(store) - record = { - worktreeId: TEST_WORKTREE_ID, - repoId: TEST_REPO_ID, - repoPath: TEST_REPO_PATH, - worktreePath: TEST_WORKTREE_PATH, - branch: 'feature', - head: '', - deleteBranch: false, - force: false, - requestedAt: Date.now() - } - vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - - afterEach(async () => { - await _settlePendingWorktreeRemovalsForTests() - _resetPendingWorktreeRemovalsForTests() - vi.restoreAllMocks() - }) - - it('retains runtime purge dispatch in a recovery job', () => { - runtime.recoveryJobHost().purge(record) - expect(runtime.purges).toEqual([ - { store, worktreeId: record.worktreeId, repoId: record.repoId, hostId: 'local' } - ]) - }) - - it('uses the runtime helper override before resuming an interrupted removal', () => { - runtime.stopAtHelper = true - pendingWorktreeRemovals.set(record.worktreeId, record) - expect(() => runtime.finishInterruptedWorktreeRemovals()).toThrow(runtime.helperFailure) - }) - - it('uses the runtime helper override before retrying a failed removal', async () => { - runtime.stopAtHelper = true - failedWorktreeRemovals.set(record.worktreeId, record) - await expect(runtime.retryRemoval(record)).rejects.toThrow(runtime.helperFailure) - }) - - it('captures the watcher callback and retains its job-host receiver', async () => { - const calls: { receiver: unknown; path: string }[] = [] - runtime.acquireFileWatcherRemoval = async function (this: unknown, path: string) { - calls.push({ receiver: this, path }) - return { finish: async () => {} } - } - const captured = runtime.acquireFileWatcherRemoval - const host = runtime.recoveryJobHost() - runtime.acquireFileWatcherRemoval = async () => { - throw new Error('replacement callback') - } - await host.acquireWatcherRemoval(record.worktreePath) - expect(host.acquireWatcherRemoval).toBe(captured) - expect(calls).toEqual([{ receiver: host, path: record.worktreePath }]) - }) - - it('reads the current runtime removal queue', async () => { - const replacement = runtime.currentRemovalQueue() - const failure = new Error('current removal queue') - const get = vi.spyOn(replacement, 'get').mockImplementation(() => { - throw failure - }) - runtime.stopAtStore = true - runtime['resolveWorktreeRemovalTarget'] = async () => ({ - id: TEST_WORKTREE_ID, - repoId: TEST_REPO_ID, - path: TEST_WORKTREE_PATH - }) - runtime['joinPendingWorktreeRemoval'] = () => undefined - await expect(runtime.removeManagedWorktree(TEST_WORKTREE_ID)).rejects.toBe(failure) - expect(get).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts index 9e7059a59e2..3cc3289ed47 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts @@ -1,22 +1,21 @@ // List failed-delete leftovers with their error; refuse retry until the leftover is gone. -import { existsSync } from 'node:fs' +import 'node:fs' import { readFile, realpath, writeFile, mkdir, mkdtemp, rm } from 'node:fs/promises' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { join } from 'node:path' -import { listWorktreesStrict } from '../../git/worktrees/catalog/worktree-listing' -import * as localWorktreeFilesystem from '../../workspaces/removal/local-worktree-filesystem' +import '../../git/worktrees/catalog/worktree-listing' +import '../../workspaces/removal/local-worktree-filesystem' import { removeWorktree } from '../../git/worktrees/removal/worktree-removal' -import { scanLocalRepoWorktreesForResolutionMock } from '../orca-runtime-test-mocks/setup.spec' +import '../orca-runtime-test-mocks/setup.spec' import { tmpdir } from 'node:os' import { TEST_REPO_ID, TEST_REPO_PATH } from './orca-runtime-test-fixtures.spec' import { createWorktreeRemovalRuntime } from './orca-runtime-test-scenario-builders.spec' import { _resetPendingWorktreeRemovalsForTests, _settlePendingWorktreeRemovalsForTests, - loadWorktreeRemovalRecords, - retryFailedWorktreeRemoval + loadWorktreeRemovalRecords } from '../../workspaces/removal/worktree-background-removal' import { readWorktreeRemovalRecords, @@ -24,7 +23,6 @@ import { } from '../../workspaces/removal/worktree-removal-records' const FAILURE = "error: failed to delete 'node_modules/a/LICENSE': Operation not permitted" -const FOLLOW_UP_DELETE_FAILURE = "EPERM: operation not permitted, unlink 'node_modules/a/LICENSE'" describe('runtime Delete on a failed delete’s leftover', () => { let directory = '' @@ -60,17 +58,6 @@ describe('runtime Delete on a failed delete’s leftover', () => { await rm(directory, { recursive: true, force: true }) }) - it('lists the leftover with its error, though Git no longer does', async () => { - const runtime = createWorktreeRemovalRuntime() - - const detected = await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`) - - expect(detected.worktrees.find((row) => row.id === leftoverId)).toMatchObject({ - path: leftover, - removalError: FAILURE - }) - }) - it('refuses while the folder Git no longer tracks is there, keeping the row', async () => { const runtime = createWorktreeRemovalRuntime() // The user replaced the leftover with an ordinary folder of their own. @@ -111,113 +98,4 @@ describe('runtime Delete on a failed delete’s leftover', () => { await vi.waitFor(async () => expect(await readWorktreeRemovalRecords(directory)).toEqual([])) expect(removeWorktree).not.toHaveBeenCalled() }) - - it('takes the normal delete once Git registers a checkout at the path again', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - // A new checkout at the same path must not inherit stale removal choices. - vi.mocked(listWorktreesStrict).mockResolvedValue([ - { - path: leftover, - head: 'def', - branch: 'refs/heads/other', - isBare: false, - isMainWorktree: false - } - ]) - vi.mocked(removeWorktree).mockResolvedValue({}) - const runtime = createWorktreeRemovalRuntime() - - await runtime.removeManagedWorktree(`id:${leftoverId}`, { waitForBackgroundRemoval: true }) - await _settlePendingWorktreeRemovalsForTests() - - expect(removeWorktree).toHaveBeenCalledWith(TEST_REPO_PATH, leftover, false, expect.anything()) - expect(existsSync(join(leftover, 'node_modules'))).toBe(true) - expect(await readWorktreeRemovalRecords(directory)).toEqual([]) - }) - - it('joins a retry another client started while this Delete listed Git', async () => { - const otherClientsRetry = vi.fn(async () => ({})) - vi.mocked(listWorktreesStrict).mockImplementationOnce(async () => { - void retryFailedWorktreeRemoval(leftoverId, 'local', () => ({ - run: otherClientsRetry, - publish: () => {} - })) - return [] - }) - const runtime = createWorktreeRemovalRuntime() - - await expect( - runtime.removeManagedWorktree(`id:${leftoverId}`, { waitForBackgroundRemoval: true }) - ).resolves.toEqual({}) - - expect(otherClientsRetry).toHaveBeenCalledTimes(1) - expect(existsSync(join(leftover, 'node_modules'))).toBe(true) - expect(removeWorktree).not.toHaveBeenCalled() - }) -}) - -describe('runtime listing straight after a delete fails partway', () => { - let directory = '' - let leftover = '' - let leftoverId = '' - - beforeEach(async () => { - vi.clearAllMocks() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - directory = await realpath(await mkdtemp(join(tmpdir(), 'orca-runtime-failed-listing-'))) - leftover = join(directory, 'feature') - leftoverId = `${TEST_REPO_ID}::${leftover}` - await mkdir(join(leftover, 'node_modules'), { recursive: true }) - await loadWorktreeRemovalRecords(directory) - }) - - afterEach(async () => { - await _settlePendingWorktreeRemovalsForTests() - _resetPendingWorktreeRemovalsForTests() - vi.restoreAllMocks() - await rm(directory, { recursive: true, force: true }) - }) - - it('shows the failed row with its error, not the scan cached before the delete', async () => { - const registered = { - path: leftover, - head: 'abc', - branch: 'refs/heads/feature', - isBare: false, - isMainWorktree: false - } - const gitLists = (worktrees: (typeof registered)[]): void => { - vi.mocked(listWorktreesStrict).mockResolvedValue(worktrees) - scanLocalRepoWorktreesForResolutionMock.mockResolvedValue({ ok: true, worktrees }) - } - gitLists([registered]) - const runtime = createWorktreeRemovalRuntime() - const listLeftover = async () => - (await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`)).worktrees.find( - (row) => row.id === leftoverId - ) - expect(await listLeftover()).not.toHaveProperty('removalError') - vi.mocked(removeWorktree).mockImplementation(async () => { - // Git drops the registration, then fails on a file it cannot delete. - gitLists([]) - throw new Error(FAILURE) - }) - // Orca's follow-up delete of the folder Git left also fails, so the row stays listed. - vi.spyOn(localWorktreeFilesystem, 'removeLocalWorktreePath').mockRejectedValueOnce( - new Error(FOLLOW_UP_DELETE_FAILURE) - ) - - await expect( - runtime.removeManagedWorktree(`id:${leftoverId}`, { - force: true, - waitForBackgroundRemoval: true - }) - ).rejects.toThrow(FOLLOW_UP_DELETE_FAILURE) - await _settlePendingWorktreeRemovalsForTests() - - expect(await listLeftover()).toMatchObject({ - path: leftover, - removalError: expect.stringContaining(FOLLOW_UP_DELETE_FAILURE) - }) - }) }) diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 0cbd6235854..1af07672b22 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -54,7 +54,6 @@ await import('./orca-runtime-tests/terminal-creation-and-readiness-part-10.spec' await import('./orca-runtime-tests/terminal-creation-and-readiness-part-11.spec') await import('./orca-runtime-tests/conpty-stream-read.spec') await import('./orca-runtime-tests/terminal-creation-and-readiness-part-12.spec') -await import('./orca-runtime-tests/terminal-spawn-dispatch.spec') await import('./orca-runtime-tests/terminal-output-and-worker-recovery.spec') await import('./orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec') await import('./orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec') @@ -81,10 +80,7 @@ await import('./orca-runtime-tests/mobile-session-tabs-part-10.spec') await import('./orca-runtime-tests/mobile-session-tabs-part-11.spec') await import('./orca-runtime-tests/mobile-session-tabs-part-12.spec') await import('./orca-runtime-tests/mobile-session-tabs-part-13.spec') -await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec') -await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec') await import('./orca-runtime-tests/mobile-session-tabs-empty-headless-snapshot.spec') -await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec') await import('./orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec') await import('./orca-runtime-tests/mobile-session-tabs-targeted-agent-resume.spec') await import('./orca-runtime-tests/mobile-session-tabs-headless-wake-report.spec') @@ -121,6 +117,5 @@ await import('./orca-runtime-tests/worktree-removal-and-reconciliation-part-03.s await import('./orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec') await import('./orca-runtime-tests/worktree-removal-archive-hook-gate.spec') await import('./orca-runtime-tests/worktree-removal-failed-retry.spec') -await import('./orca-runtime-tests/worktree-removal-execution-host.spec') await import('./orca-runtime-tests/targeting-and-resilience.spec') await import('./orca-runtime-tests/worktree-scan-cache-ttl.spec') diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-authority-contracts.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-authority-contracts.test.ts index 1efb9650d6d..a4bf8c183ef 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-authority-contracts.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-authority-contracts.test.ts @@ -1,5 +1,3 @@ -import { registerWorkerReleaseOwnershipGuardTests } from './worker-release-ownership-guard.spec' import { registerWorkerReleaseRuntimeIncarnationTests } from './worker-release-runtime-incarnation.spec' -registerWorkerReleaseOwnershipGuardTests() registerWorkerReleaseRuntimeIncarnationTests() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-ownership-guard.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-ownership-guard.spec.ts deleted file mode 100644 index 82ed3d0b854..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-ownership-guard.spec.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeTerminalWait } from '../../../../../../shared/runtime-types' -import { reconcileRequestedWorkerTerminalReleases } from '../../../../orchestration/terminal-authority/release/worker-terminal-release-reconciliation' -import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' - -export function registerWorkerReleaseOwnershipGuardTests(): void { - describe('workerRelease on a retained resource whose process exited', () => { - const harness = createOrchestrationWorkerReleaseHarness() - beforeEach(() => harness.setup()) - afterEach(() => harness.cleanup()) - - it('does not release a terminal the user kept open', async () => { - const { dispatchId } = await harness.startSettledWorker('succeeded') - await harness.call('orchestration.workerKeepOpen', { - paneKey: harness.workerPaneKey, - keep: true - }) - - // The agent process later exits on its own; the user's pane and scrollback remain. - harness.inspectProcessLiveness.mockResolvedValue('exited') - const receipt = (await harness.call('orchestration.workerRelease', { - dispatch: dispatchId - })) as { state: string; reason?: string; archive: unknown } - - expect(receipt.state).toBe('retained') - expect(receipt.reason).toBe('user_kept') - expect(harness.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).toBe( - 'retained' - ) - }) - - it.each(['transferred', 'external'] as const)( - 'does not release a %s resource on an exited process', - async (ownershipState) => { - const { dispatchId } = await harness.startSettledWorker('succeeded') - const resource = harness.db.getWorkerTerminalResourceByOwner(dispatchId)! - harness.db.db - .prepare('UPDATE worker_terminal_resources SET ownership_state = ? WHERE id = ?') - .run(ownershipState, resource.id) - - harness.inspectProcessLiveness.mockResolvedValue('exited') - const receipt = (await harness.call('orchestration.workerRelease', { - dispatch: dispatchId - })) as { state: string } - - expect(receipt.state).toBe('retained') - const after = harness.db.getWorkerTerminalResourceByOwner(dispatchId) - expect(after?.ownership_state).toBe(ownershipState) - expect(after?.release_state).not.toBe('released') - } - ) - - it('records the archive as unavailable rather than retaining the pane forever', async () => { - const { dispatchId } = await harness.startWorker() - // Abandoned workers never reach `requested`, the only state that writes an archive. - expect(harness.db.abandonWorkerDispatch(dispatchId, 'epoch_test').disposition).toBe( - 'abandoned' - ) - expect(harness.db.getWorkerTerminalArchive(dispatchId)).toBeFalsy() - - harness.inspectProcessLiveness.mockResolvedValue('exited') - const receipt = (await harness.call('orchestration.workerRelease', { - dispatch: dispatchId - })) as { state: string; archive: { status: string | null } | null } - - expect(receipt.state).toBe('released') - expect(receipt.archive?.status).toBe('unavailable') - }) - - it('exits retention after a recovery abandon even once the user retained it', async () => { - const { dispatchId } = await harness.startWorker() - harness.db.reconcileMissingWorkerTerminal(dispatchId, 'terminal gone') - expect(harness.db.getWorkerDispatch(dispatchId)?.state).toBe('abandoned') - harness.inspectProcessLiveness.mockResolvedValue('exited') - - // retain deletes the archive and parks the row in `retained`: still no route back to `requested`. - await harness.call('orchestration.workerRetain', { dispatch: dispatchId }) - const receipt = (await harness.call('orchestration.workerRelease', { - dispatch: dispatchId - })) as { state: string } - - expect(receipt.state).toBe('released') - }) - - it('still refuses when an archive names a different resource', async () => { - const { dispatchId } = await harness.startWorker() - const resource = harness.db.getWorkerTerminalResourceByOwner(dispatchId)! - expect(harness.db.abandonWorkerDispatch(dispatchId, 'epoch_test').disposition).toBe( - 'abandoned' - ) - harness.db.storeWorkerTerminalArchive({ - dispatchId, - resourceId: `${resource.id}-other`, - kind: 'terminal_tail', - content: 'tail' - }) - - harness.inspectProcessLiveness.mockResolvedValue('exited') - const receipt = (await harness.call('orchestration.workerRelease', { - dispatch: dispatchId - })) as { state: string } - - expect(receipt.state).toBe('retained') - expect(harness.db.getWorkerTerminalResourceByOwner(dispatchId)?.release_state).not.toBe( - 'released' - ) - }) - }) - - const READY_WAIT = { - handle: 'term_worker', - condition: 'tui-idle', - satisfied: true, - status: 'running', - exitCode: null - } satisfies RuntimeTerminalWait - - describe('Antigravity orchestration worker lifecycle', () => { - const h = createOrchestrationWorkerReleaseHarness() - - afterEach(() => h.cleanup()) - - it('owns the terminal immediately and delays prompt delivery until AGY is ready', async () => { - h.setup() - const readiness = h.deferred() - vi.spyOn(h.runtime, 'waitForTerminal').mockReturnValue(readiness.promise) - - const pending = h.startWorker({ agent: 'antigravity' }) - await vi.waitFor(() => expect(h.runtime.waitForTerminal).toHaveBeenCalled()) - - expect(h.runtime.createTerminal).toHaveBeenCalledWith( - 'id:repo::worktree', - expect.objectContaining({ startupAgent: 'antigravity', surfaceOwner: false }) - ) - expect(h.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - expect(h.db.listWorkerTerminalResources({})[0]?.resource).toMatchObject({ - ownership_state: 'owned', - terminal_handle: 'term_worker' - }) - - readiness.resolve(READY_WAIT) - await expect(pending).resolves.toEqual( - expect.objectContaining({ dispatchId: expect.any(String) }) - ) - expect(h.runtime.sendTerminalAgentPrompt).toHaveBeenCalledTimes(1) - }) - - it('stops only the owned AGY terminal', async () => { - h.setup() - const { dispatchId } = await h.startWorker({ agent: 'antigravity' }) - - await expect( - h.call('orchestration.workerStop', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'stopped', processAction: 'closed_agent_terminal' }) - expect(h.runtime.closeTerminal).toHaveBeenCalledOnce() - expect(h.runtime.closeTerminal).toHaveBeenCalledWith('term_worker') - }) - - it('releases an owned AGY terminal and recovers a transient stale endpoint', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker('succeeded', { - agent: 'antigravity' - }) - vi.mocked(h.runtime.closeTerminal).mockRejectedValueOnce(new Error('Multiplexer disposed')) - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'release_pending', processAction: 'none' }) - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'owned', - release_state: 'releasing' - }) - - await expect(reconcileRequestedWorkerTerminalReleases(h.runtime)).resolves.toMatchObject({ - attempted: 1, - released: 1 - }) - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - release_state: 'released' - }) - expect(h.runtime.closeTerminal).toHaveBeenCalledTimes(2) - expect(h.runtime.closeTerminal).toHaveBeenNthCalledWith(2, 'term_worker') - }) - - it('fails closed on a stale AGY handle and releases it on a fresh retry', async () => { - h.setup() - const { dispatchId } = await h.startSettledWorker('succeeded', { - agent: 'antigravity' - }) - vi.mocked(h.runtime.showTerminal).mockRejectedValueOnce(new Error('terminal_handle_stale')) - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'release_unknown' }) - expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ - ownership_state: 'owned', - release_state: 'unknown' - }) - - await expect( - h.call('orchestration.workerRelease', { dispatch: dispatchId }) - ).resolves.toMatchObject({ state: 'released' }) - expect(h.runtime.closeTerminal).toHaveBeenCalledWith('term_worker') - }) - }) -} diff --git a/src/main/runtime/workspaces/removal/worktree-teardown-daemon-inventory.test.ts b/src/main/runtime/workspaces/removal/worktree-teardown-daemon-inventory.test.ts deleted file mode 100644 index bbc23a08619..00000000000 --- a/src/main/runtime/workspaces/removal/worktree-teardown-daemon-inventory.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createAdapter } from '../../../daemon/providers/routing/testing/daemon-pty-router-test-fixture' -import { DaemonPtyRouter } from '../../../daemon/providers/routing/daemon-pty-router' -import { DegradedDaemonPtyProvider } from '../../../daemon/providers/routing/degraded-daemon-pty-provider' -import { killAllProcessesForWorktree } from './worktree-teardown' -import { registerPty, unregisterPty } from '../../../memory/pty-registry' - -const worktreeId = 'repo::/projects/fix-favicon-clapping' -const unrelatedId = 'repo::/projects/team-automations@@duplicate' -const targetId = `${worktreeId}@@terminal` - -function setup(kind: 'router' | 'degraded', targetIds: string[] = []) { - const currentSessions = [unrelatedId, ...targetIds] - const legacySessions = [unrelatedId] - const current = createAdapter('current', currentSessions) - const legacy = createAdapter('legacy', legacySessions) - const provider = - kind === 'router' - ? new DaemonPtyRouter({ current, legacy: [legacy] }) - : new DegradedDaemonPtyProvider({ - current, - legacy: [legacy], - fallback: createAdapter('fallback', []) - }) - return { provider, current, legacy, currentSessions, legacySessions } -} - -describe.each(['router', 'degraded'] as const)('workspace deletion with %s inventory', (kind) => { - afterEach(() => { - unregisterPty(targetId) - }) - - it('stops the target terminal and preserves ambiguous sessions in other workspaces', async () => { - const { provider, currentSessions, legacySessions } = setup(kind, [targetId]) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true - }) - ).resolves.toEqual({ runtimeStopped: 0, providerStopped: 1, registryStopped: 0 }) - expect(currentSessions).toEqual([unrelatedId]) - expect(legacySessions).toEqual([unrelatedId]) - }) - - it('refuses an ambiguous target even after establishing its legacy input route', async () => { - const { provider, currentSessions, legacySessions } = setup(kind) - legacySessions.push(targetId) - await (provider instanceof DaemonPtyRouter - ? provider.discoverLegacySessions() - : provider.discoverDaemonSessions()) - currentSessions.push(targetId) - await provider.listProcesses({ includeUnrouted: true }) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true - }) - ).rejects.toThrow(`Terminal session owner could not be verified: ${targetId}`) - expect(currentSessions).toContain(targetId) - expect(legacySessions).toContain(targetId) - }) - - it('refuses a scoped target whose duplicate is routed to another workspace', async () => { - const { provider, current, legacy } = setup(kind) - vi.mocked(legacy.listProcesses).mockResolvedValue([ - { - id: 'floating', - incarnationId: 'legacy', - cwd: '', - title: 'shell', - worktreeId: 'repo::/projects/other' - } - ]) - await (provider instanceof DaemonPtyRouter - ? provider.discoverLegacySessions() - : provider.discoverDaemonSessions()) - vi.mocked(current.listProcesses).mockResolvedValue([ - { id: 'floating', incarnationId: 'current', cwd: '', title: 'shell', worktreeId } - ]) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true - }) - ).rejects.toThrow('Terminal session owner could not be verified: floating') - expect(current.shutdown).not.toHaveBeenCalled() - expect(legacy.shutdown).not.toHaveBeenCalled() - }) - - it('does not omit another live target generation even when the input owner is exact', async () => { - const { provider, current, legacy } = setup(kind) - const old = { id: targetId, incarnationId: 'old', cwd: '', title: 'old' } - vi.mocked(legacy.listProcesses).mockResolvedValue([old]) - await (provider instanceof DaemonPtyRouter - ? provider.discoverLegacySessions() - : provider.discoverDaemonSessions()) - vi.mocked(current.listProcesses).mockResolvedValue([ - { id: targetId, incarnationId: 'new', cwd: '', title: 'new' } - ]) - await expect(provider.listProcesses()).resolves.toEqual([old]) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true - }) - ).rejects.toThrow(`Terminal session owner could not be verified: ${targetId}`) - expect(current.shutdown).not.toHaveBeenCalled() - expect(legacy.shutdown).not.toHaveBeenCalled() - }) - - it.each(['metadata', 'cwd'] as const)( - 'retains %s ownership for older terminal IDs', - async (via) => { - const { provider, current, currentSessions, legacySessions } = setup(kind, ['floating']) - vi.mocked(current.listProcesses).mockImplementation(async () => - currentSessions.map((id) => ({ - id, - cwd: id === 'floating' && via === 'cwd' ? '/projects/fix-favicon-clapping/nested' : '', - title: 'shell', - ...(id === 'floating' && via === 'metadata' ? { worktreeId } : {}) - })) - ) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true - }) - ).resolves.toEqual({ runtimeStopped: 0, providerStopped: 1, registryStopped: 0 }) - expect(currentSessions).toEqual([unrelatedId]) - expect(legacySessions).toEqual([unrelatedId]) - } - ) - - it('verifies an absent stale terminal without requiring unrelated route authority', async () => { - const { provider, currentSessions, legacySessions } = setup(kind) - const onPtyStopped = vi.fn() - vi.spyOn(provider, 'shutdown').mockRejectedValue(new Error('shutdown reply lost')) - registerPty({ ptyId: targetId, worktreeId, sessionId: null, paneKey: null, pid: 100 }) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true, - onPtyStopped - }) - ).resolves.toEqual({ runtimeStopped: 0, providerStopped: 0, registryStopped: 0 }) - expect(onPtyStopped).toHaveBeenCalledExactlyOnceWith(targetId) - expect(currentSessions).toEqual([unrelatedId]) - expect(legacySessions).toEqual([unrelatedId]) - }) - - it('refuses deletion when a failed shutdown leaves the target terminal live', async () => { - const { provider, currentSessions } = setup(kind, [targetId]) - vi.spyOn(provider, 'shutdown').mockRejectedValue(new Error('shutdown reply lost')) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true - }) - ).rejects.toThrow(`still live: ${targetId}`) - expect(currentSessions).toContain(targetId) - }) - - it('still refuses deletion when a daemon cannot supply its inventory', async () => { - const { provider, legacy } = setup(kind) - vi.mocked(legacy.listProcesses).mockRejectedValue(new Error('daemon unavailable')) - - await expect( - killAllProcessesForWorktree(worktreeId, { - localProvider: provider, - requirePhysicalStop: true - }) - ).rejects.toThrow('daemon unavailable') - }) -}) diff --git a/src/main/runtime/workspaces/sleep/worktree-terminal-sleep-host-twin.test.ts b/src/main/runtime/workspaces/sleep/worktree-terminal-sleep-host-twin.test.ts deleted file mode 100644 index 46900b7f768..00000000000 --- a/src/main/runtime/workspaces/sleep/worktree-terminal-sleep-host-twin.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -// A same-id SSH twin is a different workspace: its spawn must not wake or be refused by this computer's sleep. -import { describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' -import { spawnWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' -import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' -import { WORKTREE_TERMINALS_SLEEPING_ERROR } from '../../../../shared/workspace-sleep' -import { resolveWorktreeLaunchHost } from '../catalog/worktree-launch-host-repo' -import { resolveSleepScope } from '../../terminal/stop/worktree-terminal-sleep-key' - -// Fragments stay side-effect ordered: mocks, then lifecycle, then fixtures. -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -const { OrcaRuntimeService } = await import('../../orca-runtime') -await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { TEST_WORKTREE_ID, TEST_WORKTREE_PATH, store } = - await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -// Runtime-nested SSH routes are not dialled from this process. -const nestedSshRepo = { - ...store.getRepos()[0], - executionHostId: 'runtime:env-a' as const, - connectionId: 'ssh-nested' -} -const nestedSshStore = { - ...store, - getRepo: () => nestedSshRepo, - getRepos: () => [nestedSshRepo] -} - -// A cwd alone never files a terminal for a worktree-scoped stop (#36716); the daemon id names the owner. -const LOCAL_PTY_ID = `${TEST_WORKTREE_ID}@@local` -const TWIN_PTY_ID = toAppSshPtyId('ssh-twin', 'relay-pty-1') -const twinPty = { - id: TWIN_PTY_ID, - cwd: TEST_WORKTREE_PATH, - title: 'Shell', - worktreeId: TEST_WORKTREE_ID -} - -async function sleepLocalCopy(runtimeStore: typeof store = store, twinLive = false) { - const runtime = new OrcaRuntimeService(runtimeStore) - const events: RuntimeClientEvent[] = [] - runtime.onClientEvent((event) => events.push(event)) - const twin = twinLive ? [twinPty] : [] - const processLists = [ - [{ id: LOCAL_PTY_ID, cwd: TEST_WORKTREE_PATH, title: 'Shell' }, ...twin], - twin - ] - const stopAndWait = vi.fn(async (ptyId: string) => { - runtime.onPtyExit(ptyId, -1) - return true - }) - runtime.setPtyController({ - write: () => true, - kill: () => false, - stopAndWait, - getForegroundProcess: async () => null, - listProcesses: async () => processLists.shift() ?? [] - }) - await expect(runtime.sleepTerminalsForWorktree(`id:${TEST_WORKTREE_ID}`)).resolves.toMatchObject({ - stopped: 1, - postStopVerified: true - }) - const phases = (): string[] => - events.flatMap((event) => (event.type === 'worktreeTerminalSleepState' ? [event.phase] : [])) - return { runtime, phases, stopAndWait } -} - -describe('worktree terminal sleep across same-id host twins', () => { - it("a spawn on the SSH twin neither wakes nor is refused by this computer's sleep", async () => { - const { runtime, phases } = await sleepLocalCopy() - const twin = spawnWorktreeTarget(TEST_WORKTREE_ID, 'ssh-twin') - - const releaseRefusable = await runtime.acquireWorktreeTerminalSpawn(twin, { - refuseSleptWorktree: true - }) - releaseRefusable() - const releaseTwin = await runtime.acquireWorktreeTerminalSpawn(twin) - releaseTwin() - - expect(phases()).not.toContain('woken') - expect(runtime.getTerminalSleepClientEventSnapshot()).toEqual([ - expect.objectContaining({ worktreeId: TEST_WORKTREE_ID, phase: 'committed' }) - ]) - }) - - it("this computer's own spawn still refuses or wakes its sleep", async () => { - const { runtime, phases } = await sleepLocalCopy() - const local = spawnWorktreeTarget(TEST_WORKTREE_ID, null) - - await expect( - runtime.acquireWorktreeTerminalSpawn(local, { refuseSleptWorktree: true }) - ).rejects.toThrow(WORKTREE_TERMINALS_SLEEPING_ERROR) - const release = await runtime.acquireWorktreeTerminalSpawn(local) - release() - - expect(phases()).toContain('woken') - expect(runtime.getTerminalSleepClientEventSnapshot()).toEqual([]) - }) - - it("a runtime-stamped project's launch-scope spawn refuses and wakes its sleep", async () => { - const { runtime, phases } = await sleepLocalCopy(nestedSshStore) - // The connection the launch scope hands the spawn, not one predicted from the row. - const launch = resolveWorktreeLaunchHost(nestedSshStore.getRepos(), { - repoId: nestedSshRepo.id - }) - expect(launch.kind).toBe('resolved') - const nested = spawnWorktreeTarget( - TEST_WORKTREE_ID, - launch.kind === 'resolved' ? launch.connectionId : undefined - ) - - await expect( - runtime.acquireWorktreeTerminalSpawn(nested, { refuseSleptWorktree: true }) - ).rejects.toThrow(WORKTREE_TERMINALS_SLEEPING_ERROR) - const release = await runtime.acquireWorktreeTerminalSpawn(nested) - release() - - expect(phases()).toContain('woken') - }) - - it("sleeping this computer's copy leaves the SSH twin's live terminal running and unfiled", async () => { - const { runtime, phases, stopAndWait } = await sleepLocalCopy(store, true) - - expect(stopAndWait.mock.calls.map(([ptyId]) => ptyId)).toEqual([LOCAL_PTY_ID]) - expect(runtime.getTerminalSleepClientEventSnapshot()).toEqual([ - expect.objectContaining({ phase: 'committed', ptyIds: [LOCAL_PTY_ID] }) - ]) - const release = await runtime.acquireWorktreeTerminalSpawn( - spawnWorktreeTarget(TEST_WORKTREE_ID, 'ssh-twin') - ) - release() - expect(phases()).not.toContain('woken') - }) - - it('refuses to sleep a worktree whose rival rows disagree about its host', () => { - const local = store.getRepos()[0] - const rivals = [local, { ...local, connectionId: 'ssh-twin' }] - - expect(() => resolveSleepScope(rivals, { id: TEST_WORKTREE_ID, repoId: local.id })).toThrow( - 'worktree_execution_host_unresolved' - ) - }) -}) diff --git a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.test.ts b/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.test.ts deleted file mode 100644 index c7dfda25ce8..00000000000 --- a/src/main/runtime/workspaces/startup/runtime-local-worktree-terminal-startup.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { Worktree } from '../../../../shared/worktree/types' -import { startRuntimeLocalWorktreeTerminals } from './runtime-local-worktree-terminal-startup' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' - -const repo: Repo = { - id: 'repo-1', - path: '/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 -} - -const worktree: Worktree = { - id: 'worktree-1', - repoId: repo.id, - path: '/worktree', - head: 'abc', - branch: 'feature', - isBare: false, - isMainWorktree: false, - displayName: 'feature', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1 -} - -type StartupArgs = Parameters[0] - -function createPorts() { - const createTerminal = vi.fn().mockResolvedValue({ - handle: 'term-1', - worktreeId: worktree.id, - title: null - }) - const ports: StartupArgs['ports'] = { - canSpawn: true, - createTerminal, - pasteDraft: vi.fn(), - sendFollowup: vi.fn(), - provision: vi.fn().mockResolvedValue({ setupSpawned: false, setupTerminalHandle: null }), - activate: vi.fn() - } - return { createTerminal, ports } -} - -const TAB_ID = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' -const LEAF_ID = '3f2504e0-4f89-41d3-9a0c-0305e82c3301' - -async function startupTerminalOptions( - startupPaneKey?: string, - request: Partial = {} -) { - const { createTerminal, ports } = createPorts() - const observe = vi.fn() - const followup = { agent: 'codex' as const, prompt: 'task' } - const terminal = { - handle: 'term-1', - worktreeId: worktree.id, - title: null, - ptyId: 'pty-startup', - incarnationId: 'inc-startup', - isReattach: true as const - } - createTerminal.mockResolvedValueOnce(terminal) - await startRuntimeLocalWorktreeTerminals({ - request: { - onStartupTerminalCreated: observe, - repoSelector: `id:${repo.id}`, - name: worktree.displayName, - ...(startupPaneKey ? { startupPaneKey } : {}), - ...request - }, - repo, - worktree, - createdWithAgent: 'codex', - startup: { command: 'codex' }, - startupFollowup: followup, - ports - }) - expect(observe).toHaveBeenCalledExactlyOnceWith(terminal) - expect(ports.sendFollowup).toHaveBeenCalledExactlyOnceWith(terminal.handle, followup, terminal) - return createTerminal.mock.calls[0]?.[1] ?? {} -} - -describe('startRuntimeLocalWorktreeTerminals reserved startup pane', () => { - // The local, folder and remote creates each forward this separately, so nothing above them - // catches the one that stops. - it('creates the startup terminal under the pane the caller reserved', async () => { - expect(await startupTerminalOptions(`${TAB_ID}:${LEAF_ID}`)).toMatchObject({ - tabId: TAB_ID, - leafId: LEAF_ID - }) - }) - - it('titles the startup tab with the title the caller named', async () => { - expect(await startupTerminalOptions(undefined, { startupTitle: 'Nightly' })).toMatchObject({ - title: 'Nightly' - }) - }) - - it('leaves the pane to the runtime when none was reserved', async () => { - const options = await startupTerminalOptions() - expect(options).not.toHaveProperty('tabId') - expect(options).not.toHaveProperty('leafId') - }) -}) - -describe('startRuntimeLocalWorktreeTerminals default shell seeding', () => { - it.each([{}, { activate: true }, { runHooks: true }])( - 'preserves an explicit promised chat during setup (%j)', - async (activation) => { - const { ports } = createPorts() - await startRuntimeLocalWorktreeTerminals({ - request: { repoSelector: repo.id, name: 'chat', ...activation }, - repo, - worktree, - setup: { runnerScriptPath: '/repo/setup.sh', envVars: {} }, - promisedAgentChat: true, - ports - }) - expect(ports.provision).toHaveBeenCalledWith( - expect.objectContaining({ callerProvidesSurface: true }) - ) - } - ) - - it.each([false, true])( - 'passes the submitted setup-only choice to the host (%s)', - async (setupOnly) => { - const { ports } = createPorts() - await startRuntimeLocalWorktreeTerminals({ - request: { - repoSelector: `id:${repo.id}`, - name: 'choice', - setupOnly, - awaitTerminalProvisioning: true - }, - repo, - worktree, - setup: { runnerScriptPath: '/repo/setup.sh', envVars: {} }, - ports - }) - expect(ports.provision).toHaveBeenCalledWith(expect.objectContaining({ setupOnly })) - } - ) - - it.each([false, true])( - 'provisions a headless activated workspace without a viewer (setup=%s)', - async (withSetup) => { - const { ports } = createPorts() - ports.provisionInBackground = () => true - const setup = withSetup ? { runnerScriptPath: '/repo/setup.sh', envVars: {} } : undefined - await startRuntimeLocalWorktreeTerminals({ - request: { repoSelector: `id:${repo.id}`, name: 'headless', activate: true }, - repo, - worktree, - setup, - ports - }) - expect(ports.provision).toHaveBeenCalledWith( - expect.objectContaining({ - worktreeId: worktree.id, - hasStartupTerminal: false, - surfaceOwner: false, - ...(setup ? { setup } : {}) - }) - ) - expect(ports.createTerminal).not.toHaveBeenCalled() - } - ) - - it.each([ - ['Blank Terminal', undefined, 1], - ['an agent', 'codex' as const, 0] - ])('seeds a background shell for %s selection only', async (_label, agent, expectedCalls) => { - const { createTerminal, ports } = createPorts() - - await startRuntimeLocalWorktreeTerminals({ - request: { repoSelector: `id:${repo.id}`, name: worktree.displayName }, - repo, - worktree, - ...(agent ? { createdWithAgent: agent } : {}), - ports - }) - - expect(createTerminal).toHaveBeenCalledTimes(expectedCalls) - if (expectedCalls > 0) { - expect(createTerminal).toHaveBeenCalledWith(`id:${worktree.id}`, { surfaceOwner: false }) - } - }) - - it('hands failed startup and defaults to renderer before host provisioning', async () => { - const { ports, createTerminal } = createPorts() - createTerminal.mockRejectedValueOnce(new Error('pty unavailable')) - const setup = { runnerScriptPath: '/repo/setup.sh', envVars: {} } - const startup = { command: 'codex' } - const defaultTabs = { - runCommands: true, - tabs: [{ title: 'Dev', command: 'pnpm dev' }] - } - await startRuntimeLocalWorktreeTerminals({ - request: { - repoSelector: repo.id, - name: 'recover', - activate: true, - awaitTerminalProvisioning: true - }, - repo, - worktree, - startup, - setup, - defaultTabs, - ports - }) - expect(createTerminal).toHaveBeenCalledTimes(1) - if (!ORCA_LAYOUT_OWNER_IS_MAIN) { - expect(ports.provision).not.toHaveBeenCalled() - expect(ports.activate).toHaveBeenCalledWith(repo.id, worktree.id, startup, setup, defaultTabs) - return - } - // Main keeps the agent's pane to show the failure and lays setup and default tabs out itself. - expect(createTerminal).toHaveBeenCalledWith( - `id:${worktree.id}`, - expect.objectContaining({ command: 'codex', keepPaneOnStartFailure: true }) - ) - expect(ports.provision).toHaveBeenCalledWith( - expect.objectContaining({ - setup, - defaultTabs, - primaryTerminalHandle: null, - hasStartupTerminal: true - }) - ) - expect(ports.activate).toHaveBeenCalledWith( - repo.id, - worktree.id, - undefined, - undefined, - undefined - ) - }) - - it('does not treat agent attribution alone as a promised chat on activation', async () => { - const { ports } = createPorts() - await startRuntimeLocalWorktreeTerminals({ - request: { repoSelector: repo.id, name: 'attributed', activate: true }, - repo, - worktree, - createdWithAgent: 'codex', - ports - }) - expect(ports.activate).toHaveBeenCalledWith( - repo.id, - worktree.id, - undefined, - undefined, - undefined - ) - }) -}) - -describe('startRuntimeLocalWorktreeTerminals held startup terminal (E9)', () => { - it('names the stopped WSL distro in the warning, not the raw hold code', async () => { - const { createTerminal, ports } = createPorts() - createTerminal.mockRejectedValueOnce(new Error('terminal_held_wsl_distro_stopped:Ubuntu')) - - const result = await startRuntimeLocalWorktreeTerminals({ - request: { repoSelector: `id:${repo.id}`, name: worktree.displayName }, - repo, - worktree, - startup: { command: 'codex' }, - ports - }) - - expect(result.warning).toBe( - "Failed to create the startup terminal for /worktree: The WSL distro Ubuntu is stopped, so Orca didn't start this terminal. Start the distro, then try again." - ) - expect(result.warning).not.toContain('terminal_held_wsl_distro') - }) -}) diff --git a/src/main/runtime/workspaces/startup/runtime-worktree-terminal-provisioning.test.ts b/src/main/runtime/workspaces/startup/runtime-worktree-terminal-provisioning.test.ts deleted file mode 100644 index 87568757279..00000000000 --- a/src/main/runtime/workspaces/startup/runtime-worktree-terminal-provisioning.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - provisionWorktreeTerminals, - type WorktreeTerminalProvisioningHost -} from './runtime-worktree-terminal-provisioning' - -const DEFAULT_TABS = { - runCommands: true, - tabs: [ - { title: 'Dev', command: 'pnpm dev', color: '#ff0000' }, - { title: 'Tests', command: 'pnpm test', color: '#00ff00' } - ] -} - -function fakeHost() { - let created = 0 - return { - canSpawn: () => true, - createTerminal: vi.fn(async (_selector: string, _options: Record) => { - created += 1 - return { handle: `term_${created}` } - }), - setTabTitle: vi.fn(async (_handle: string, _title: string) => {}), - setTabColor: vi.fn(async (_handle: string, _color: string) => {}), - getPtyId: () => undefined, - recordSetupCompletionToken: vi.fn() - } satisfies Partial> -} - -function provision(host: ReturnType, startup: boolean) { - return provisionWorktreeTerminals(host, { - worktreeSelector: 'id:wt-1', - worktreeId: 'wt-1', - worktreePath: '/worktrees/wt-1', - defaultTabs: DEFAULT_TABS, - primaryTerminalHandle: startup ? 'term_agent' : null, - hasStartupTerminal: startup, - setupCommandPlatform: 'posix' - }) -} - -describe('default tabs beside the agent a create started', () => { - it('makes the agent the first default tab, as the window lays it out', async () => { - const host = fakeHost() - await provision(host, true) - - expect(host.setTabTitle).toHaveBeenCalledWith('term_agent', 'Dev') - expect(host.setTabColor).toHaveBeenCalledWith('term_agent', '#ff0000') - // The first template's command never runs beside the agent; only the rest are created. - expect(host.createTerminal).toHaveBeenCalledTimes(1) - expect(host.createTerminal).toHaveBeenCalledWith('id:wt-1', { - title: 'Tests', - command: 'pnpm test' - }) - }) - - it('dresses every created default tab the same way', async () => { - const host = fakeHost() - await provision(host, false) - - expect(host.createTerminal).toHaveBeenCalledTimes(2) - expect(host.setTabTitle.mock.calls).toEqual([ - ['term_1', 'Dev'], - ['term_2', 'Tests'] - ]) - expect(host.setTabColor.mock.calls).toEqual([ - ['term_1', '#ff0000'], - ['term_2', '#00ff00'] - ]) - }) - - it('still colors the tab and creates the rest when titling fails', async () => { - const host = fakeHost() - host.setTabTitle.mockRejectedValue(new Error('terminal_tab_unresolved')) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - await expect(provision(host, true)).resolves.toEqual({ - setupSpawned: false, - setupTerminalHandle: null - }) - - expect(host.setTabColor).toHaveBeenCalledWith('term_agent', '#ff0000') - expect(host.createTerminal).toHaveBeenCalledTimes(1) - expect(warn).toHaveBeenCalledWith( - '[worktree-create] Failed to title a default tab for wt-1:', - expect.any(Error) - ) - warn.mockRestore() - }) -}) - -const setup = { runnerScriptPath: '/repo/.orca/setup.sh', envVars: {} } - -function createHost(): { - host: WorktreeTerminalProvisioningHost - titles: () => (string | undefined)[] -} { - const createTerminal = vi.fn(async () => ({ - handle: `term-${createTerminal.mock.calls.length}` - })) - return { - host: { - canSpawn: () => true, - createTerminal, - setTabTitle: vi.fn(async () => {}), - setTabColor: vi.fn(async () => {}), - getPtyId: () => undefined, - recordSetupCompletionToken: vi.fn() - }, - titles: () => createTerminal.mock.calls.map(([, options]) => options.title) - } -} - -function provisionWithSetup( - host: WorktreeTerminalProvisioningHost, - withSetup = true, - setupOnly?: boolean, - defaultTabs?: typeof DEFAULT_TABS, - callerProvidesSurface = false -) { - return provisionWorktreeTerminals(host, { - worktreeSelector: 'id:wt-1', - worktreeId: 'wt-1', - worktreePath: '/repo/wt-1', - ...(withSetup ? { setup } : {}), - hasStartupTerminal: false, - ...(setupOnly !== undefined ? { setupOnly } : {}), - ...(defaultTabs ? { defaultTabs } : {}), - callerProvidesSurface, - setupCommandPlatform: 'posix' - }) -} - -describe('provisionWorktreeTerminals with a cleared creation choice', () => { - it('uses the injected setup title', async () => { - const { host, titles } = createHost() - host.getSetupTerminalTitle = () => '초기 설정' - await provisionWithSetup(host, true, true) - expect(titles()).toEqual(['초기 설정']) - }) - - it('creates only Setup for an explicit setup-only choice', async () => { - const { host, titles } = createHost() - await provisionWithSetup(host, true, true) - expect(titles()).toEqual(['Setup']) - }) - - it('skips configured template commands when Setup is the only tab', async () => { - const { host, titles } = createHost() - await provisionWithSetup(host, true, true, DEFAULT_TABS) - expect(titles()).toEqual(['Setup']) - expect(host.setTabTitle).not.toHaveBeenCalled() - expect(host.setTabColor).not.toHaveBeenCalled() - }) - - it.each([ - { withSetup: true, setupOnly: false, titles: ['Dev', 'Tests', 'Setup'] }, - { withSetup: false, setupOnly: true, titles: ['Dev', 'Tests'] } - ])('keeps templates for blank or skipped setup: $withSetup/$setupOnly', async (test) => { - const { host, titles } = createHost() - await provisionWithSetup(host, test.withSetup, test.setupOnly, DEFAULT_TABS) - expect(titles()).toEqual(test.titles) - expect(host.createTerminal).toHaveBeenCalledWith('id:wt-1', { - title: 'Dev', - command: 'pnpm dev' - }) - }) - - it('keeps the primary terminal for an explicit plain-terminal choice', async () => { - const { host, titles } = createHost() - await provisionWithSetup(host, true, false) - expect(titles()).toEqual([undefined, 'Setup']) - }) - - it('keeps the primary terminal without a cleared creation choice', async () => { - const { host, titles } = createHost() - await expect(provisionWithSetup(host)).resolves.toMatchObject({ setupSpawned: true }) - expect(titles()).toEqual([undefined, 'Setup']) - }) - - it('creates Setup without a shell when the caller supplies the primary surface', async () => { - const { host, titles } = createHost() - await provisionWithSetup(host, true, false, undefined, true) - expect(titles()).toEqual(['Setup']) - }) - - it('falls back to a blank terminal when no setup runs', async () => { - const { host, titles } = createHost() - await provisionWithSetup(host, false, true) - expect(titles()).toEqual([undefined]) - }) - - it.each([false, true])( - 'opens a failed-Setup recovery shell only when the caller owes the surface (%s)', - async (callerProvidesSurface) => { - const { host, titles } = createHost() - const createTerminal = vi.mocked(host.createTerminal) - createTerminal.mockRejectedValueOnce(new Error('spawn failed')) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - await expect( - provisionWithSetup(host, true, true, undefined, callerProvidesSurface) - ).resolves.toEqual({ - setupSpawned: false, - setupTerminalHandle: null - }) - expect(titles()).toEqual(callerProvidesSurface ? ['Setup'] : ['Setup', undefined]) - warn.mockRestore() - } - ) -}) - -describe("a create's E9 origin", () => { - it("starts every terminal of a person's create as their act, and an automation's as background", async () => { - const person = fakeHost() - await provisionWorktreeTerminals(person, { - worktreeSelector: 'id:wt-1', - worktreeId: 'wt-1', - worktreePath: '/worktrees/wt-1', - defaultTabs: DEFAULT_TABS, - hasStartupTerminal: false, - setupCommandPlatform: 'posix', - wslUserAct: true - }) - expect(person.createTerminal.mock.calls.map((call) => call[1])).toEqual( - DEFAULT_TABS.tabs.map(() => expect.objectContaining({ wslUserAct: true })) - ) - - const automation = fakeHost() - await provision(automation, false) - for (const call of automation.createTerminal.mock.calls) { - expect(call[1]).not.toHaveProperty('wslUserAct') - } - }) -}) diff --git a/src/main/runtime/wsl-host-agent-terminal-launch.test.ts b/src/main/runtime/wsl-host-agent-terminal-launch.test.ts index 8fed7eb91e7..285e8c6d2da 100644 --- a/src/main/runtime/wsl-host-agent-terminal-launch.test.ts +++ b/src/main/runtime/wsl-host-agent-terminal-launch.test.ts @@ -1,14 +1,11 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { resolveAgentStartupPlanInputs } from '../../shared/agent-launch/startup/agent-startup-plan-inputs' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { resolveAgentTerminalCreateOptions } from './terminal/launch/runtime-agent-terminal-startup' -import { - resolveWslHostAgentLaunchInputs, - resolveWslHostAgentResumeInputs -} from './terminal/launch/wsl-host-agent-terminal-launch' +import './terminal/launch/runtime-agent-terminal-startup' +import { resolveWslHostAgentLaunchInputs } from './terminal/launch/wsl-host-agent-terminal-launch' let root: string let windowsMount: string @@ -57,13 +54,6 @@ afterEach(() => { // POSIX paths and exec bits stand in for a distro; Windows runners can't model them. describe.skipIf(process.platform === 'win32')('resolveWslHostAgentLaunchInputs', () => { - it('refuses an agent installed only on the Windows side, and says how to fix it', () => { - fakeExecutable(windowsBin, 'claude') - expect(() => launch('claude', `${nativeBin}:${windowsBin}`)).toThrow( - 'claude is installed only on Windows, not in this WSL distro. Install it inside the distro. Or set the claude Command setting to a program inside the distro.' - ) - }) - it('launches the distro copy by absolute path even when a Windows copy is on PATH first', () => { fakeExecutable(windowsBin, 'claude') const native = fakeExecutable(nativeBin, 'claude') @@ -71,45 +61,6 @@ describe.skipIf(process.platform === 'win32')('resolveWslHostAgentLaunchInputs', expect(inputs.cmdOverrides.claude).toBe(`'${native}'`) }) - it('launches a native alias instead of refusing for a Windows-only primary name', () => { - fakeExecutable(windowsBin, 'qodercli') - const native = fakeExecutable(nativeBin, 'qoder') - expect(launch('qoder', `${windowsBin}:${nativeBin}`).cmdOverrides.qoder).toBe(`'${native}'`) - }) - - it('refuses Agent Teams when the Claude it runs exists only on Windows', () => { - fakeExecutable(windowsBin, 'claude') - expect(() => launch('claude-agent-teams', `${nativeBin}:${windowsBin}`)).toThrow( - 'claude is installed only on Windows, not in this WSL distro. Install it inside the distro. Or set the claude-agent-teams Command setting to a program inside the distro.' - ) - }) - - it('leaves the Agent Teams wrapper command alone when Claude is in the distro', () => { - fakeExecutable(windowsBin, 'claude') - fakeExecutable(nativeBin, 'claude') - const inputs = inputsFor('claude-agent-teams') - expect( - resolveWslHostAgentLaunchInputs(inputs, `${windowsBin}:${nativeBin}`, { - isWslHost: true, - mounts: [windowsMount], - homePath: home - }) - ).toBe(inputs) - }) - - it('refuses an agent whose required companion CLI exists only on Windows', () => { - fakeExecutable(nativeBin, 'dsh-tui') - fakeExecutable(windowsBin, 'dsh') - expect(() => launch('dsh', `${nativeBin}:${windowsBin}`)).toThrow( - 'dsh is installed only on Windows, not in this WSL distro. Install it inside the distro. Or set the dsh Command setting to a program inside the distro.' - ) - }) - - it('keeps launch arguments that ride on the stock command', () => { - const native = fakeExecutable(nativeBin, 'kiro-cli') - expect(launch('kiro', nativeBin).cmdOverrides.kiro).toBe(`'${native}' chat --tui`) - }) - // orcad's PATH lacks the interactive shell's nvm/~/.local entries; the install-dir search still finds them. it('finds a distro install that only the interactive shell PATH would list', () => { fakeExecutable(windowsBin, 'codex') @@ -119,110 +70,4 @@ describe.skipIf(process.platform === 'win32')('resolveWslHostAgentLaunchInputs', const local = fakeExecutable(join(home, '.local', 'bin'), 'codex') expect(launch('codex', `/usr/bin:${windowsBin}`).cmdOverrides.codex).toBe(`'${local}'`) }) - - it('leaves an agent found nowhere to the shell, as before', () => { - const inputs = inputsFor('claude') - expect( - resolveWslHostAgentLaunchInputs(inputs, nativeBin, { - isWslHost: true, - mounts: [windowsMount], - homePath: home - }) - ).toBe(inputs) - }) - - it('never checks or rewrites an explicit Command setting', () => { - fakeExecutable(windowsBin, 'claude') - const inputs = launch('claude', windowsBin, { override: 'my-claude --flag' }) - expect(inputs.cmdOverrides).toEqual({ claude: 'my-claude --flag' }) - }) - - it('leaves remote launches and non-WSL hosts untouched', () => { - fakeExecutable(windowsBin, 'claude') - fakeExecutable(nativeBin, 'claude') - const remote = inputsFor('claude', { isRemote: true }) - expect( - resolveWslHostAgentLaunchInputs(remote, windowsBin, { - isWslHost: true, - mounts: [windowsMount], - homePath: home - }) - ).toBe(remote) - const local = inputsFor('claude') - expect( - resolveWslHostAgentLaunchInputs(local, nativeBin, { isWslHost: false, homePath: home }) - ).toBe(local) - }) -}) - -describe.skipIf(process.platform === 'win32')('resolveWslHostAgentResumeInputs', () => { - const resume = (agentCommand: string, isWslHost = true) => { - const args = { - agent: 'claude' as const, - cmdOverrides: {}, - platform: 'linux' as const, - agentCommand - } - return { - args, - out: resolveWslHostAgentResumeInputs(args, `${windowsBin}:${nativeBin}`, { - isWslHost, - mounts: [windowsMount], - homePath: home - }) - } - } - - it('pins a recorded stock command and keeps its arguments', () => { - const native = fakeExecutable(nativeBin, 'claude') - expect(resume('claude --verbose').out.agentCommand).toBe(`'${native}' --verbose`) - }) - - it('returns the same arguments off a WSL host or for an already pinned command', () => { - fakeExecutable(nativeBin, 'claude') - const offHost = resume('claude', false) - expect(offHost.out).toBe(offHost.args) - const pinned = resume(`'${nativeBin}/claude'`) - expect(pinned.out).toBe(pinned.args) - }) -}) - -describe.skipIf(process.platform === 'win32')('WSL-host agent terminal launch', () => { - const original = process.platform - beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) - vi.stubEnv('ORCA_WSL_ORCAD_HOST', '1') - vi.stubEnv('WSL_DISTRO_NAME', 'Ubuntu') - }) - afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: original }) - vi.unstubAllEnvs() - }) - - // Interop stays usable in the agent's terminal (code ., explorer.exe); only the program is pinned. - it('types the absolute distro path and leaves the terminal PATH alone', async () => { - const native = fakeExecutable(nativeBin, 'claude') - vi.stubEnv('PATH', `${nativeBin}:${windowsBin}`) - const workspace = { id: 'w', path: root, connectionId: null, repo: null, folderWorkspace: null } - const host = { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: for a workspace with no repo or folder, the planner reads only getSettings. - store: { getSettings: () => ({}) } as never, - hostIdentity: 'host-1', - toSessionOptions: () => undefined - } - const created = await resolveAgentTerminalCreateOptions( - workspace, - { - startupAgent: 'claude', - agentArgs: null, - launchRuntime: { - platform: 'linux', - pty: { shellOverride: undefined, terminalWindowsWslDistro: null } - } - }, - host - ) - expect(created.command).toBe(`'${native}'`) - expect(created.env?.PATH).toBeUndefined() - }) }) diff --git a/src/main/skills/skill-bundle-creation.test.ts b/src/main/skills/skill-bundle-creation.test.ts index 3611d8b73ea..b9d25056a19 100644 --- a/src/main/skills/skill-bundle-creation.test.ts +++ b/src/main/skills/skill-bundle-creation.test.ts @@ -1,14 +1,11 @@ -import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { - AGENT_PLUGIN_MANIFEST_PATH, - AGENT_PLUGIN_SCHEMA_V1 -} from '../../shared/skill-bundle-manifest' +import { AGENT_PLUGIN_SCHEMA_V1 } from '../../shared/skill-bundle-manifest' import { createSkillBundleArchive } from './skill-bundle-creation' import { extractSkillBundleArchive } from './skill-bundle-extraction' -import { writeSkillTarGzip } from './skill-package-tar' +import './skill-package-tar' const temporaryDirectories: string[] = [] @@ -36,32 +33,6 @@ afterEach(async () => { }) describe('skill bundle creation and extraction', () => { - it('verifies manifest executable paths without Windows mode bits', async () => { - const root = await temporaryDirectory() - const source = await createSkill(root, 'script-skill', 'Script') - const script = join(source, 'run.sh') - await writeFile(script, '#!/bin/sh\necho ok\n') - await chmod(script, 0o700) - const created = await createSkillBundleArchive({ - sources: [{ sourceDirectory: source }], - archivePath: join(root, 'bundle.tar.gz'), - packageId: 'package_windows', - versionId: 'version_windows', - bundleName: 'windows-bundle' - }) - expect(created.manifest.skills[0].files).toContainEqual( - expect.objectContaining({ path: 'run.sh', executable: true }) - ) - - await expect( - extractSkillBundleArchive({ - archivePath: created.archivePath, - destinationDirectory: join(root, 'windows-extracted'), - platform: 'win32' - }) - ).resolves.toMatchObject({ manifest: { bundleName: 'windows-bundle' } }) - }) - it('round trips multiple skills through an Agent Plugins compatible root', async () => { const root = await temporaryDirectory() const alpha = await createSkill(root, 'alpha-skill', 'Alpha') @@ -97,63 +68,6 @@ describe('skill bundle creation and extraction', () => { ) }) - it('creates deterministic archives regardless of source selection order', async () => { - const root = await temporaryDirectory() - const alpha = await createSkill(root, 'alpha-skill', 'Alpha') - const beta = await createSkill(root, 'beta-skill', 'Beta') - const publication = { - packageId: 'package_1', - versionId: 'version_1', - bundleName: 'team-skills', - createdAt: '2026-08-11T12:00:00.000Z' - } - const first = await createSkillBundleArchive({ - ...publication, - sources: [{ sourceDirectory: alpha }, { sourceDirectory: beta }], - archivePath: join(root, 'first.tar.gz') - }) - const second = await createSkillBundleArchive({ - ...publication, - sources: [{ sourceDirectory: beta }, { sourceDirectory: alpha }], - archivePath: join(root, 'second.tar.gz') - }) - - expect(first.archiveSha256).toBe(second.archiveSha256) - expect(await readFile(first.archivePath)).toEqual(await readFile(second.archivePath)) - }) - - it('packages and extracts thirty selected skills within the shared limits', async () => { - const root = await temporaryDirectory() - const names = Array.from( - { length: 30 }, - (_, index) => `skill-${String(index).padStart(2, '0')}` - ) - const sources = await Promise.all( - names.map(async (name) => ({ - sourceDirectory: await createSkill(root, name, `Description for ${name}`) - })) - ) - const created = await createSkillBundleArchive({ - sources: sources.toReversed(), - archivePath: join(root, 'thirty-skills.tar.gz'), - packageId: 'package_30', - versionId: 'version_30', - bundleName: 'thirty-skills' - }) - - const extracted = await extractSkillBundleArchive({ - archivePath: created.archivePath, - destinationDirectory: join(root, 'thirty-skills'), - expectedBundleDigest: created.manifest.bundleDigest - }) - - expect(extracted.manifest.skills.map((skill) => skill.name)).toEqual(names) - expect(extracted.manifest.skills).toHaveLength(30) - await expect( - readFile(join(extracted.skillsDirectory, 'skill-29', 'notes.txt'), 'utf8') - ).resolves.toBe('skill-29 notes\n') - }) - it('rejects conflicting staging roots without changing their imported namespace', async () => { const root = await temporaryDirectory() const source = await createSkill(root, 'alpha-skill', 'Alpha') @@ -177,52 +91,4 @@ describe('skill bundle creation and extraction', () => { ).rejects.toMatchObject({ code: 'EEXIST' }) await expect(readFile(importedManifest, 'utf8')).resolves.toBe('unowned\n') }) - - it('rejects unknown top-level extension namespaces and removes fresh staging', async () => { - const root = await temporaryDirectory() - const plugin = Buffer.from( - JSON.stringify({ $schema: AGENT_PLUGIN_SCHEMA_V1, name: 'team-skills' }) - ) - const unknown = Buffer.from('{}') - const archivePath = join(root, 'unknown-extension.tar.gz') - await writeSkillTarGzip(archivePath, [ - { - path: AGENT_PLUGIN_MANIFEST_PATH, - size: plugin.length, - executable: false, - bytes: plugin - }, - { - path: 'dev.orca.unexpected/manifest.json', - size: unknown.length, - executable: false, - bytes: unknown - } - ]) - const destination = join(root, 'unknown-extension-staging') - - await expect( - extractSkillBundleArchive({ archivePath, destinationDirectory: destination }) - ).rejects.toThrow('skill-bundle-manifest-envelope-invalid') - await expect(stat(destination)).rejects.toMatchObject({ code: 'ENOENT' }) - }) - - it('rejects duplicate names and source drift without publishing an archive', async () => { - const root = await temporaryDirectory() - const first = await createSkill(root, 'same-skill', 'First') - const secondRoot = join(root, 'other') - const second = await createSkill(secondRoot, 'same-skill', 'Second') - const archivePath = join(root, 'duplicate.tar.gz') - - await expect( - createSkillBundleArchive({ - sources: [{ sourceDirectory: first }, { sourceDirectory: second }], - archivePath, - packageId: 'package_1', - versionId: 'version_1', - bundleName: 'team-skills' - }) - ).rejects.toThrow('skill-bundle-skill-collision') - await expect(readFile(archivePath)).rejects.toMatchObject({ code: 'ENOENT' }) - }) }) diff --git a/src/main/skills/skill-package-identity.test.ts b/src/main/skills/skill-package-identity.test.ts index 8f0d6540218..0a94d854901 100644 --- a/src/main/skills/skill-package-identity.test.ts +++ b/src/main/skills/skill-package-identity.test.ts @@ -1,15 +1,11 @@ import { execFile } from 'node:child_process' import { createServer } from 'node:net' -import { chmod, link, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { link, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' import { afterEach, describe, expect, it } from 'vitest' -import { - describeObservedSkillFile, - matchesBundledSkillFiles, - observeSkillPackage -} from './skill-package-identity' +import { observeSkillPackage } from './skill-package-identity' const temporaryDirectories: string[] = [] const execFileAsync = promisify(execFile) @@ -25,81 +21,6 @@ afterEach(async () => { }) describe('skill package identity', () => { - it('matches CRLF installed text to LF bundled files', async () => { - const root = await temporarySkill() - await writeFile(join(root, 'SKILL.md'), 'first\r\nsecond\r\n') - const observed = await observeSkillPackage(root) - const expected = describeObservedSkillFile('SKILL.md', Buffer.from('first\nsecond\n'), false) - - // Concurrent identities may reach multiple byte budgets; retain file hashes rather than raw buffers. - expect(observed.files[0]).not.toHaveProperty('bytes') - expect(matchesBundledSkillFiles(observed, [expected])).toBe(true) - }) - - it('uses exact bytes for executable and binary files', async () => { - const executable = describeObservedSkillFile('run.sh', Buffer.from('#!/bin/sh\r\n'), true) - const binary = describeObservedSkillFile('asset.bin', Buffer.from([0, 13, 10]), false) - expect(executable.identitySha256).toBe(executable.exactSha256) - expect(binary.identitySha256).toBe(binary.exactSha256) - expect(binary.classification).toBe('binary') - }) - - it('infers shebang scripts as executable on Windows filesystems', async () => { - const root = await temporarySkill() - await writeFile(join(root, 'SKILL.md'), 'skill\n') - await writeFile(join(root, 'run.sh'), '#!/bin/sh\necho ok\n') - - const observed = await observeSkillPackage(root, undefined, undefined, undefined, 'win32', true) - - expect(observed.files.find((file) => file.path === 'run.sh')?.executable).toBe(true) - expect(observed.files.find((file) => file.path === 'SKILL.md')?.executable).toBe(false) - }) - - it('matches receipt executable paths case-insensitively on Windows', async () => { - const root = await temporarySkill() - await writeFile(join(root, 'SKILL.md'), 'skill\n') - await writeFile(join(root, 'run.sh'), '#!/bin/sh\necho ok\n') - - const observed = await observeSkillPackage( - root, - undefined, - new Set(['Run.sh']), - undefined, - 'win32' - ) - - expect(observed.files.find((file) => file.path === 'run.sh')?.executable).toBe(true) - }) - - it('orders package files by locale-independent code units', async () => { - const root = await temporarySkill() - await writeFile(join(root, 'apple.md'), 'apple') - await writeFile(join(root, 'Zebra.md'), 'zebra') - - const observed = await observeSkillPackage(root) - - expect(observed.files.map((file) => file.path)).toEqual(['Zebra.md', 'apple.md']) - }) - - it('rejects links and bounded-observation overflows', async () => { - const root = await temporarySkill() - await writeFile(join(root, 'SKILL.md'), 'skill') - if (process.platform !== 'win32') { - await symlink(join(root, 'SKILL.md'), join(root, 'linked.md')) - await expect(observeSkillPackage(root)).rejects.toThrow('skill-package-link') - await rm(join(root, 'linked.md')) - } - await expect( - observeSkillPackage(root, { - maximumDepth: 1, - maximumEntries: 0, - maximumFiles: 1, - maximumSingleFileBytes: 10, - maximumTotalBytes: 10 - }) - ).rejects.toThrow('skill-package-entry-limit') - }) - it.runIf(process.platform !== 'win32')('rejects hardlinks, FIFOs, and Unix sockets', async () => { const root = await temporarySkill() const source = join(root, 'SKILL.md') @@ -126,25 +47,6 @@ describe('skill package identity', () => { } }) - it('ignores OS-authored sidecars so a browsed folder still matches the bundle', async () => { - const pristine = await temporarySkill() - await writeFile(join(pristine, 'SKILL.md'), 'skill\n') - const official = await observeSkillPackage(pristine) - - const browsed = await temporarySkill() - await writeFile(join(browsed, 'SKILL.md'), 'skill\n') - await writeFile(join(browsed, '.DS_Store'), Buffer.from([0, 1, 2, 3])) - await writeFile(join(browsed, '._SKILL.md'), Buffer.from([0, 5])) - await writeFile(join(browsed, 'Thumbs.db'), Buffer.from([9])) - await writeFile(join(browsed, 'desktop.ini'), '[.ShellClassInfo]\n') - - const observed = await observeSkillPackage(browsed) - - expect(observed.files.map((file) => file.path)).toEqual(['SKILL.md']) - expect(observed.observedDigest).toBe(official.observedDigest) - expect(matchesBundledSkillFiles(observed, official.files)).toBe(true) - }) - it('keeps guarding a directory or link that only wears an OS metadata name', async () => { const root = await temporarySkill() await writeFile(join(root, 'SKILL.md'), 'skill\n') @@ -163,47 +65,4 @@ describe('skill package identity', () => { await expect(observeSkillPackage(root)).rejects.toThrow('skill-package-link') } }) - - it('still reports a genuinely modified skill as unmatched', async () => { - const pristine = await temporarySkill() - await writeFile(join(pristine, 'SKILL.md'), 'skill\n') - const official = await observeSkillPackage(pristine) - - const edited = await temporarySkill() - await writeFile(join(edited, 'SKILL.md'), 'skill\nlocal tweak\n') - await writeFile(join(edited, '.DS_Store'), Buffer.from([0, 1])) - // Agent CLI sidecars may coexist with unchanged official bytes. - const withPayload = await temporarySkill() - await writeFile(join(withPayload, 'SKILL.md'), 'skill\n') - await mkdir(join(withPayload, 'agents'), { recursive: true }) - await writeFile(join(withPayload, 'agents', 'openai.yaml'), 'display_name: test\n') - - expect(matchesBundledSkillFiles(await observeSkillPackage(edited), official.files)).toBe(false) - expect(matchesBundledSkillFiles(await observeSkillPackage(withPayload), official.files)).toBe( - true - ) - }) - - it('reports a missing bundled file as unmatched', async () => { - const shipped = await temporarySkill() - await writeFile(join(shipped, 'SKILL.md'), 'skill\n') - await mkdir(join(shipped, 'references'), { recursive: true }) - await writeFile(join(shipped, 'references', 'x.md'), 'reference\n') - const official = await observeSkillPackage(shipped) - - const partial = await temporarySkill() - await writeFile(join(partial, 'SKILL.md'), 'skill\n') - - expect(matchesBundledSkillFiles(await observeSkillPackage(partial), official.files)).toBe(false) - }) - - it.runIf(process.platform !== 'win32')('tracks executable mode in package identity', async () => { - const root = await temporarySkill() - await mkdir(join(root, 'scripts')) - const script = join(root, 'scripts', 'run.sh') - await writeFile(script, '#!/bin/sh\n') - await chmod(script, 0o755) - const observed = await observeSkillPackage(root) - expect(observed.files[0]?.executable).toBe(true) - }) }) diff --git a/src/main/source-control/hosted-review-creation-shared-symlinks.test.ts b/src/main/source-control/hosted-review-creation-shared-symlinks.test.ts deleted file mode 100644 index 15d649ba5f9..00000000000 --- a/src/main/source-control/hosted-review-creation-shared-symlinks.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - createGitHubPullRequestMock, - getRepoSlugMock, - getProjectSlugMock, - getBitbucketRepoSlugMock, - getAzureDevOpsRepoSlugMock, - getGiteaRepoSlugMock, - getEnterpriseGitHubRepoSlugMock, - getHostedReviewForBranchMock, - ghExecFileAsyncMock, - glabExecFileAsyncMock, - gitExecFileAsyncMock, - getUpstreamStatusMock -} = vi.hoisted(() => ({ - createGitHubPullRequestMock: vi.fn(), - getRepoSlugMock: vi.fn(), - getProjectSlugMock: vi.fn(), - getBitbucketRepoSlugMock: vi.fn(), - getAzureDevOpsRepoSlugMock: vi.fn(), - getGiteaRepoSlugMock: vi.fn(), - getEnterpriseGitHubRepoSlugMock: vi.fn(), - getHostedReviewForBranchMock: vi.fn(), - ghExecFileAsyncMock: vi.fn(), - glabExecFileAsyncMock: vi.fn(), - gitExecFileAsyncMock: vi.fn(), - getUpstreamStatusMock: vi.fn() -})) - -vi.mock('../github/client', () => ({ - createGitHubPullRequest: createGitHubPullRequestMock, - getRepoSlug: getRepoSlugMock, - getPRForBranch: vi.fn() -})) -vi.mock('../github/github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock -})) -vi.mock('../gitlab/client', () => ({ - getProjectSlug: getProjectSlugMock, - getMergeRequestForBranch: vi.fn(), - getMergeRequest: vi.fn() -})) -vi.mock('../gitlab/merge-request-creation', () => ({ createGitLabMergeRequest: vi.fn() })) -vi.mock('../bitbucket/client', () => ({ - getBitbucketRepoSlug: getBitbucketRepoSlugMock, - getBitbucketPullRequestForBranch: vi.fn(), - getBitbucketPullRequest: vi.fn() -})) -vi.mock('../azure-devops/client', () => ({ - getAzureDevOpsRepoSlug: getAzureDevOpsRepoSlugMock, - getAzureDevOpsPullRequestForBranch: vi.fn(), - getAzureDevOpsPullRequest: vi.fn() -})) -vi.mock('../azure-devops/pull-request-creation', () => ({ - createAzureDevOpsPullRequest: vi.fn(), - isAzureDevOpsReviewCreationAuthenticated: vi.fn() -})) -vi.mock('../gitea/client', () => ({ - getGiteaRepoSlug: getGiteaRepoSlugMock, - getGiteaPullRequestForBranch: vi.fn(), - getGiteaPullRequest: vi.fn() -})) -vi.mock('../gitea/pull-request-creation', () => ({ - createGiteaPullRequest: vi.fn(), - isGiteaReviewCreationAuthenticated: vi.fn() -})) -vi.mock('../github/gh-utils', () => ({ - acquire: vi.fn(), - release: vi.fn(), - ghExecFileAsync: ghExecFileAsyncMock, - gitExecFileAsync: gitExecFileAsyncMock -})) -vi.mock('../gitlab/gl-utils', () => ({ - acquire: vi.fn(), - release: vi.fn(), - glabExecFileAsync: glabExecFileAsyncMock, - glabRepoExecOptions: (repoPath: string) => ({ cwd: repoPath }) -})) -vi.mock('../git/source-control/upstream', () => ({ - getUpstreamStatus: getUpstreamStatusMock -})) -vi.mock('./hosted-review', () => ({ - getHostedReviewForBranch: getHostedReviewForBranchMock -})) - -import { createHostedReview } from './hosted-review-creation' - -// Directory-only ignores miss worktree symlinks; exclude Orca-owned links rather than demand an impossible commit. -describe('createHostedReview with shared symlinks', () => { - let worktree: string - let statusOutput: string - - const createPr = (sharedLinkPaths?: string[]): ReturnType => - createHostedReview( - worktree, - { provider: 'github', base: 'main', head: 'feature', title: 'Feature' }, - 'local', - sharedLinkPaths ? { sharedLinkPaths } : {} - ) - - beforeEach(() => { - worktree = mkdtempSync(join(tmpdir(), 'orca-hosted-shared-')) - mkdirSync(join(worktree, 'primary-node-modules')) - symlinkSync(join(worktree, 'primary-node-modules'), join(worktree, 'node_modules'), 'dir') - statusOutput = '?? node_modules\0' - - for (const mock of [ - createGitHubPullRequestMock, - getRepoSlugMock, - getProjectSlugMock, - getBitbucketRepoSlugMock, - getAzureDevOpsRepoSlugMock, - getGiteaRepoSlugMock, - getEnterpriseGitHubRepoSlugMock, - getHostedReviewForBranchMock, - ghExecFileAsyncMock, - glabExecFileAsyncMock, - gitExecFileAsyncMock, - getUpstreamStatusMock - ]) { - mock.mockReset() - } - - getProjectSlugMock.mockResolvedValue(null) - getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' }) - getBitbucketRepoSlugMock.mockResolvedValue(null) - getAzureDevOpsRepoSlugMock.mockResolvedValue(null) - getGiteaRepoSlugMock.mockResolvedValue(null) - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) - getHostedReviewForBranchMock.mockResolvedValue(null) - ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) - glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) - getUpstreamStatusMock.mockResolvedValue({ - hasUpstream: true, - upstreamName: 'origin/feature', - ahead: 0, - behind: 0 - }) - createGitHubPullRequestMock.mockResolvedValue({ - ok: true, - number: 12, - url: 'https://github.com/acme/orca/pull/12' - }) - gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args[0] === 'rev-parse') { - return { stdout: 'feature\n', stderr: '' } - } - if (args[0] === 'status') { - return { stdout: statusOutput, stderr: '' } - } - if (args[0] === 'for-each-ref') { - return { stdout: 'refs/remotes/origin/main\n', stderr: '' } - } - if (args[0] === 'log') { - return { stdout: 'Feature title\n', stderr: '' } - } - return { stdout: '', stderr: '' } - }) - }) - - afterEach(() => { - rmSync(worktree, { recursive: true, force: true }) - }) - - it('blocks creation when the shared symlink is not declared', async () => { - await expect(createPr()).resolves.toEqual( - expect.objectContaining({ ok: false, code: 'validation' }) - ) - expect(createGitHubPullRequestMock).not.toHaveBeenCalled() - }) - - it('creates the pull request when the untracked entry is a declared shared symlink', async () => { - await expect(createPr(['node_modules'])).resolves.toEqual({ - ok: true, - number: 12, - url: 'https://github.com/acme/orca/pull/12' - }) - expect(createGitHubPullRequestMock).toHaveBeenCalledOnce() - }) - - it('still blocks when a genuine untracked file sits beside the shared symlink', async () => { - statusOutput = '?? node_modules\0?? scratch.txt\0' - - await expect(createPr(['node_modules'])).resolves.toEqual( - expect.objectContaining({ ok: false, code: 'validation' }) - ) - expect(createGitHubPullRequestMock).not.toHaveBeenCalled() - }) - - it('still blocks on a modified tracked file beside the shared symlink', async () => { - statusOutput = '?? node_modules\0 M src/app.ts\0' - - await expect(createPr(['node_modules'])).resolves.toEqual( - expect.objectContaining({ ok: false, code: 'validation' }) - ) - expect(createGitHubPullRequestMock).not.toHaveBeenCalled() - }) - - // A configured shared name holding a regular file remains user work. - it('still blocks when a declared name exists as a regular file', async () => { - writeFileSync(join(worktree, 'notes'), 'user work\n') - statusOutput = '?? notes\0' - - await expect(createPr(['node_modules', 'notes'])).resolves.toEqual( - expect.objectContaining({ ok: false, code: 'validation' }) - ) - expect(createGitHubPullRequestMock).not.toHaveBeenCalled() - }) - - // Tracked changes remain committable user work even at declared shared paths. - it('still blocks on a tracked change at the declared shared path', async () => { - symlinkSync(join(worktree, 'primary-node-modules'), join(worktree, 'tracked-link'), 'dir') - statusOutput = '?? node_modules\0 M tracked-link\0' - - await expect(createPr(['node_modules', 'tracked-link'])).resolves.toEqual( - expect.objectContaining({ ok: false, code: 'validation' }) - ) - expect(createGitHubPullRequestMock).not.toHaveBeenCalled() - }) - - it('does not mistake a rename origin for an untracked shared path', async () => { - // Consume rename origin fields so they cannot masquerade as untracked shared links. - statusOutput = 'R renamed.txt\0node_modules\0' - - await expect(createPr(['node_modules'])).resolves.toEqual( - expect.objectContaining({ ok: false, code: 'validation' }) - ) - expect(createGitHubPullRequestMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/source-control/hosted-review-project-account.test.ts b/src/main/source-control/hosted-review-project-account.test.ts deleted file mode 100644 index eafca5fc10c..00000000000 --- a/src/main/source-control/hosted-review-project-account.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { - HOSTED_REVIEW_LOOKUP_DEADLINE_MS, - NO_REVIEW_REFRESH_INTERVAL_MS -} from './hosted-review-refresh-pacing' -import { githubRepoContext } from '../github/github-repository-identity' -import type { Repo } from '../../shared/repo-types' -import { installGitHubProjectAccounts } from '../github/github-project-account' -import { __resetHostedReviewBranchCacheForTests } from './hosted-review-branch-cache' -import { getHostedReviewForBranch } from './hosted-review' - -const { read, detect, probe } = vi.hoisted(() => ({ - read: vi.fn(), - detect: vi.fn(), - probe: vi.fn() -})) -vi.mock('../git/remotes/remote-url-probe', () => ({ assertRemoteUrlReadable: probe })) -vi.mock('./forge-provider-detection', () => ({ getForgeProviderForRepository: detect })) -let release: () => void -let repo: Repo -beforeEach(() => { - __resetHostedReviewBranchCacheForTests() - probe.mockReset() - read.mockReset() - detect.mockReset().mockResolvedValue({ id: 'github', getReviewForBranch: read }) - repo = { - id: 'repo', - path: '/repo', - displayName: 'Repo', - badgeColor: '#000000', - addedAt: 0, - ghAccount: { host: 'github.com', user: 'Alice' } - } - release = installGitHubProjectAccounts({ getRepos: () => [repo] }) -}) -afterEach(() => { - release() - vi.useRealTimers() - __resetHostedReviewBranchCacheForTests() -}) - -it('does not reuse a negative review result after the saved account changes or clears', async () => { - read.mockResolvedValue(null) - const input = { repoPath: '/repo', executionHostId: 'local', branch: 'feature' } as const - await getHostedReviewForBranch(input) - await getHostedReviewForBranch(input) - expect(read).toHaveBeenCalledTimes(1) - expect(read.mock.calls[0][0].localGitExecOptions.ghAccount.user).toBe('Alice') - repo = { ...repo, ghAccount: { host: 'github.com', user: 'Bob' } } - await getHostedReviewForBranch(input) - expect(read).toHaveBeenCalledTimes(2) - expect(read.mock.calls[1][0].localGitExecOptions.ghAccount.user).toBe('Bob') - repo = { ...repo, ghAccount: undefined } - await getHostedReviewForBranch(input) - expect(read).toHaveBeenCalledTimes(3) - expect(read.mock.calls[2][0].localGitExecOptions.ghAccount).toBeUndefined() -}) - -it('leaves other providers outside GitHub account selection', async () => { - detect.mockResolvedValue({ id: 'gitlab', getReviewForBranch: read }) - read.mockResolvedValue(null) - await getHostedReviewForBranch({ repoPath: '/repo', executionHostId: 'local', branch: 'feature' }) - expect(read.mock.calls[0][0].localGitExecOptions).toBeUndefined() -}) - -it.each(['github', 'gitlab'] as const)( - 'keeps %s discovery inside cache, failure/backoff and total deadline', - async (id) => { - vi.useFakeTimers() - const review = { provider: id, title: 'Last good' } - detect.mockResolvedValue({ id, getReviewForBranch: read }) - read.mockResolvedValue(review) - const localGitExecOptions = { ghAccount: repo.ghAccount, admissionTier: 'background' } as const - const input = { - repoPath: '/repo', - executionHostId: 'local', - branch: 'feature', - localGitExecOptions - } as const - await expect(getHostedReviewForBranch(input)).resolves.toEqual(review) - expect(detect.mock.calls[0][0]).toEqual({ - repoPath: input.repoPath, - executionHostId: input.executionHostId, - localGitExecOptions - }) - expect(read.mock.calls[0][0]).toMatchObject({ branch: 'feature', localGitExecOptions }) - detect.mockResolvedValue(null) - probe.mockRejectedValue(new Error('Remote discovery unavailable')) - // Same fresh hit as the old path: no discovery/probe, regardless of new detector outcome. - await expect(getHostedReviewForBranch(input)).resolves.toEqual(review) - expect(detect).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(NO_REVIEW_REFRESH_INTERVAL_MS) - await expect(getHostedReviewForBranch(input)).resolves.toEqual(review) - expect(detect).toHaveBeenCalledTimes(2) - expect(probe).toHaveBeenCalledTimes(1) - await expect(getHostedReviewForBranch(input)).resolves.toEqual(review) - expect(detect).toHaveBeenCalledTimes(2) - - // New branch, unsettled discovery: coalescing and deadline enclose discovery itself. - detect.mockImplementation(() => new Promise(() => {})) - const fresh = { ...input, branch: 'new' } - const first = getHostedReviewForBranch(fresh).catch((error: Error) => error.message) - const second = getHostedReviewForBranch(fresh).catch((error: Error) => error.message) - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - expect(await first).toContain('timed out') - expect(await second).toContain('timed out') - expect(detect).toHaveBeenCalledTimes(3) - await expect(getHostedReviewForBranch(fresh)).rejects.toThrow('backing off') - expect(detect).toHaveBeenCalledTimes(3) - } -) - -it('pins detached provider work through late publication, while independent operations reselect', async () => { - vi.useFakeTimers() - let resume: () => void = () => {} - const gate = new Promise((resolve) => { - resume = resolve - }) - let entered: () => void = () => {} - const started = new Promise((resolve) => { - entered = resolve - }) - const observed: string[] = [] - read.mockImplementation(async (input) => { - entered() - await gate - const selected = githubRepoContext(input.repoPath, null, input.localGitExecOptions).ghAccount - ?.user - observed.push(selected ?? 'ambient') - return { title: selected, state: 'open' } - }) - const input = { repoPath: '/repo', executionHostId: 'local', branch: 'feature' } as const - const pending = getHostedReviewForBranch(input).catch((error: Error) => error.message) - await started - await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) - expect(await pending).toContain('timed out') - repo = { ...repo, ghAccount: { host: 'github.com', user: 'Bob' } } - resume() - await vi.advanceTimersByTimeAsync(0) - await expect(getHostedReviewForBranch(input)).resolves.toMatchObject({ title: 'Bob' }) - repo = { ...repo, ghAccount: { host: 'github.com', user: 'Alice' } } - await expect(getHostedReviewForBranch(input)).resolves.toMatchObject({ title: 'Alice' }) - expect(observed).toEqual(['Alice', 'Bob']) - expect(read).toHaveBeenCalledTimes(2) -}) - -// A polling batch makes N independent requests; each may scan the live catalog once. -it.each(['root', 'warm', 'cold'] as const)( - 'bounds %s ownership work per refresh at N and 10N', - async (mode) => { - const measurements: number[] = [] - for (const count of [10, 100]) { - let visits = 0 - const repos = Array.from({ length: count }, (_, i) => ({ - ...repo, - get id() { - visits++ - return `r${i}` - }, - path: `/r${i}`, - ghAccount: { host: 'github.com', user: i === count - 1 ? 'Bob' : 'Alice' } - })) - const projects = repos.map((entry) => ({ - id: entry.id, - displayName: 'Project', - badgeColor: '#000000', - createdAt: 0, - updatedAt: 0, - get sourceRepoIds() { - visits++ - return [entry.id] - } - })) - const children = Array.from({ length: count }, (_, i) => ({ - get repoId() { - visits++ - return `r${count - 1}` - }, - get path() { - visits++ - return `/children/${i}` - } - })) - release = installGitHubProjectAccounts( - { - getRepos: () => repos, - getProjects: () => projects, - getSettings: () => ({}), - getAllWorktreeMetaForHost: () => - mode === 'cold' - ? Object.fromEntries(children.map((child) => [`${child.repoId}::${child.path}`, {}])) - : {} - }, - () => (mode === 'warm' ? children : []) - ) - __resetHostedReviewBranchCacheForTests() - read.mockImplementation(async (input) => ({ - title: githubRepoContext(input.repoPath, null, input.localGitExecOptions).ghAccount?.user - })) - visits = 0 - for (let i = 0; i < count; i++) { - const selected = await getHostedReviewForBranch({ - repoPath: mode === 'root' ? `/r${i}` : `/children/${i}`, - executionHostId: 'local', - branch: 'feature' - }) - expect(selected?.title).toBe(mode === 'root' && i !== count - 1 ? 'Alice' : 'Bob') - } - measurements.push(visits) - // O(N) live catalog/ownership work per independent request, not nested project scans. - expect(visits).toBeLessThanOrEqual(16 * count * count) - release() - } - expect(measurements[1]).toBeLessThanOrEqual(110 * measurements[0]) - } -) diff --git a/src/main/speech/stt-service-model-warmup.test.ts b/src/main/speech/stt-service-model-warmup.test.ts deleted file mode 100644 index 30f8849675d..00000000000 --- a/src/main/speech/stt-service-model-warmup.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { SpeechModelStatus } from '../../shared/speech-types' -import { SttService } from './stt-service' -import { SttWorkerChildProcess } from './stt-worker-process' - -vi.mock('electron', () => ({ app: { isPackaged: false } })) - -vi.mock('./model-catalog', () => ({ - isLocalSpeechModel: () => true, - getCatalogModel: (id: string) => ({ - id, - type: 'transducer', - provider: 'local', - streaming: true, - sampleRate: 16000, - files: ['encoder.onnx', 'decoder.onnx', 'joiner.onnx', 'tokens.txt'] - }) -})) - -type FakeChild = { worker: SttWorkerChildProcess; modelDir: string; killed: boolean } - -function createService( - options: { - status?: Record - answerInit?: boolean | 'error' - modelStateGate?: Promise - } = {} -): { service: SttService; children: FakeChild[] } { - const children: FakeChild[] = [] - const spawn = (): SttWorkerChildProcess => { - const child: FakeChild = { - modelDir: '', - killed: false, - worker: new SttWorkerChildProcess({ - send: (message) => { - if (message.type === 'init') { - child.modelDir = message.modelDir - if (options.answerInit === 'error') { - queueMicrotask(() => child.worker.receiveMessage({ type: 'error', error: 'bad' })) - } else if (options.answerInit !== false) { - queueMicrotask(() => child.worker.receiveMessage({ type: 'ready' })) - } - } else if (message.type === 'stop' || message.type === 'discard') { - const { streamId } = message - queueMicrotask(() => child.worker.receiveMessage({ type: 'stopped', streamId })) - } - }, - kill: () => { - child.killed = true - child.worker.receiveExit(0) - } - }) - } - children.push(child) - return child.worker - } - const models = { - getModelState: async (id: string) => { - await options.modelStateGate - return { id, status: options.status?.[id] ?? 'ready' } - }, - getModelDir: (id: string) => `/models/${id}` - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: local starts read only getModelState and getModelDir. - return { service: new SttService(models as never, spawn), children } -} - -describe('SttService model pre-warm', () => { - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('loads the model before the first dictation, which then reuses it', async () => { - const { service, children } = createService() - const sink = vi.fn() - - await service.prewarm('model-a') - expect(children).toHaveLength(1) - await service.startDictation('model-a', sink, undefined, 'desktop') - - expect(children).toHaveLength(1) - expect(sink).toHaveBeenCalledWith({ type: 'ready' }) - }) - - it('holds a dictation started mid pre-warm until the model has loaded', async () => { - const { service, children } = createService({ answerInit: false }) - const sink = vi.fn() - - const warming = service.prewarm('model-a') - await vi.waitFor(() => expect(children[0]?.modelDir).toBe('/models/model-a')) - const start = service.startDictation('model-a', sink, undefined, 'desktop') - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(sink).not.toHaveBeenCalled() - - children[0].worker.receiveMessage({ type: 'ready' }) - await Promise.all([warming, start]) - - expect(children).toHaveLength(1) - expect(sink).toHaveBeenCalledWith({ type: 'ready' }) - }) - - it('does not load a model that is not downloaded', async () => { - const { service, children } = createService({ status: { 'model-a': 'not-downloaded' } }) - - await service.prewarm('model-a') - - expect(children).toHaveLength(0) - }) - - it('frees the idle model when a model that is not downloaded is selected', async () => { - const { service, children } = createService({ status: { 'model-b': 'not-downloaded' } }) - await service.prewarm('model-a') - - await service.prewarm('model-b') - - expect(children).toHaveLength(1) - expect(children[0].killed).toBe(true) - }) - - it('retries a model that failed to load only when asked to', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { service, children } = createService({ answerInit: 'error' }) - - await service.prewarm('model-a') - await service.prewarm('model-a') - expect(children).toHaveLength(1) - - await service.prewarm('model-a', undefined, true) - expect(children).toHaveLength(2) - }) - - it('does not count a load cut short by an unload as a failure', async () => { - const { service, children } = createService({ answerInit: false }) - const warming = service.prewarm('model-a') - await vi.waitFor(() => expect(children[0]?.modelDir).toBe('/models/model-a')) - - await service.unloadIdleModel() - await warming - void service.prewarm('model-a') - - await vi.waitFor(() => expect(children).toHaveLength(2)) - }) - - it('does not load the model when voice is turned off while it checks the model', async () => { - const gate = Promise.withResolvers() - const { service, children } = createService({ modelStateGate: gate.promise }) - const warming = service.prewarm('model-a') - - await service.unloadIdleModel() - gate.resolve() - await warming - - expect(children).toHaveLength(0) - }) - - it('unloads a pre-warmed model after the default 15 idle minutes', async () => { - vi.useFakeTimers() - const { service, children } = createService() - - await service.prewarm('model-a') - await vi.advanceTimersByTimeAsync(15 * 60 * 1000 - 1) - expect(children[0].killed).toBe(false) - await vi.advanceTimersByTimeAsync(1) - - expect(children[0].killed).toBe(true) - }) - - it('keeps an idle model loaded when set to never unload', async () => { - vi.useFakeTimers() - const { service, children } = createService() - service.setIdleUnloadDelay(null) - - await service.prewarm('model-a') - await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000) - - expect(children[0].killed).toBe(false) - }) - - it('skips pre-warm and unloads after each dictation when set to immediately', async () => { - vi.useFakeTimers() - const { service, children } = createService() - service.setIdleUnloadDelay(0) - - await service.prewarm('model-a') - expect(children).toHaveLength(0) - await service.startDictation('model-a', vi.fn(), undefined, 'desktop') - await service.stopDictation('desktop') - await vi.advanceTimersByTimeAsync(0) - - expect(children[0].killed).toBe(true) - }) - - it('unloads the idle model at once when the setting changes to immediately', async () => { - const { service, children } = createService() - await service.prewarm('model-a') - - service.setIdleUnloadDelay(0) - - await vi.waitFor(() => expect(children[0].killed).toBe(true)) - }) -}) diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-connections.test.ts b/src/main/ssh/legacy-relay/legacy-relay-bridge-connections.test.ts deleted file mode 100644 index 13b5ec7b66c..00000000000 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-connections.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { EventEmitter } from 'node:events' -import { describe, expect, it, vi } from 'vitest' -import type { ClientChannel } from 'ssh2' -import type { SshConnection } from '../connection/ssh-connection' -import { - createLegacyRelayBridgeConnections, - LEGACY_RELAY_CHANNEL_BUDGET_EXHAUSTED, - RELAY_CHANNELS_ON_PRIMARY, - RELAY_CHANNELS_PER_SIDE_CONNECTION -} from './legacy-relay-bridge-connections' - -type FakeChannel = EventEmitter & { close: () => void } - -function fakeConnection( - options: { - systemSsh?: boolean - controlMaster?: boolean - connectError?: Error - maxSessions?: number - } = {} -) { - const channels: FakeChannel[] = [] - const conn = { - usesSystemSshTransport: () => options.systemSsh === true, - canRunConcurrentExecCommands: () => - options.systemSsh !== true || options.controlMaster === true, - connect: vi.fn(async () => { - if (options.connectError) { - throw options.connectError - } - }), - disconnect: vi.fn(async () => {}), - exec: vi.fn(async () => { - if (channels.length >= (options.maxSessions ?? Infinity)) { - throw Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 2 }) - } - const channel = Object.assign(new EventEmitter(), { - close: () => channel.emit('close') - }) - channels.push(channel) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pool only listens for 'close' and calls close(). - return channel as unknown as ClientChannel - }) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pool calls only the methods this fake defines. - return { conn, channels, asConnection: conn as unknown as SshConnection } -} - -describe('legacy relay bridge connections', () => { - it('keeps relay channels off the target connection, a bounded number per side connection', async () => { - const primary = fakeConnection() - const sides: ReturnType[] = [] - const pool = createLegacyRelayBridgeConnections({ - primary: () => primary.asConnection, - createSide: () => { - const side = fakeConnection() - sides.push(side) - return side.asConnection - } - }) - - for (let i = 0; i < 20; i++) { - await pool.open(`relay ${i}`) - } - - expect(primary.conn.exec).not.toHaveBeenCalled() - expect(sides.map((side) => side.channels.length)).toEqual([ - RELAY_CHANNELS_PER_SIDE_CONNECTION, - RELAY_CHANNELS_PER_SIDE_CONNECTION, - 20 - 2 * RELAY_CHANNELS_PER_SIDE_CONNECTION - ]) - }) - - it('closes a side connection once its last relay channel closes, and reuses freed room', async () => { - const sides: ReturnType[] = [] - const pool = createLegacyRelayBridgeConnections({ - primary: () => fakeConnection().asConnection, - createSide: () => { - const side = fakeConnection() - sides.push(side) - return side.asConnection - } - }) - await pool.open('a') - await pool.open('b') - sides[0].channels[0].close() - expect(sides[0].conn.disconnect).not.toHaveBeenCalled() - sides[0].channels[1].close() - expect(sides[0].conn.disconnect).toHaveBeenCalledTimes(1) - - await pool.open('c') - expect(sides).toHaveLength(2) - }) - - it('falls back to the target connection, within a budget, when a side cannot sign in unprompted', async () => { - const primary = fakeConnection() - const createSide = vi.fn(() => fakeConnection({ connectError: new Error('auth') }).asConnection) - const pool = createLegacyRelayBridgeConnections({ - primary: () => primary.asConnection, - createSide - }) - - for (let i = 0; i < RELAY_CHANNELS_ON_PRIMARY; i++) { - await pool.open(`relay ${i}`) - } - await expect(pool.open('one too many')).rejects.toThrow(LEGACY_RELAY_CHANNEL_BUDGET_EXHAUSTED) - - // One refused sign-in is not retried for every relay. - expect(createSide).toHaveBeenCalledTimes(1) - expect(primary.conn.exec).toHaveBeenCalledTimes(RELAY_CHANNELS_ON_PRIMARY) - - primary.channels[0].close() - await expect(pool.open('room again')).resolves.toBeDefined() - }) - - it('keeps system ssh on the target connection, budgeted only when a ControlMaster shares one session', async () => { - const createSide = vi.fn() - const shared = fakeConnection({ systemSsh: true, controlMaster: true }) - const sharedPool = createLegacyRelayBridgeConnections({ - primary: () => shared.asConnection, - createSide - }) - for (let i = 0; i < RELAY_CHANNELS_ON_PRIMARY; i++) { - await sharedPool.open(`relay ${i}`) - } - await expect(sharedPool.open('over')).rejects.toThrow(LEGACY_RELAY_CHANNEL_BUDGET_EXHAUSTED) - - const separate = fakeConnection({ systemSsh: true }) - const separatePool = createLegacyRelayBridgeConnections({ - primary: () => separate.asConnection, - createSide - }) - for (let i = 0; i < 20; i++) { - await separatePool.open(`relay ${i}`) - } - expect(separate.conn.exec).toHaveBeenCalledTimes(20) - expect(createSide).not.toHaveBeenCalled() - }) - - it('opens on another side connection when the host allows fewer sessions than the shard size', async () => { - const primary = fakeConnection() - const sides: ReturnType[] = [] - const pool = createLegacyRelayBridgeConnections({ - primary: () => primary.asConnection, - createSide: () => { - const side = fakeConnection({ maxSessions: 3 }) - sides.push(side) - return side.asConnection - } - }) - for (let i = 0; i < 7; i++) { - await pool.open(`relay ${i}`) - } - expect(primary.conn.exec).not.toHaveBeenCalled() - expect(sides.map((side) => side.channels.length)).toEqual([3, 3, 1]) - }) - - it('disconnects side connections on dispose and opens nothing after', async () => { - const side = fakeConnection() - const pool = createLegacyRelayBridgeConnections({ - primary: () => fakeConnection().asConnection, - createSide: () => side.asConnection - }) - await pool.open('relay') - pool.dispose() - expect(side.conn.disconnect).toHaveBeenCalledTimes(1) - await expect(pool.open('late')).rejects.toThrow('legacy_relay_bridge_disposed') - }) -}) diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.test.ts b/src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.test.ts deleted file mode 100644 index f5b9aed84fb..00000000000 --- a/src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.test.ts +++ /dev/null @@ -1,230 +0,0 @@ -import type * as ExecCommandModule from '../remote-exec/remote-exec-command' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { SshConnection } from '../connection/ssh-connection' -import { - parseRelayEndpointIncumbentProbe, - type RelayEndpointIncumbent -} from './ssh-relay-endpoint-incumbent' -import { getRemoteHostPlatform } from '../ssh-remote-platform' - -const { execCommand, probeRelayEndpointIncumbent, countRelayEndpointPtys } = vi.hoisted(() => ({ - execCommand: vi.fn(), - probeRelayEndpointIncumbent: vi.fn(), - countRelayEndpointPtys: vi.fn() -})) - -vi.mock('../remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand -})) -vi.mock('./ssh-relay-endpoint-pty-count', () => ({ countRelayEndpointPtys })) -vi.mock('./ssh-relay-endpoint-incumbent', async (importOriginal) => ({ - ...(await importOriginal>()), - probeRelayEndpointIncumbent -})) - -import { censusHostRelayEndpoints, readRelayEndpointProbe } from './ssh-host-relay-endpoint-census' -import { RELAY_DAEMON_ARGV_COMMAND } from './ssh-relay-endpoint-runtime' - -let daemonArgv = '' -function hostAnswers(listing: string): void { - execCommand.mockImplementation(async (_conn: unknown, command: string) => - command === RELAY_DAEMON_ARGV_COMMAND ? daemonArgv : listing - ) -} - -const conn: SshConnection = Object.create(null) -const linux = getRemoteHostPlatform('linux-x64') -const sock = (n: number) => `/home/dev/.orca-remote/relay-1.4.${n}/relay-abc.sock` - -const husk = { pid: 10, matchesRelayArgv: true, childCount: 0, unrecognizedChildCount: 0 } -const working = { ...husk, childCount: 1, unrecognizedChildCount: 1 } - -function incumbent(overrides: Partial): RelayEndpointIncumbent { - return { - sockPath: sock(1), - verdict: 'live', - evidence: 'accepted-connection', - socketPresent: true, - holders: [working], - holdersEnumerable: true, - ...overrides - } -} - -const census = (nodePath: () => Promise = async () => '/usr/bin/node') => - censusHostRelayEndpoints(conn, { - host: linux, - remoteHome: '/home/dev', - fallbackNodePath: nodePath - }) - -describe('the host-side relay endpoint census', () => { - beforeEach(() => { - execCommand.mockReset() - probeRelayEndpointIncumbent.mockReset() - // Without a relay reply, retain the probe's conservative verdict. - countRelayEndpointPtys.mockReset().mockResolvedValue(null) - daemonArgv = '' - }) - - it('finds none when no relay endpoint exists, without resolving node', async () => { - hostAnswers('') - const nodePath = vi.fn(async () => '/usr/bin/node') - - await expect(census(nodePath)).resolves.toEqual({ verdict: 'none', count: 0 }) - expect(nodePath).not.toHaveBeenCalled() - }) - - it('reads endpoints that hold no live work as idle', async () => { - hostAnswers(`${sock(1)}\n${sock(2)}\n`) - probeRelayEndpointIncumbent - .mockResolvedValueOnce(incumbent({ verdict: 'exited', socketPresent: true, holders: [] })) - // A live relay holding no shell of its own is a husk. - .mockResolvedValueOnce(incumbent({ holders: [husk] })) - - await expect(census()).resolves.toMatchObject({ verdict: 'idle' }) - }) - - it('reports live work any endpoint still runs, including another desktop\u2019s', async () => { - hostAnswers(`${sock(1)}\n/home/dev/.orca-remote/relay-1.4.1/relay-other.sock\n`) - probeRelayEndpointIncumbent - .mockResolvedValueOnce(incumbent({ verdict: 'exited', holders: [] })) - .mockResolvedValueOnce(incumbent({ holders: [working] })) - - await expect(census()).resolves.toEqual({ verdict: 'live', count: 1 }) - }) - - it('asks a relay the probe could not prove idle, and trusts its empty answer', async () => { - hostAnswers(`${sock(1)}\n${sock(2)}\n`) - // Holders not enumerable (no lsof): an accepting relay reads as live work to the probe. - probeRelayEndpointIncumbent - .mockResolvedValueOnce(incumbent({ holdersEnumerable: false })) - .mockResolvedValueOnce(incumbent({ verdict: 'unverifiable' })) - countRelayEndpointPtys.mockResolvedValue(0) - - await expect(census()).resolves.toEqual({ verdict: 'idle', count: 0 }) - expect(countRelayEndpointPtys).toHaveBeenCalledWith(conn, '/usr/bin/node', sock(1), undefined) - }) - - it('reports live work when the relay itself lists PTYs', async () => { - hostAnswers(`${sock(1)}\n`) - probeRelayEndpointIncumbent.mockResolvedValue(incumbent({})) - countRelayEndpointPtys.mockResolvedValue(2) - - await expect(census()).resolves.toEqual({ verdict: 'live', count: 1 }) - }) - - it.each([ - ['the listing failed', () => execCommand.mockRejectedValue(new Error('channel closed'))], - [ - 'an endpoint could not be classified', - () => { - hostAnswers(`${sock(1)}\n`) - probeRelayEndpointIncumbent.mockResolvedValue(incumbent({ verdict: 'unverifiable' })) - } - ], - [ - 'a probe threw', - () => { - hostAnswers(`${sock(1)}\n`) - probeRelayEndpointIncumbent.mockRejectedValue(new Error('timeout')) - } - ], - [ - 'there were more endpoints than it probes', - () => hostAnswers(Array.from({ length: 33 }, (_, i) => sock(i)).join('\n')) - ] - ])('is unverifiable when %s', async (_label, arrange) => { - arrange() - await expect(census()).resolves.toMatchObject({ verdict: 'unverifiable' }) - }) - - it('is unverifiable when endpoints exist but the host has no node to probe them', async () => { - hostAnswers(`${sock(1)}\n`) - await expect(census(async () => null)).resolves.toEqual({ verdict: 'unverifiable', count: 1 }) - }) - - it('cannot enumerate Windows named pipes', async () => { - await expect( - censusHostRelayEndpoints(conn, { - host: getRemoteHostPlatform('win32-x64'), - remoteHome: 'C:\\Users\\dev', - fallbackNodePath: async () => 'node.exe' - }) - ).resolves.toEqual({ verdict: 'unenumerable', count: 0 }) - expect(execCommand).not.toHaveBeenCalled() - }) - - it('probes and asks each relay with its own pinned runtime on a host with no Node on PATH', async () => { - const pinned = '/home/dev/.orca-remote/node-runtimes/v24.21.0-linux-x64/bin/node' - daemonArgv = `${pinned} relay.js --detached --grace-time 300 --sock-path ${sock(1)} --credential-file ${sock(1)}.credential\n` - hostAnswers(`${sock(1)}\n`) - probeRelayEndpointIncumbent.mockResolvedValue(incumbent({ holdersEnumerable: false })) - countRelayEndpointPtys.mockResolvedValue(0) - const noPathNode = vi.fn(async () => null) - - await expect(census(noPathNode)).resolves.toEqual({ verdict: 'idle', count: 0 }) - expect(probeRelayEndpointIncumbent).toHaveBeenCalledWith(conn, linux, pinned, sock(1), { - signal: undefined - }) - expect(countRelayEndpointPtys).toHaveBeenCalledWith(conn, pinned, sock(1), undefined) - expect(noPathNode).not.toHaveBeenCalled() - }) -}) - -describe('readRelayEndpointProbe', () => { - const probed = (lines: string[]) => - parseRelayEndpointIncumbentProbe( - sock(1), - ['ORCA-INCUMBENT-BEGIN', ...lines, 'ORCA-INCUMBENT-END'].join('\n') - ) - - it('reads a live relay that still owns PTYs as holding work', () => { - expect( - readRelayEndpointProbe( - probed([ - 'PRESENT=yes', - 'LISTEN=accepted', - 'HOLDERS_SOURCE=lsof', - 'HOLDER=3669803 yes 13 11' - ]) - ) - ).toBe('holds-work') - }) - - it('reads a proven empty relay as idle', () => { - expect( - readRelayEndpointProbe( - probed(['PRESENT=yes', 'LISTEN=accepted', 'HOLDERS_SOURCE=lsof', 'HOLDER=80583 yes 2 0']) - ) - ).toBe('idle') - }) - - it('reads a socket proven to have no holder as idle', () => { - expect( - readRelayEndpointProbe( - probed(['PRESENT=yes', 'LISTEN=refused', 'FS_TYPE=linux ef53 ef53', 'HOLDERS_SOURCE=lsof']) - ) - ).toBe('idle') - }) - - it('never reads a refused socket on a network home as idle: another machine may hold it', () => { - expect( - readRelayEndpointProbe( - probed(['PRESENT=yes', 'LISTEN=refused', 'FS_TYPE=linux 6969 ef53', 'HOLDERS_SOURCE=lsof']) - ) - ).toBe('unverifiable') - }) - - it('never reads an unanswered endpoint as idle', () => { - expect( - readRelayEndpointProbe( - probed(['PRESENT=yes', 'LISTEN=unknown', 'HOLDERS_SOURCE=unavailable']) - ) - ).toBe('unverifiable') - expect( - readRelayEndpointProbe(probed(['PRESENT=no', 'LISTEN=absent', 'HOLDERS_SOURCE=lsof'])) - ).toBe('unverifiable') - }) -}) diff --git a/src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts b/src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts index f724401c229..bb41dfbe72a 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts +++ b/src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts @@ -3,14 +3,8 @@ import { describe, expect, it, vi } from 'vitest' import type { ClientChannel } from 'ssh2' import { waitForSentinel } from './ssh-relay-sentinel' import { RELAY_SENTINEL } from '../remote-exec/remote-frame-protocol' -import { - RelayVersionMismatchError, - RELAY_EXIT_CODE_VERSION_MISMATCH -} from './ssh-relay-version-mismatch-error' -import { - RelayCredentialMismatchError, - RELAY_EXIT_CODE_CREDENTIAL_MISMATCH -} from './ssh-relay-credential-mismatch-error' +import './ssh-relay-version-mismatch-error' +import './ssh-relay-credential-mismatch-error' type MockChannel = ClientChannel & { stdin: EventEmitter & { write: ReturnType } @@ -26,44 +20,6 @@ function createMockChannel(): MockChannel { } describe('waitForSentinel', () => { - it('closes and rejects with AbortError while clearing startup resources on abort', async () => { - vi.useFakeTimers() - try { - const channel = createMockChannel() - const controller = new AbortController() - const removeListener = vi.spyOn(controller.signal, 'removeEventListener') - const transportPromise = waitForSentinel(channel, controller.signal) - - expect(vi.getTimerCount()).toBe(1) - controller.abort() - - await expect(transportPromise).rejects.toMatchObject({ name: 'AbortError' }) - expect(channel.close).toHaveBeenCalledTimes(1) - expect(removeListener).toHaveBeenCalledWith('abort', expect.any(Function)) - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('removes the abort listener and timers when startup fails before the sentinel', async () => { - vi.useFakeTimers() - try { - const channel = createMockChannel() - const controller = new AbortController() - const removeListener = vi.spyOn(controller.signal, 'removeEventListener') - const transportPromise = waitForSentinel(channel, controller.signal) - - channel.emit('error', new Error('remote host rebooted')) - - await expect(transportPromise).rejects.toThrow('remote host rebooted') - expect(removeListener).toHaveBeenCalledWith('abort', expect.any(Function)) - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - it('buffers post-sentinel chunks until the transport subscribes', async () => { const channel = createMockChannel() const transportPromise = waitForSentinel(channel) @@ -91,111 +47,6 @@ describe('waitForSentinel', () => { expect(chunks).toEqual(['same-chunk-frame']) }) - it('rejects on relay channel errors before the sentinel instead of emitting uncaught errors', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - expect(() => channel.emit('error', new Error('remote host rebooted'))).not.toThrow() - await expect(transportPromise).rejects.toThrow('remote host rebooted') - }) - - it('notifies transport close subscribers on relay channel errors after the sentinel', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - channel.emit('data', Buffer.from(RELAY_SENTINEL)) - const transport = await transportPromise - const onClose = vi.fn() - transport.onClose(onClose) - - expect(() => channel.emit('error', new Error('remote host rebooted'))).not.toThrow() - expect(onClose).toHaveBeenCalledTimes(1) - }) - - it('translates a pre-sentinel exit-42 + close into RelayVersionMismatchError', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - channel.stderr.emit( - 'data', - Buffer.from( - '[relay-connect] Handshake mismatch: expected=0.1.0+aaa, daemon=0.1.0+bbb; exiting 42\n' - ) - ) - channel.emit('exit', RELAY_EXIT_CODE_VERSION_MISMATCH) - channel.emit('close') - - await expect(transportPromise).rejects.toBeInstanceOf(RelayVersionMismatchError) - await transportPromise.catch((err: RelayVersionMismatchError) => { - expect(err.expected).toBe('0.1.0+aaa') - expect(err.got).toBe('0.1.0+bbb') - }) - }) - - it('translates a pre-sentinel exit-42 even when the version detail is missing', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - channel.stderr.emit('data', Buffer.from('boom\n')) - channel.emit('exit', RELAY_EXIT_CODE_VERSION_MISMATCH) - channel.emit('close') - - await expect(transportPromise).rejects.toBeInstanceOf(RelayVersionMismatchError) - }) - - it('translates a pre-sentinel exit-43 + close into RelayCredentialMismatchError', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - channel.stderr.emit( - 'data', - Buffer.from('[relay-connect] Endpoint credential refused by daemon; exiting 43\n') - ) - channel.emit('exit', RELAY_EXIT_CODE_CREDENTIAL_MISMATCH) - channel.emit('close') - - await expect(transportPromise).rejects.toBeInstanceOf(RelayCredentialMismatchError) - await transportPromise.catch((err: unknown) => { - expect(err).not.toBeInstanceOf(RelayVersionMismatchError) - }) - }) - - it('rejects with a generic error (not RelayVersionMismatchError) on a non-42 exit code', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - channel.stderr.emit('data', Buffer.from('node: bad bytecode\n')) - channel.emit('exit', 1) - channel.emit('close') - - await expect(transportPromise).rejects.toThrow(/Relay process exited before ready/) - await transportPromise.catch((err: unknown) => { - expect(err).not.toBeInstanceOf(RelayVersionMismatchError) - }) - }) - - it('rejects and closes the channel when pre-sentinel stdout exceeds the startup buffer cap', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - channel.emit('data', Buffer.alloc(65 * 1024, 'a')) - - const outcome = await Promise.race([ - transportPromise.then( - () => 'resolved', - (err: Error) => `rejected:${err.message}` - ), - new Promise((resolve) => setTimeout(() => resolve('pending'), 0)) - ]) - if (outcome === 'pending') { - channel.emit('close') - await transportPromise.catch(() => {}) - } - - expect(outcome).toContain('Relay startup output exceeded') - expect(channel.close).toHaveBeenCalledTimes(1) - }) - it('does not count same-chunk post-sentinel payload against the startup buffer cap', async () => { const channel = createMockChannel() const transportPromise = waitForSentinel(channel) @@ -217,33 +68,4 @@ describe('waitForSentinel', () => { expect(Buffer.concat(chunks)).toEqual(postSentinelPayload) expect(channel.close).not.toHaveBeenCalled() }) - - it.each(['ssh2 channel', 'system-SSH child stdio'])( - 'forwards write(false), callback settlement, and drain for a %s', - async (channelKind) => { - const channel = createMockChannel() - if (channelKind.startsWith('system')) { - Object.assign(channel, { _process: new EventEmitter() }) - } - const callback = vi.fn() - const drain = vi.fn() - channel.stdin.write.mockImplementation((...args: unknown[]) => { - const onWritten = args.find((arg) => typeof arg === 'function') as ( - error?: Error | null - ) => void - onWritten(null) - return false - }) - const transportPromise = waitForSentinel(channel) - channel.emit('data', Buffer.from(RELAY_SENTINEL)) - const transport = await transportPromise - - transport.onDrain?.(drain) - expect(transport.write(Buffer.from('frame'), callback)).toBe(false) - expect(callback).toHaveBeenCalledWith({ ok: true }) - channel.stdin.emit('drain') - expect(drain).toHaveBeenCalledOnce() - expect(transport.supportsWriteSettlement).toBe(true) - } - ) }) diff --git a/src/main/ssh/orcad-migration-automation-run-history.test.ts b/src/main/ssh/orcad-migration-automation-run-history.test.ts index fec0a70f55a..49b54a5fb86 100644 --- a/src/main/ssh/orcad-migration-automation-run-history.test.ts +++ b/src/main/ssh/orcad-migration-automation-run-history.test.ts @@ -11,9 +11,9 @@ import { closeTestStores, createSqliteTestStore } from '../persistence/persisten import { Store } from '../persistence/loading-store/store' import { commitOrcadMigrationDestination } from './orcad-migration-cutover-coordinator' import { storeBackedOrcadMigrationDestination } from './orcad-migration-destination-fake' -import { writeOrcadMigrationSourceCutover } from './orcad-migration-cutover-journal' -import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' -import { assertOrcadMigrationSourceUnchanged } from './orcad-migration-source-assertions' +import './orcad-migration-cutover-journal' +import './orcad-migration-manifest-export' +import './orcad-migration-source-assertions' import { fenceOrcadMigrationSource } from './orcad-migration-source-fence' import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' @@ -128,23 +128,4 @@ describe('moving automation run history to a host server', () => { expect(h.server.getOrcadMigrationCatalogState(manifest).state).toBe('staged') expect(h.server.listAutomations()).toEqual([]) }) - it('still resumes a journal an older desktop signed with its runs inline', async () => { - const h = await hostWithRunHistory(10) - const inline = createOrcadMigrationManifest(h.store, TARGET, { - migrationId: h.cutover.migrationId, - destinationEnvironmentId: h.cutover.destinationEnvironmentId, - now: () => new Date(h.cutover.manifest.createdAt), - inlineAutomationRuns: true - }) - expect(inline.payload.dormantState?.automationRuns).toHaveLength(40) - const journaled = { ...h.cutover, manifest: inline, manifestSha256: inline.manifestSha256 } - writeOrcadMigrationSourceCutover(h.userDataPath, journaled) - - expect( - assertOrcadMigrationSourceUnchanged( - { userDataPath: h.userDataPath, store: h.store }, - journaled - ) - ).toEqual([]) - }) }) diff --git a/src/main/ssh/orcad-retained-source-lists.test.ts b/src/main/ssh/orcad-retained-source-lists.test.ts deleted file mode 100644 index 5eefe3da443..00000000000 --- a/src/main/ssh/orcad-retained-source-lists.test.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../shared/project-group-types' -import type { ProjectHostSetup } from '../../shared/project-types' -import type { Repo } from '../../shared/repo-types' -import type { SshTarget } from '../../shared/ssh-types' -import type { Store } from '../persistence/loading-store/store' -import { orcadMigrationCutoverFixture } from './orcad-migration-cutover-fixture' -import { writeOrcadMigrationSourceCutover } from './orcad-migration-cutover-journal' -import { wslMoveCutoverFixture } from '../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { seedWslMoveCutover } from '../persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' -import { - loadWslMoveFence, - resetWslMoveFenceForTests -} from '../persistence/moving-wsl-projects/wsl-move-scope-guard' - -const userData = vi.hoisted(() => ({ dir: '' })) -vi.mock('../../shared/app-environment', () => ({ - getAppEnvironment: () => ({ getPath: () => userData.dir }) -})) - -const { isFrozenOrcadSourceSessionPartition, visibleProjectGroups, visibleProjectHostSetups } = - await import('./orcad-retained-source') -const { visibleSessionHostIds } = await import('./orcad-retained-source-session') - -const FENCED: SshTarget = { - id: 'ssh-box', - label: 'Box', - host: 'box.example.com', - port: 22, - username: 'me', - generation: 2, - orcadFence: { environmentId: 'env-1' } -} - -function group(id: string, connectionId: string | null): ProjectGroup { - return { - id, - name: id, - parentPath: '/srv', - parentGroupId: null, - connectionId, - createdFrom: 'manual', - tabOrder: 0, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - } -} - -const sourceRepo: Repo = { - id: 'repo-1', - path: '/srv/app', - displayName: 'App', - badgeColor: '#737373', - addedAt: 1, - kind: 'git', - connectionId: FENCED.id -} - -function catalog(targets: SshTarget[]): Store { - const groups = [group('source-group', FENCED.id), group('local-group', null)] - const folders: FolderWorkspace[] = [] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the lists read only these four getters. - return { - getSshTargets: () => targets, - getRepos: () => [sourceRepo], - getProjectGroups: () => groups, - getFolderWorkspaces: () => folders - } as unknown as Store -} - -describe('lists while a converted host keeps its source rows', () => { - beforeEach(() => { - userData.dir = mkdtempSync(join(tmpdir(), 'orcad-retained-lists-')) - writeOrcadMigrationSourceCutover(userData.dir, { - ...orcadMigrationCutoverFixture('m-0', FENCED.id), - phase: 'destination-committed' - }) - }) - afterEach(() => rmSync(userData.dir, { recursive: true, force: true })) - - it('shows every row of a fenced host no journal explains, as after an empty-host deploy', () => { - const emptyDeploy = mkdtempSync(join(tmpdir(), 'orcad-retained-lists-')) - try { - // An older build added these after the deploy; no move owns them, so they stay visible. - expect(visibleProjectGroups(catalog([FENCED]), () => emptyDeploy)).toHaveLength(2) - } finally { - rmSync(emptyDeploy, { recursive: true, force: true }) - } - }) - - it('hides the host own project groups, but not a local group', () => { - expect(visibleProjectGroups(catalog([FENCED])).map((entry) => entry.id)).toEqual([ - 'local-group' - ]) - }) - - it('shows them again once an older build changed the host', () => { - const changed = { ...FENCED, orcadFence: { environmentId: 'env-1', sourceChangedAt: 'x' } } - expect(visibleProjectGroups(catalog([changed])).map((entry) => entry.id)).toEqual([ - 'source-group', - 'local-group' - ]) - }) - - // #33539: adopting the hidden source's session at startup restored tabs closed on the server. - it('leaves the hidden host session out of the partition census until the host changes', () => { - const hostIds: ExecutionHostId[] = ['local', 'ssh:ssh-box', 'ssh:other', 'runtime:env-1'] - expect(visibleSessionHostIds(catalog([FENCED]), hostIds)).toEqual([ - 'local', - 'ssh:other', - 'runtime:env-1' - ]) - const changed = { ...FENCED, orcadFence: { environmentId: 'env-1', sourceChangedAt: 'x' } } - expect(visibleSessionHostIds(catalog([changed]), hostIds)).toEqual(hostIds) - // A fenced move that has not committed still shows its repos, so their session stays too. - const inFlight = mkdtempSync(join(tmpdir(), 'orcad-retained-lists-')) - try { - writeOrcadMigrationSourceCutover(inFlight, orcadMigrationCutoverFixture('m-1', FENCED.id)) - expect(visibleSessionHostIds(catalog([FENCED]), hostIds, () => inFlight)).toEqual(hostIds) - } finally { - rmSync(inFlight, { recursive: true, force: true }) - } - }) - - it('shows them until the migration commits, while freezing the session from the fence on', () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orcad-retained-lists-')) - try { - const cutover = orcadMigrationCutoverFixture('m-1', FENCED.id) - writeOrcadMigrationSourceCutover(userDataPath, cutover) - const store = catalog([FENCED]) - const lookup = { getSshTarget: () => FENCED } - expect(visibleProjectGroups(store, () => userDataPath)).toHaveLength(2) - expect(isFrozenOrcadSourceSessionPartition(lookup, 'ssh:ssh-box')).toBe(true) - writeOrcadMigrationSourceCutover(userDataPath, { ...cutover, phase: 'destination-committed' }) - expect(visibleProjectGroups(store, () => userDataPath)).toHaveLength(1) - expect(isFrozenOrcadSourceSessionPartition(lookup, 'local')).toBe(false) - const changed = { ...FENCED, orcadFence: { environmentId: 'env-1', sourceChangedAt: 'x' } } - expect( - isFrozenOrcadSourceSessionPartition({ getSshTarget: () => changed }, 'ssh:ssh-box') - ).toBe(false) - } finally { - rmSync(userDataPath, { recursive: true, force: true }) - } - }) -}) - -function setup(id: string, hostId: ExecutionHostId, repoId: string): ProjectHostSetup { - return { - id, - projectId: 'github:acme/app', - hostId, - repoId, - path: '/srv/app', - displayName: 'App', - setupState: repoId ? 'ready' : 'not-set-up', - setupMethod: 'legacy-repo', - createdAt: 1, - updatedAt: 1 - } -} - -describe('project host setups of a converted host', () => { - const localRepo: Repo = { ...sourceRepo, id: 'repo-local', path: '/work/app' } - delete localRepo.connectionId - const setups = [ - setup('repo-1', 'ssh:ssh-box', 'repo-1'), - setup('placeholder', 'ssh:ssh-box', ''), - setup('repo-local', 'local', 'repo-local') - ] - type SetupCatalog = Parameters[0] - const catalogOf = (targets: SshTarget[], repos: Repo[], rows = setups): SetupCatalog => ({ - getSshTargets: () => targets, - getRepos: () => repos, - getProjectGroups: () => [], - getFolderWorkspaces: () => [], - getProjectHostSetups: () => rows - }) - const store = (targets: SshTarget[]): SetupCatalog => catalogOf(targets, [sourceRepo, localRepo]) - let dir = '' - beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orcad-retained-setups-')) - userData.dir = dir - writeOrcadMigrationSourceCutover(dir, { - ...orcadMigrationCutoverFixture('m-0', FENCED.id), - phase: 'destination-committed' - }) - }) - afterEach(() => rmSync(dir, { recursive: true, force: true })) - - // #30859: retained setup rows duplicated the server's same-id host setups. - it('hides the setups the hidden source rows own, and keeps local ones', () => { - expect(visibleProjectHostSetups(store([FENCED])).map((entry) => entry.id)).toEqual([ - 'repo-local' - ]) - }) - - it('hides a folder-only host placeholder even when no repo row is hidden', () => { - const folderOnly = catalogOf([FENCED], [localRepo], setups.slice(1)) - expect(visibleProjectHostSetups(folderOnly).map((entry) => entry.id)).toEqual(['repo-local']) - }) - - it('hides the local setup of a project a WSL move took, by its repo row alone', () => { - loadWslMoveFence(dir) - try { - seedWslMoveCutover( - dir, - wslMoveCutoverFixture('move-1', 'destination-committed', {}, { repoIds: ['repo-local'] }) - ) - // No SSH host is fenced here, so only the repo-row match can drop the setup. - expect(visibleProjectHostSetups(store([])).map((entry) => entry.id)).toEqual([ - 'repo-1', - 'placeholder' - ]) - } finally { - resetWslMoveFenceForTests() - } - }) - - it('lists them again once an older build changed the host', () => { - const changed = { ...FENCED, orcadFence: { environmentId: 'env-1', sourceChangedAt: 'x' } } - expect(visibleProjectHostSetups(store([changed]))).toHaveLength(3) - }) -}) diff --git a/src/main/ssh/remote-exec/remote-host-failure-producers.test.ts b/src/main/ssh/remote-exec/remote-host-failure-producers.test.ts index fd097e158d6..8f5a83411ee 100644 --- a/src/main/ssh/remote-exec/remote-host-failure-producers.test.ts +++ b/src/main/ssh/remote-exec/remote-host-failure-producers.test.ts @@ -4,20 +4,15 @@ import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { NODE_RUNTIME_PIN } from '../../../shared/node-runtime-pin' +import '../../../shared/node-runtime-pin' import type { SshTarget } from '../../../shared/ssh-types' -import { runProcess, runProcessSync } from '@orca/process-host' -import { - REMOTE_NODE_RUNTIME_READY, - REMOTE_NODE_RUNTIME_VERIFIED_MARKER, - RemoteNodeRuntimeSelfTestError, - assertRemoteNodeRuntimePromoted -} from '../orcad-remote-node-runtime-report' -import { remoteNodeRuntimePresentCommand } from '../../managed-server/install/orcad-remote-node-runtime' -import { getRemoteHostPlatform } from '../ssh-remote-platform' +import '@orca/process-host' +import '../orcad-remote-node-runtime-report' +import '../../managed-server/install/orcad-remote-node-runtime' +import '../ssh-remote-platform' import { findSystemSsh } from '../system-transport/system-ssh-binary' import { uploadDirectoryViaSystemSsh } from '../system-transport/system-ssh-file-transfer' -import { runSftpBatch } from '../system-transport/system-ssh-sftp-transfer' +import '../system-transport/system-ssh-sftp-transfer' import { isHostAnsweredSystemSshExit } from '../system-transport/system-ssh-operation-lifecycle' vi.mock('@orca/process-host', async (importOriginal) => ({ @@ -49,28 +44,7 @@ async function script(name: string, body: string): Promise { return path } -async function payload(): Promise { - const dir = join(scratch, 'payload') - await mkdir(dir) - await writeFile(join(dir, 'runtime.tar.gz'), 'fixture') - return dir -} - describe.runIf(posix)('system-ssh directory upload', () => { - it('reports a remote tar ENOSPC as the host answering', async () => { - vi.mocked(findSystemSsh).mockReturnValue( - await script( - 'ssh', - 'cat >/dev/null\necho "tar: Cannot write: No space left on device" >&2\nexit 2' - ) - ) - const error = await uploadDirectoryViaSystemSsh(target, await payload(), '/remote').catch( - (e: unknown) => e - ) - expect(String(error)).toContain('No space left on device') - expect(isHostAnsweredSystemSshExit(error)).toBe(true) - }) - it('keeps the remote ENOSPC when the far end closes mid-stream and local tar then fails to write', async () => { // Keep tar writing past SSH exit so downstream failure occurs on BSD tar too. const dir = join(scratch, 'large') @@ -91,29 +65,6 @@ describe.runIf(posix)('system-ssh directory upload', () => { } }) - it("keeps ssh's own exit 255 (contact lost) retryable", async () => { - vi.mocked(findSystemSsh).mockReturnValue( - await script('ssh', 'cat >/dev/null\necho "Connection reset by peer" >&2\nexit 255') - ) - const error = await uploadDirectoryViaSystemSsh(target, await payload(), '/remote').catch( - (e: unknown) => e - ) - expect(isHostAnsweredSystemSshExit(error)).toBe(false) - }) - - it('blames a local tar failure, not the remote tar that saw a truncated stream', async () => { - vi.mocked(findSystemSsh).mockReturnValue( - await script('ssh', 'cat >/dev/null\necho "tar: Unexpected EOF in archive" >&2\nexit 2') - ) - const error = await uploadDirectoryViaSystemSsh( - target, - join(scratch, 'missing'), - '/remote' - ).catch((e: unknown) => e) - expect(String(error)).toContain('local tar relay upload') - expect(isHostAnsweredSystemSshExit(error)).toBe(false) - }) - it('blames the local tar failure even when the remote exit is observed first', async () => { // Local tar closes its output, so remote tar sees EOF and exits, before tar reports its own failure. await script('tar', 'exec 1>&-\nsleep 1\necho "tar: could not chdir to missing" >&2\nexit 1') @@ -128,92 +79,3 @@ describe.runIf(posix)('system-ssh directory upload', () => { expect(isHostAnsweredSystemSshExit(error)).toBe(false) }) }) - -describe('system sftp batch', () => { - beforeEach(() => { - vi.stubEnv('ORCA_SYSTEM_SFTP_PATH', '/fixture/sftp') - }) - - it('reports a Windows file permission refusal as the host answering', async () => { - vi.mocked(runProcess).mockResolvedValueOnce({ - code: 1, - signal: null, - stdout: '', - stderr: 'dest open "C:/Users/me/.orca-remote/node.zip": Permission denied', - timedOut: false - }) - const error = await runSftpBatch(target, ['put node.zip']).catch((e: unknown) => e) - expect(String(error)).toContain('sftp batch failed (exit 1)') - expect(isHostAnsweredSystemSshExit(error)).toBe(true) - }) - - it.each([ - [255, 'Connection closed'], - [1, 'Connection reset by peer'] - ])('keeps a lost connection (exit %i: %s) unanswered', async (code, stderr) => { - vi.mocked(runProcess).mockResolvedValueOnce({ - code, - signal: null, - stdout: '', - stderr, - timedOut: false - }) - const error = await runSftpBatch(target, ['put node.zip']).catch((e: unknown) => e) - expect(String(error)).toContain(stderr) - expect(isHostAnsweredSystemSshExit(error)).toBe(false) - }) -}) - -describe.runIf(posix)('warm runtime check on a cached install', () => { - const host = getRemoteHostPlatform('linux-x64') - - async function cachedRuntime(nodeBody: string): Promise { - const runtimeDir = join(scratch, 'runtime') - await mkdir(join(runtimeDir, 'bin'), { recursive: true }) - await writeFile(join(runtimeDir, REMOTE_NODE_RUNTIME_VERIFIED_MARKER), '') - const node = join(runtimeDir, 'bin', 'node') - await writeFile(node, `#!/bin/sh\n${nodeBody}\n`) - await chmod(node, 0o755) - return runtimeDir - } - - function runCheck(runtimeDir: string, run: boolean): string { - return runProcessSync({ - program: '/bin/sh', - args: ['-c', remoteNodeRuntimePresentCommand(host, runtimeDir, run)] - }).stdout - } - - it('stays READY while the cached runtime still runs', async () => { - const runtimeDir = await cachedRuntime(`echo v${NODE_RUNTIME_PIN.version}`) - expect(runCheck(runtimeDir, true).trim()).toBe(REMOTE_NODE_RUNTIME_READY) - }) - - it.each([ - [ - 'a shared library removed since the install', - 'echo "node: error while loading shared libraries: libatomic.so.1: cannot open shared object file" >&2\nexit 127', - 127 - ], - [ - 'an exec policy that now denies uploaded binaries', - 'echo "sh: node: Permission denied" >&2\nexit 126', - 126 - ] - ])('reports %s as an answered refusal before launch', async (_label, body, exitStatus) => { - const runtimeDir = await cachedRuntime(body) - // Without running it, presence alone still says READY: the gap this check closes. - expect(runCheck(runtimeDir, false).trim()).toBe(REMOTE_NODE_RUNTIME_READY) - const output = runCheck(runtimeDir, true) - let thrown: unknown - try { - assertRemoteNodeRuntimePromoted(output) - } catch (error) { - thrown = error - } - if (!(thrown instanceof RemoteNodeRuntimeSelfTestError)) { - throw new Error(`expected a self-test refusal, got ${String(thrown)}`) - } - expect(thrown.exitStatus).toBe(exitStatus) - }) -}) diff --git a/src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts b/src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts deleted file mode 100644 index 22b3361f2f3..00000000000 --- a/src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { VerifiedCodexResumeSource } from '../codex/history/resume/codex-session-resume-preparation' - -/** Launch/resume must honor the hook opt-out or they reinstall the entry just removed by settings. */ -const SYSTEM_HOME = '/home/user/.codex' -const ACCOUNT_HOME = '/accounts/one/.codex' - -const mocks = vi.hoisted(() => { - const settings: Partial = {} - return { - settings, - prepareForCodexLaunchAsync: vi.fn(async (): Promise => null), - isHostSystemDefaultRealHomeSelected: vi.fn(() => false), - prepareRuntimeHomeForLaunch: vi.fn(async () => ({ state: 'ok' as const })), - installForLaunchPrep: vi.fn(async () => {}), - refreshRuntimeUserHooksForLaunchPrep: vi.fn(async () => {}), - reconcileCodexHooksForLaunch: vi.fn(async () => {}), - prepareCodexSessionResume: vi.fn() - } -}) - -vi.mock('electron', () => ({ app: { getPath: vi.fn(() => '/tmp/orca-user-data') } })) -vi.mock('../agent-launch/trust/agent-trust-presets', () => ({ - markCodexProjectTrusted: vi.fn(async () => {}) -})) -vi.mock('../codex/hooks/installation/hook-service', () => ({ - codexHookService: { - prepareRuntimeHomeForLaunch: mocks.prepareRuntimeHomeForLaunch, - installForLaunchPrep: mocks.installForLaunchPrep, - refreshRuntimeUserHooksForLaunchPrep: mocks.refreshRuntimeUserHooksForLaunchPrep - } -})) -vi.mock('../codex/hooks/reconciliation/codex-hook-reconcile', () => ({ - reconcileCodexHooksForLaunch: mocks.reconcileCodexHooksForLaunch -})) -// Keep the real predicate without importing every agent hook service. -vi.mock( - '../agent-hooks/managed-agent-hook-controls', - async () => - await import('../../shared/agent-hook-listener/configuration/agent-status-hooks-setting') -) -vi.mock('../wsl/discovery/distro-catalog', () => ({ getDefaultWslDistro: () => 'Ubuntu' })) -vi.mock('../codex/configuration/homes/codex-home-paths', () => ({ - getSystemCodexHomePath: () => SYSTEM_HOME, - getOrcaManagedCodexHomePath: () => '/managed/.codex' -})) -vi.mock('../codex/history/resume/codex-session-resume-preparation', () => ({ - prepareCodexSessionResume: mocks.prepareCodexSessionResume -})) -vi.mock('../codex/history/resume/codex-legacy-session-resume', () => ({ - prepareLegacySharedCodexSessionResume: vi.fn(async () => ({ useRealCodexHome: false })) -})) -vi.mock('./main-process-state', () => ({ - mainProcessState: { - codexRuntimeHome: { - prepareForCodexLaunchAsync: mocks.prepareForCodexLaunchAsync, - isHostSystemDefaultRealHomeSelected: mocks.isHostSystemDefaultRealHomeSelected, - getHostCodexHomePathsForSessionDiscovery: () => [], - resolveSelectedHostAccountCodexHomePathForResume: () => null - }, - store: { getSettings: () => mocks.settings } - } -})) - -import { prepareCodexRuntimeHomeForLaunch } from './codex-launch-preparation' -import { prepareCodexSessionResumeForLaunch } from './codex-session-resume-launch' - -const HOOK_SETTINGS: readonly { - name: string - settings: Partial - codexHooksOn: boolean -}[] = [ - { - name: 'Codex turned off per agent', - settings: { agentStatusHooksEnabled: true, disabledTuiAgents: ['codex'] }, - codexHooksOn: false - }, - { - name: 'every agent on', - settings: { agentStatusHooksEnabled: true, disabledTuiAgents: [] }, - codexHooksOn: true - }, - { - name: 'another agent turned off', - settings: { agentStatusHooksEnabled: true, disabledTuiAgents: ['claude'] }, - codexHooksOn: true - }, - { - name: 'the global switch off', - settings: { agentStatusHooksEnabled: false, disabledTuiAgents: [] }, - codexHooksOn: false - } -] - -function readsSetting(enabled: boolean): { asymmetricMatch: (reader: unknown) => boolean } { - return { asymmetricMatch: (reader) => typeof reader === 'function' && reader() === enabled } -} - -function resumeFrom(homePath: string): Promise { - mocks.prepareCodexSessionResume.mockImplementation( - async (args: { - resolveVerifiedResumeHome: (source: VerifiedCodexResumeSource) => Promise - }) => { - const codexHomePath = await args.resolveVerifiedResumeHome({ - homePath, - transcriptPath: `${homePath}/sessions/abc.jsonl` - }) - return { outcome: 'resume' as const, codexHomePath, sessionId: 'abc' } - } - ) - return prepareCodexSessionResumeForLaunch({ - providerSession: { key: 'session_id', id: 'abc' }, - target: { runtime: 'host' } - }) -} - -describe('Codex launch prep honours the per-agent hook opt-out', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.isHostSystemDefaultRealHomeSelected.mockReturnValue(false) - mocks.prepareForCodexLaunchAsync.mockResolvedValue(null) - }) - - it.each(HOOK_SETTINGS)( - 'real ~/.codex launch with $name: the reconcile reads the opt-out', - async ({ settings }) => { - mocks.settings = settings - mocks.isHostSystemDefaultRealHomeSelected.mockReturnValue(true) - - await expect( - prepareCodexRuntimeHomeForLaunch(undefined, undefined, { launchesCodex: true }) - ).resolves.toBeNull() - - // Reconciliation itself checks opt-out before writing. - expect(mocks.reconcileCodexHooksForLaunch).toHaveBeenCalledTimes(1) - expect(mocks.prepareRuntimeHomeForLaunch).not.toHaveBeenCalled() - } - ) - - it.each(HOOK_SETTINGS)( - 'managed account home launch with $name: hooks on = $codexHooksOn', - async ({ settings, codexHooksOn }) => { - mocks.settings = settings - mocks.prepareForCodexLaunchAsync.mockResolvedValue(ACCOUNT_HOME) - - await expect( - prepareCodexRuntimeHomeForLaunch(undefined, undefined, { launchesCodex: true }) - ).resolves.toBe(ACCOUNT_HOME) - - expect(mocks.reconcileCodexHooksForLaunch).not.toHaveBeenCalled() - expect(mocks.prepareRuntimeHomeForLaunch).toHaveBeenCalledWith( - ACCOUNT_HOME, - undefined, - readsSetting(codexHooksOn), - true - ) - } - ) - - it.each(HOOK_SETTINGS)( - 'resume into the real ~/.codex with $name: the reconcile reads the opt-out', - async ({ settings }) => { - mocks.settings = settings - - await resumeFrom(SYSTEM_HOME) - - // Resuming a system-home session reconciles there regardless of current account selection. - expect(mocks.reconcileCodexHooksForLaunch).toHaveBeenCalledTimes(1) - expect(mocks.installForLaunchPrep).not.toHaveBeenCalled() - expect(mocks.refreshRuntimeUserHooksForLaunchPrep).not.toHaveBeenCalled() - } - ) - - it.each(HOOK_SETTINGS)( - 'resume into a managed account home with $name: hooks on = $codexHooksOn', - async ({ settings, codexHooksOn }) => { - mocks.settings = settings - - await resumeFrom(ACCOUNT_HOME) - - expect(mocks.reconcileCodexHooksForLaunch).not.toHaveBeenCalled() - if (codexHooksOn) { - expect(mocks.installForLaunchPrep).toHaveBeenCalledWith( - ACCOUNT_HOME, - true, - readsSetting(true) - ) - expect(mocks.refreshRuntimeUserHooksForLaunchPrep).not.toHaveBeenCalled() - } else { - expect(mocks.installForLaunchPrep).not.toHaveBeenCalled() - expect(mocks.refreshRuntimeUserHooksForLaunchPrep).toHaveBeenCalledWith(ACCOUNT_HOME) - } - } - ) - - it("never makes a plain terminal or a structured launch wait for Codex's hook hashes", async () => { - mocks.settings = { agentStatusHooksEnabled: true, disabledTuiAgents: [] } - mocks.prepareForCodexLaunchAsync.mockResolvedValue(ACCOUNT_HOME) - - await prepareCodexRuntimeHomeForLaunch() - await prepareCodexRuntimeHomeForLaunch(undefined, undefined, { launchesCodex: false }) - mocks.prepareForCodexLaunchAsync.mockResolvedValue(null) - await prepareCodexRuntimeHomeForLaunch() - - expect(mocks.prepareRuntimeHomeForLaunch.mock.calls).toEqual([ - [ACCOUNT_HOME, undefined, readsSetting(true), false], - [ACCOUNT_HOME, undefined, readsSetting(true), false] - ]) - expect(mocks.reconcileCodexHooksForLaunch).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/startup/login-shell-environment-cache.test.ts b/src/main/startup/login-shell-environment-cache.test.ts index ecd8198d4ca..d4d5f8becf1 100644 --- a/src/main/startup/login-shell-environment-cache.test.ts +++ b/src/main/startup/login-shell-environment-cache.test.ts @@ -1,105 +1,11 @@ import { afterEach, expect, it, vi } from 'vitest' import { - captureLoginShellEnvironment, resetLoginShellEnvironmentCacheForTests, resolveLoginShellEnvironment } from './login-shell-environment' afterEach(resetLoginShellEnvironmentCacheForTests) -it('shares concurrent probes only within the same shell and environment', async () => { - const release = Promise.withResolvers() - const spawner = vi.fn(async (_shell: string, env: NodeJS.ProcessEnv) => { - await release.promise - return { PI_CONFIG_DIR: env.PROFILE_ROOT } - }) - const first = { HOME: '/host/a', PROFILE_ROOT: '.first' } - const second = { HOME: '/host/a', PROFILE_ROOT: '.second' } - const pending = [ - resolveLoginShellEnvironment({ shellOverride: '/bin/bash', env: first, spawner }), - resolveLoginShellEnvironment({ shellOverride: '/bin/bash', env: second, spawner }), - ...Array.from({ length: 20 }, () => - resolveLoginShellEnvironment({ - shellOverride: '/bin/bash', - env: { PROFILE_ROOT: '.first', HOME: '/host/a' }, - spawner - }) - ) - ] - expect(spawner).toHaveBeenCalledTimes(2) - release.resolve() - const values = await Promise.all(pending) - expect(values[0]?.PI_CONFIG_DIR).toBe('.first') - expect(values[1]?.PI_CONFIG_DIR).toBe('.second') - expect(values.slice(2).every((value) => value.PI_CONFIG_DIR === '.first')).toBe(true) - await resolveLoginShellEnvironment({ shellOverride: '/bin/zsh', env: first, spawner }) - expect(spawner).toHaveBeenCalledTimes(3) -}) - -it('bounds retained environments and supports explicit refresh', async () => { - const spawner = vi.fn(async (_shell: string, env: NodeJS.ProcessEnv) => env) - for (let index = 0; index < 10; index++) { - await resolveLoginShellEnvironment({ - shellOverride: '/bin/bash', - env: { HOME: `/host/${index}` }, - spawner - }) - } - await resolveLoginShellEnvironment({ - shellOverride: '/bin/bash', - env: { HOME: '/host/0' }, - spawner - }) - expect(spawner).toHaveBeenCalledTimes(11) - await resolveLoginShellEnvironment({ - shellOverride: '/bin/bash', - env: { HOME: '/host/0' }, - spawner, - startedAfter: Date.now() - }) - expect(spawner).toHaveBeenCalledTimes(12) -}) - -it('says whether the shell produced the env, and a failed rerun keeps the cached one', async () => { - const env = { HOME: '/host' } - const spawner = vi - .fn<(shell: string, env: NodeJS.ProcessEnv) => Promise>() - .mockResolvedValueOnce({ PATH: '/profile/bin' }) - .mockResolvedValueOnce(null) - const options = { shellOverride: '/bin/bash', env, spawner } - await expect(captureLoginShellEnvironment(options)).resolves.toEqual({ - status: 'captured', - env: { PATH: '/profile/bin' } - }) - await expect( - captureLoginShellEnvironment({ ...options, startedAfter: Date.now() }) - ).resolves.toEqual({ - status: 'fallback', - env - }) - await expect(resolveLoginShellEnvironment(options)).resolves.toEqual({ PATH: '/profile/bin' }) - expect(spawner).toHaveBeenCalledTimes(2) -}) - -it('serves the cached env to other readers while a rerun runs', async () => { - const release = Promise.withResolvers() - const spawner = vi - .fn<(shell: string, env: NodeJS.ProcessEnv) => Promise>() - .mockResolvedValueOnce({ PATH: '/first' }) - .mockReturnValueOnce(release.promise) - const options = { shellOverride: '/bin/bash', env: { HOME: '/host' }, spawner } - await resolveLoginShellEnvironment(options) - const forced = resolveLoginShellEnvironment({ ...options, startedAfter: Date.now() }) - const tick = new Promise((resolve) => setImmediate(() => resolve('still waiting'))) - await expect(Promise.race([resolveLoginShellEnvironment(options), tick])).resolves.toEqual({ - PATH: '/first' - }) - release.resolve({ PATH: '/second' }) - await expect(forced).resolves.toEqual({ PATH: '/second' }) - await expect(resolveLoginShellEnvironment(options)).resolves.toEqual({ PATH: '/second' }) - expect(spawner).toHaveBeenCalledTimes(2) -}) - type Spawner = (shell: string, env: NodeJS.ProcessEnv) => Promise it('answers a lookup only with a run that started no earlier, so a run predating an install never counts', async () => { @@ -135,61 +41,3 @@ it('answers a lookup only with a run that started no earlier, so a run predating vi.useRealTimers() } }) - -it('reruns a failed shell once its last attempt is older, and keeps a captured one when asked', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - try { - const spawner = vi - .fn() - .mockResolvedValueOnce(null) - .mockResolvedValueOnce({ PATH: '/repaired' }) - const options = { - shellOverride: '/bin/bash', - env: { HOME: '/host' }, - spawner, - refreshAfterMs: 10_000, - keepCaptured: true - } - await expect(captureLoginShellEnvironment(options)).resolves.toMatchObject({ - status: 'fallback' - }) - vi.advanceTimersByTime(9_999) - await captureLoginShellEnvironment(options) - expect(spawner).toHaveBeenCalledOnce() - vi.advanceTimersByTime(1) - await captureLoginShellEnvironment(options) - await vi.waitFor(async () => { - expect((await captureLoginShellEnvironment(options)).env).toEqual({ PATH: '/repaired' }) - }) - vi.advanceTimersByTime(60_000) - await captureLoginShellEnvironment(options) - expect(spawner).toHaveBeenCalledTimes(2) - } finally { - vi.useRealTimers() - } -}) - -it('answers a lookup from a finished capture that started after it, without another shell', async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - try { - const spawner = vi - .fn<(shell: string, env: NodeJS.ProcessEnv) => Promise>() - .mockResolvedValueOnce({ PATH: '/first' }) - .mockResolvedValueOnce({ PATH: '/second' }) - const options = { shellOverride: '/bin/bash', env: { HOME: '/host' }, spawner } - const before = Date.now() - vi.advanceTimersByTime(1) - await resolveLoginShellEnvironment(options) - vi.advanceTimersByTime(1) - await expect( - resolveLoginShellEnvironment({ ...options, startedAfter: before }) - ).resolves.toEqual({ PATH: '/first' }) - expect(spawner).toHaveBeenCalledTimes(1) - await expect( - resolveLoginShellEnvironment({ ...options, startedAfter: Date.now() }) - ).resolves.toEqual({ PATH: '/second' }) - expect(spawner).toHaveBeenCalledTimes(2) - } finally { - vi.useRealTimers() - } -}) diff --git a/src/main/startup/run-electron-vite-dev-web.test.ts b/src/main/startup/run-electron-vite-dev-web.test.ts deleted file mode 100644 index 0776e1a0fb2..00000000000 --- a/src/main/startup/run-electron-vite-dev-web.test.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { dirname, join, resolve } from 'node:path' -import { spawn, type ChildProcess } from 'node:child_process' -import { afterEach, describe, expect, it } from 'vitest' - -const processesToCleanUp = new Set() - -function sleep(ms: number): Promise { - return new Promise((resolvePromise) => { - setTimeout(resolvePromise, ms) - }) -} - -async function waitFor(predicate: () => boolean, timeoutMs = 5000): Promise { - const start = Date.now() - while (!predicate()) { - if (Date.now() - start > timeoutMs) { - throw new Error('Timed out waiting for condition') - } - await sleep(50) - } -} - -function processExists(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch (error) { - const code = error && typeof error === 'object' && 'code' in error ? error.code : null - if (code === 'ESRCH') { - return false - } - throw error - } -} - -function readPidFile(pidFile: string): number[] { - return readFileSync(pidFile, 'utf8') - .trim() - .split(/\s+/) - .map((pid) => Number.parseInt(pid, 10)) - .filter((pid) => Number.isFinite(pid)) -} - -function trackPidFile(pidFile: string): number[] { - const pids = readPidFile(pidFile) - for (const pid of pids) { - processesToCleanUp.add(pid) - } - return pids -} - -function waitForExit(child: ChildProcess, timeoutMs = 5000): Promise { - if (child.exitCode !== null || child.signalCode !== null) { - return Promise.resolve() - } - return new Promise((resolveExit, reject) => { - const timer = setTimeout(() => { - child.kill('SIGKILL') - reject(new Error('Timed out waiting for dev wrapper exit')) - }, timeoutMs) - child.once('exit', () => { - clearTimeout(timer) - resolveExit() - }) - }) -} - -async function stopWrapper(wrapper: ChildProcess): Promise { - if (wrapper.pid) { - processesToCleanUp.add(wrapper.pid) - } - if (wrapper.exitCode === null && wrapper.signalCode === null) { - wrapper.kill('SIGINT') - } - await waitForExit(wrapper) - if (wrapper.pid) { - processesToCleanUp.delete(wrapper.pid) - } -} - -async function stopWrapperAndTrackedPids(wrapper: ChildProcess, pids: number[]): Promise { - await stopWrapper(wrapper) - await waitFor(() => pids.every((pid) => !processExists(pid))) - for (const pid of pids) { - processesToCleanUp.delete(pid) - } -} - -function stashWebBuild(): () => void { - const outWebPath = resolve('out/web') - if (!existsSync(outWebPath)) { - return () => { - rmSync(outWebPath, { recursive: true, force: true }) - } - } - - // Stash beside output: Windows temp may be on another drive, where rename cannot move directories. - const tempDir = mkdtempSync(join(dirname(outWebPath), '.orca-dev-web-stash-')) - const stashedPath = join(tempDir, 'web') - renameSync(outWebPath, stashedPath) - return () => { - rmSync(outWebPath, { recursive: true, force: true }) - mkdirSync(resolve('out'), { recursive: true }) - renameSync(stashedPath, outWebPath) - rmSync(tempDir, { recursive: true, force: true }) - } -} - -describe('run-electron-vite-dev web client prepare', () => { - afterEach(async () => { - for (const pid of processesToCleanUp) { - try { - process.kill(pid, 'SIGTERM') - } catch (error) { - const code = error && typeof error === 'object' && 'code' in error ? error.code : null - if (code !== 'ESRCH') { - throw error - } - } - } - await sleep(100) - for (const pid of processesToCleanUp) { - try { - if (processExists(pid)) { - process.kill(pid, 'SIGKILL') - } - } catch (error) { - const code = error && typeof error === 'object' && 'code' in error ? error.code : null - if (code !== 'ESRCH') { - throw error - } - } - } - processesToCleanUp.clear() - }) - - it('skips the initial web client build when no bundle exists', async () => { - const restoreWebBuild = stashWebBuild() - const tempDir = mkdtempSync(join(tmpdir(), 'orca-dev-wrapper-')) - const pidFile = join(tempDir, 'grandchild.pid') - const envFile = join(tempDir, 'env.json') - const viteFile = join(tempDir, 'vite.txt') - const wrapperPath = resolve('config/scripts/development/launch/run-electron-vite-dev.mjs') - const fakeCliPath = resolve('src/main/startup/__fixtures__/fake-electron-vite-dev-cli.mjs') - const fakeVitePath = resolve('src/main/startup/__fixtures__/fake-vite-cli.mjs') - let stderr = '' - - try { - const wrapper = spawn(process.execPath, [wrapperPath, '--remote-debugging-port=9446'], { - cwd: resolve('.'), - env: { - ...process.env, - ORCA_ELECTRON_VITE_CLI: fakeCliPath, - ORCA_VITE_CLI: fakeVitePath, - ORCA_SKIP_DEV_CLI_PREPARE: '1', - ORCA_DEV_USER_DATA_PATH: join(tempDir, 'user-data'), - ORCA_SKIP_DEV_STORAGE_RECLAIM: '1', - ORCA_SKIP_DEV_ELECTRON_APP_PREPARE: '1', - ORCA_DEV_WRAPPER_TEST_PID_FILE: pidFile, - ORCA_DEV_WRAPPER_TEST_ENV_FILE: envFile, - ORCA_DEV_WRAPPER_TEST_VITE_FILE: viteFile - }, - stdio: ['ignore', 'ignore', 'pipe'] - }) - - expect(wrapper.pid).toBeTypeOf('number') - processesToCleanUp.add(wrapper.pid!) - wrapper.stderr.on('data', (chunk) => { - stderr += String(chunk) - }) - - await waitFor(() => { - try { - return readFileSync(envFile, 'utf8').trim().length > 0 - } catch { - return false - } - }) - - const trackedPids = trackPidFile(pidFile) - - expect(existsSync(viteFile)).toBe(false) - expect(stderr).toContain('Web client bundle missing; skipping pairing web build.') - - await stopWrapperAndTrackedPids(wrapper, trackedPids) - } finally { - restoreWebBuild() - } - }) - - it('builds the missing web client bundle when explicitly requested', async () => { - const restoreWebBuild = stashWebBuild() - const tempDir = mkdtempSync(join(tmpdir(), 'orca-dev-wrapper-')) - const pidFile = join(tempDir, 'grandchild.pid') - const envFile = join(tempDir, 'env.json') - const viteFile = join(tempDir, 'vite.txt') - const wrapperPath = resolve('config/scripts/development/launch/run-electron-vite-dev.mjs') - const fakeCliPath = resolve('src/main/startup/__fixtures__/fake-electron-vite-dev-cli.mjs') - const fakeVitePath = resolve('src/main/startup/__fixtures__/fake-vite-cli.mjs') - - try { - const wrapper = spawn(process.execPath, [wrapperPath, '--remote-debugging-port=9447'], { - cwd: resolve('.'), - env: { - ...process.env, - ORCA_ELECTRON_VITE_CLI: fakeCliPath, - ORCA_VITE_CLI: fakeVitePath, - ORCA_SKIP_DEV_CLI_PREPARE: '1', - ORCA_DEV_USER_DATA_PATH: join(tempDir, 'user-data'), - ORCA_SKIP_DEV_STORAGE_RECLAIM: '1', - ORCA_SKIP_DEV_ELECTRON_APP_PREPARE: '1', - ORCA_DEV_WEB_PREPARE: '1', - ORCA_DEV_WRAPPER_TEST_PID_FILE: pidFile, - ORCA_DEV_WRAPPER_TEST_ENV_FILE: envFile, - ORCA_DEV_WRAPPER_TEST_VITE_FILE: viteFile - }, - stdio: 'ignore' - }) - - expect(wrapper.pid).toBeTypeOf('number') - processesToCleanUp.add(wrapper.pid!) - - await waitFor(() => { - try { - return readFileSync(envFile, 'utf8').trim().length > 0 - } catch { - return false - } - }) - - // Track before the build wait: a timeout there would otherwise orphan the fake CLI tree. - const trackedPids = trackPidFile(pidFile) - - // The pairing build runs beside electron-vite instead of before it. - await waitFor(() => existsSync(viteFile), 20_000) - expect(readFileSync(viteFile, 'utf8')).toContain('build') - - await stopWrapperAndTrackedPids(wrapper, trackedPids) - } finally { - restoreWebBuild() - } - }) -}) diff --git a/src/main/text-generation/pull-request-context-errors.test.ts b/src/main/text-generation/pull-request-context-errors.test.ts deleted file mode 100644 index 74627bd569e..00000000000 --- a/src/main/text-generation/pull-request-context-errors.test.ts +++ /dev/null @@ -1,269 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { getPullRequestDraftContext } from './pull-request-context' - -type GitExec = Parameters[0] - -afterEach(() => { - vi.restoreAllMocks() -}) - -function createContextInput(base = 'main') { - return { - base, - currentTitle: 'Existing title', - currentBody: 'Existing body', - currentDraft: false - } -} - -describe('getPullRequestDraftContext error handling', () => { - it('does not run rebase before collecting PR context', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'fetch') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'remote') { - return { stdout: 'origin\n', stderr: '' } - } - if (args[0] === 'show-ref') { - return { stdout: '', stderr: '' } - } - if (args[0] === 'branch') { - return { stdout: 'feature\n', stderr: '' } - } - if (args[0] === 'rebase') { - throw new Error('Generate must not rebase the live worktree') - } - if (args[0] === 'merge-base') { - return { stdout: 'abc123\n', stderr: '' } - } - if (args[0] === 'log') { - return { stdout: '- feat: change\n', stderr: '' } - } - if (args[0] === 'diff') { - return { stdout: 'M\tREADME.md\n', stderr: '' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).resolves.toMatchObject({ - branch: 'feature' - }) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['rebase']), expect.anything()) - }) - - it('stops generation when the relevant base fetch fails', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'origin\nstale-fork\n', stderr: '' } - } - if (args[0] === 'show-ref') { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'fetch') { - if (args[2] !== 'origin') { - throw new Error(`Fetched unrelated remote: ${args.join(' ')}`) - } - throw new Error( - 'Command failed: git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main\nfatal: unable to access origin' - ) - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).rejects.toThrow( - 'Fetch before generating PR details failed: fatal: unable to access origin' - ) - }) - - it('handles newline-heavy remote state and fetch errors without line-array splitting', async () => { - const splitSpy = vi.spyOn(String.prototype, 'split') - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: `${'\r\n'.repeat(10_000)}origin\r\n`, stderr: '' } - } - if (args[0] === 'show-ref') { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'fetch') { - throw new Error( - `Command failed: git fetch\r\n${'remote: progress\r\n'.repeat(10_000)}fatal: unable to access origin\r\n` - ) - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).rejects.toThrow( - 'Fetch before generating PR details failed: fatal: unable to access origin' - ) - - const usedLineSplit = splitSpy.mock.calls.some( - ([separator]) => - (typeof separator === 'string' && separator === '\n') || - (separator instanceof RegExp && separator.source === '\\r?\\n') - ) - expect(usedLineSplit).toBe(false) - }) - - it('returns null without running git when the base is invalid', async () => { - const execGit = vi.fn() - - await expect(getPullRequestDraftContext(execGit, createContextInput('--main'))).resolves.toBe( - null - ) - expect(execGit).not.toHaveBeenCalled() - }) - - it.each(['origin/feature*', 'origin/feature?', 'origin/feature:other', 'origin/feature\u0000'])( - 'does not turn unsafe characters in a qualified base into a fetch refspec (%s)', - async (base) => { - const execGit = vi.fn() - - await expect(getPullRequestDraftContext(execGit, createContextInput(base))).resolves.toBe( - null - ) - expect(execGit).not.toHaveBeenCalled() - } - ) - - it('ignores stale tracking refs whose remote name could be parsed as a fetch option', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: '--upload-pack=x\n' } - } - if (args[0] === 'for-each-ref') { - return { stdout: '' } - } - if (args[0] === 'show-ref' && args.includes('--verify')) { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'show-ref') { - return { stdout: 'abc refs/remotes/--upload-pack=x/main\n' } - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('main') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect(getPullRequestDraftContext(execGit, createContextInput())).resolves.toMatchObject({ - branch: 'feature' - }) - expect(execGit).not.toHaveBeenCalledWith(expect.arrayContaining(['fetch']), expect.any(Object)) - }) - - it('preserves the existing bare HEAD remote-base behavior', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'origin\n' } - } - if (args[0] === 'for-each-ref') { - return { stdout: '' } - } - if (args[0] === 'show-ref') { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'fetch') { - return { stdout: '' } - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('origin/HEAD') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect( - getPullRequestDraftContext(execGit, createContextInput('HEAD')) - ).resolves.toMatchObject({ base: 'HEAD', branch: 'feature' }) - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/HEAD:refs/remotes/origin/HEAD'], - expect.any(Object) - ) - }) - - it('does not resolve bare HEAD to a nested branch ending in HEAD', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'fork\n' } - } - if (args[0] === 'for-each-ref') { - return { stdout: '' } - } - if (args[0] === 'show-ref' && args.some((arg) => arg.startsWith('refs/remotes/'))) { - throw Object.assign(new Error('missing exact ref'), { code: 1 }) - } - if (args[0] === 'show-ref') { - expect(args).toEqual(['show-ref', '--', 'HEAD']) - return { stdout: 'abc123 refs/remotes/fork/feature/HEAD\n' } - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('HEAD') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect( - getPullRequestDraftContext(execGit, createContextInput('HEAD')) - ).resolves.toMatchObject({ base: 'HEAD', branch: 'feature' }) - expect(execGit).not.toHaveBeenCalledWith( - ['fetch', '--no-tags', 'fork', '+refs/heads/feature/HEAD:refs/remotes/fork/feature/HEAD'], - expect.any(Object) - ) - }) - - it('preserves an explicitly qualified remote HEAD ref', async () => { - const execGit = vi.fn(async (args) => { - if (args[0] === 'remote') { - return { stdout: 'origin\n' } - } - if (args[0] === 'show-ref') { - return args.at(-1) === 'refs/remotes/origin/HEAD' - ? { stdout: '' } - : Promise.reject(Object.assign(new Error('missing exact ref'), { code: 1 })) - } - if (args[0] === 'fetch') { - return { stdout: '' } - } - if (args[0] === 'branch') { - return { stdout: 'feature\n' } - } - if (args[0] === 'merge-base') { - expect(args[1]).toBe('origin/HEAD') - return { stdout: 'abc123\n' } - } - if (args[0] === 'log' || args[0] === 'diff') { - return { stdout: 'change\n' } - } - throw new Error(`Unexpected git args: ${args.join(' ')}`) - }) - - await expect( - getPullRequestDraftContext(execGit, createContextInput('origin/HEAD')) - ).resolves.toMatchObject({ base: 'origin/HEAD', branch: 'feature' }) - expect(execGit).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', '+refs/heads/HEAD:refs/remotes/origin/HEAD'], - expect.any(Object) - ) - }) -}) diff --git a/src/main/text-generation/source-control-agent-launch.test.ts b/src/main/text-generation/source-control-agent-launch.test.ts index 10e38c6fe7c..e2c85810c3f 100644 --- a/src/main/text-generation/source-control-agent-launch.test.ts +++ b/src/main/text-generation/source-control-agent-launch.test.ts @@ -1,14 +1,14 @@ -import { EventEmitter } from 'node:events' +import 'node:events' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' import type * as RunProcess from '@orca/process-host' import type { ProcessSpec } from '@orca/process-host/process-spec' -import { POSIX_PROVIDER_SUPERVISOR_SCRIPT } from '../provider-process/provider-process-supervisor' +import '../provider-process/provider-process-supervisor' import { generateCommitMessageFromContext } from './commit-message-text-generation' -import { withPlatform } from './commit-message-text-generation-test-harness' -import { spawnSourceControlAgent } from './source-control-agent-launch' +import './commit-message-text-generation-test-harness' +import './source-control-agent-launch' const { spawnProcessMock } = vi.hoisted(() => ({ spawnProcessMock: vi.fn() })) @@ -18,14 +18,6 @@ vi.mock('@orca/process-host', async (importOriginal) => { return { ...actual, spawnProcess: spawnProcessMock } }) -function fakeChild(): EventEmitter & { - stdin: { on: () => void; end: () => void } -} { - return Object.assign(new EventEmitter(), { - stdin: { on: vi.fn(), end: vi.fn() } - }) -} - function lastSpawnSpec(): ProcessSpec { return spawnProcessMock.mock.calls.at(-1)![0] } @@ -41,176 +33,7 @@ beforeEach(() => { spawnProcessMock.mockClear() }) -describe('spawnSourceControlAgent', () => { - it.each([ - ['in its own cwd', true, '/work/repo'], - ['in the process cwd', false, process.cwd()] - ])('runs a POSIX agent one-shot under the provider supervisor %s', (_, useCwd, cwd) => { - spawnProcessMock.mockReturnValueOnce(fakeChild()) - const child = withPlatform('linux', () => - spawnSourceControlAgent({ - binary: '/opt/agent/claude', - args: ['-p', '--verbose'], - cwd: '/work/repo', - env: { PATH: '/usr/bin', AGENT_TOKEN: 'kept' }, - stdinMode: 'pipe', - useCwdForNative: useCwd - }) - ) - - const spec = lastSpawnSpec() - expect(child.supervised).toBe(true) - expect(spec).toMatchObject({ - program: process.execPath, - args: ['-e', POSIX_PROVIDER_SUPERVISOR_SCRIPT, '--', '/opt/agent/claude', '-p', '--verbose'], - cwd, - detached: true, - stdio: ['pipe', 'pipe', 'pipe', 'ipc'] - }) - expect(spec.env).toMatchObject({ PATH: '/usr/bin', AGENT_TOKEN: 'kept' }) - expect(decodedSupervisorSpec(spec)).toMatchObject({ - cwd, - lifetime: 'one-shot' - }) - }) - - it('spawns a Windows agent directly, without a supervisor', () => { - spawnProcessMock.mockReturnValueOnce(fakeChild()) - const child = withPlatform('win32', () => - spawnSourceControlAgent({ - binary: 'C:/tools/agent.exe', - args: ['--print'], - env: { PATH: 'C:/tools' }, - stdinMode: 'pipe', - useCwdForNative: false - }) - ) - - expect(child.supervised).toBeUndefined() - expect(lastSpawnSpec()).toMatchObject({ - program: 'C:/tools/agent.exe', - args: ['--print'] - }) - expect(lastSpawnSpec().env).not.toHaveProperty('ORCA_PROVIDER_SUPERVISOR_SPEC') - }) - - it('hands an npm .cmd shim to process-host unwrapped, multi-line prompt included', () => { - // #28768: cmd.exe wrapping rejects multiline prompts before process-host can resolve npm shims to node + script. - const shim = join(folder, 'copilot.cmd') - writeFileSync(shim, '') - spawnProcessMock.mockReturnValueOnce(fakeChild()) - withPlatform('win32', () => - spawnSourceControlAgent({ - binary: 'copilot', - args: ['--prompt', 'Summarize:\n- staged change'], - env: { PATH: folder }, - stdinMode: 'pipe', - useCwdForNative: false - }) - ) - - expect(lastSpawnSpec()).toMatchObject({ - program: shim, - args: ['--prompt', 'Summarize:\n- staged change'] - }) - }) -}) - describe.runIf(process.platform !== 'win32')('supervised agent processes', () => { - it('reports a missing agent binary as not found, as a direct spawn does', async () => { - const missing = join(folder, 'missing-agent') - - await expect( - generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M README.md', - stagedPatch: '+test' - }, - { agentId: 'custom', model: '', customAgentCommand: `"${missing}"` }, - { kind: 'local', cwd: folder } - ) - ).resolves.toMatchObject({ - success: false, - error: `${missing} not found on PATH. Install ${missing} to use AI commit messages.` - }) - }) - - it('reports an agent that cannot be executed as failing to start, as a direct spawn does', async () => { - const agent = join(folder, 'not-executable-agent') - writeFileSync(agent, '#!/bin/sh\necho never\n', { mode: 0o644 }) - - await expect( - generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M README.md', - stagedPatch: '+test' - }, - { agentId: 'custom', model: '', customAgentCommand: `"${agent}"` }, - { kind: 'local', cwd: folder } - ) - ).resolves.toMatchObject({ - success: false, - error: `${agent} failed to start. Check the agent command in Settings and try again.` - }) - }) - - it.each([ - // Only macOS returns ENOEXEC here; glibc execvp hands executable text to /bin/sh. - ...(process.platform === 'darwin' - ? [['an executable that is not a program', 'garbage', (path: string) => path] as const] - : []), - ['a path through a file', 'file', (path: string) => join(path, 'agent')] as const - ])('reports %s as not startable, as a direct spawn does', async (_, name, commandFor) => { - const file = join(folder, name) - writeFileSync(file, Buffer.from([0, 1, 2, 3]), { mode: 0o755 }) - const command = commandFor(file) - - await expect( - generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M README.md', - stagedPatch: '+test' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: `"${command}"` - }, - { kind: 'local', cwd: folder } - ) - ).resolves.toMatchObject({ - success: false, - error: `${command} could not be started. Check the agent command in Settings and try again.` - }) - }) - - // Model Electron startup warnings before supervised missing-binary diagnostics. - it('reads a missing binary as not found past the runtime own stderr output', async () => { - const missing = join(folder, 'missing-behind-warning') - - await expect( - generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M README.md', - stagedPatch: '+test' - }, - { agentId: 'custom', model: '', customAgentCommand: `"${missing}"` }, - { - kind: 'local', - cwd: folder, - env: { ...process.env, NODE_DEBUG: 'child_process' } - } - ) - ).resolves.toMatchObject({ - success: false, - error: `${missing} not found on PATH. Install ${missing} to use AI commit messages.` - }) - }) - it('passes the stdin end through so the agent can answer its request', async () => { const agent = join(folder, 'echo-agent.cjs') writeFileSync( diff --git a/src/main/updater/linux-package/appimage-runtime-identity.test.ts b/src/main/updater/linux-package/appimage-runtime-identity.test.ts index 842a6a574ca..c7d71539a54 100644 --- a/src/main/updater/linux-package/appimage-runtime-identity.test.ts +++ b/src/main/updater/linux-package/appimage-runtime-identity.test.ts @@ -1,15 +1,5 @@ import type * as fs from 'node:fs' -import { - chmodSync, - closeSync, - mkdirSync, - mkdtempSync, - openSync, - renameSync, - rmSync, - symlinkSync, - writeFileSync -} from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -90,121 +80,6 @@ describe.skipIf(process.platform === 'win32')('resolveAppImageRuntimeIdentity', }) }) - it('keeps a verified identity when closing the AppImage header reports EIO', () => { - const fixture = createFixture() - vi.mocked(closeSync).mockImplementationOnce((fd) => { - realFs.closeSync(fd) - throw Object.assign(new Error('close failed'), { code: 'EIO' }) - }) - - expect(resolveAppImageRuntimeIdentity(fixture.identity)).toEqual({ - appImagePath: fixture.appImagePath - }) - expect(vi.mocked(openSync).mock.calls[0]?.[0]).toBe(fixture.appImagePath) - expect(vi.mocked(closeSync).mock.calls[0]).toEqual([vi.mocked(openSync).mock.results[0]?.value]) - expect(closeSync).toHaveBeenCalledTimes(vi.mocked(openSync).mock.calls.length) - }) - - it('accepts an AppImage moved independently of its runtime directory', () => { - const fixture = createFixture() - const movedPath = join(fixture.root, 'Moved Apps', 'Orca current.AppImage') - mkdirSync(dirname(movedPath), { recursive: true }) - renameSync(fixture.appImagePath, movedPath) - fixture.identity.environment.APPIMAGE = movedPath - expect(resolveAppImageRuntimeIdentity(fixture.identity)?.appImagePath).toBe(movedPath) - }) - - it('accepts the exact AppImage package-type marker', () => { - const fixture = createFixture() - rmSync(fixture.packageMarkerPath) - writeFileSync(fixture.packageTypePath, 'AppImage') - expect(resolveAppImageRuntimeIdentity(fixture.identity)).not.toBeNull() - }) - - it.each([ - ['APPIMAGE', undefined], - ['APPIMAGE', 'relative/Orca.AppImage'], - ['APPDIR', undefined], - ['APPDIR', 'relative/mount'], - ['APPIMAGE', '/tmp/Orca\0.AppImage'] - ] as const)('rejects an unusable %s value', (key, value) => { - const fixture = createFixture() - expect( - resolveAppImageRuntimeIdentity({ - ...fixture.identity, - environment: { ...fixture.identity.environment, [key]: value } - }) - ).toBeNull() - }) - - it.each([ - ['an ordinary executable', (path: string) => writeFileSync(path, '#!/bin/sh\n')], - [ - 'bad ELF magic', - (path: string) => { - const header = appImageHeader(0x3e) - header[0] = 0 - writeFileSync(path, header) - } - ], - [ - 'bad AppImage type magic', - (path: string) => { - const header = appImageHeader(0x3e) - header[10] = 1 - writeFileSync(path, header) - } - ], - ['a non-executable file', (path: string) => chmodSync(path, 0o644)], - [ - 'a directory', - (path: string) => { - rmSync(path) - mkdirSync(path) - } - ] - ])('rejects APPIMAGE pointing to %s', (_case, mutate) => { - const fixture = createFixture() - mutate(fixture.appImagePath) - expect(resolveAppImageRuntimeIdentity(fixture.identity)).toBeNull() - }) - - it.each([ - [ - 'AppRun', - (fixture: ReturnType) => rmSync(join(fixture.appDirPath, 'AppRun')) - ], - [ - 'an executable AppRun', - (fixture: ReturnType) => - chmodSync(join(fixture.appDirPath, 'AppRun'), 0o644) - ], - [ - 'the Orca package marker', - (fixture: ReturnType) => rmSync(fixture.packageMarkerPath) - ] - ])('rejects a runtime missing %s', (_case, mutate) => { - const fixture = createFixture() - mutate(fixture) - expect(resolveAppImageRuntimeIdentity(fixture.identity)).toBeNull() - }) - - it('rejects a package marker for a different application', () => { - const fixture = createFixture() - writeFileSync( - fixture.packageMarkerPath, - JSON.stringify({ name: 'foreign-compiled-output', type: 'commonjs' }) - ) - expect(resolveAppImageRuntimeIdentity(fixture.identity)).toBeNull() - }) - - it('rejects an inexact package-type marker without the Orca fallback', () => { - const fixture = createFixture() - rmSync(fixture.packageMarkerPath) - writeFileSync(fixture.packageTypePath, 'appimage') - expect(resolveAppImageRuntimeIdentity(fixture.identity)).toBeNull() - }) - it('rejects payload evidence that resolves outside APPDIR', () => { const fixture = createFixture() const externalAppRun = join(fixture.root, 'foreign-AppRun') @@ -225,30 +100,4 @@ describe.skipIf(process.platform === 'win32')('resolveAppImageRuntimeIdentity', symlinkSync(externalMarker, fixture.packageMarkerPath) expect(resolveAppImageRuntimeIdentity(fixture.identity)).toBeNull() }) - - it('rejects inherited AppImage variables around a non-AppImage executable', () => { - const fixture = createFixture() - expect( - resolveAppImageRuntimeIdentity({ - ...fixture.identity, - execPath: join(fixture.root, 'opt', 'Orca', 'orca-ide'), - resourcesPath: join(fixture.root, 'opt', 'Orca', 'resources') - }) - ).toBeNull() - }) - - it('rejects a resources path outside the runtime root', () => { - const fixture = createFixture() - expect( - resolveAppImageRuntimeIdentity({ - ...fixture.identity, - resourcesPath: `${fixture.appDirPath}-other/resources` - }) - ).toBeNull() - }) - - it('rejects the identity off Linux', () => { - const fixture = createFixture() - expect(resolveAppImageRuntimeIdentity({ ...fixture.identity, platform: 'darwin' })).toBeNull() - }) }) diff --git a/src/main/updater/updater.startup-scheduling.test.ts b/src/main/updater/updater.startup-scheduling.test.ts deleted file mode 100644 index 2e31163ea14..00000000000 --- a/src/main/updater/updater.startup-scheduling.test.ts +++ /dev/null @@ -1,218 +0,0 @@ -import type { getReleaseDownloadUrl } from './releases/updater-release-readiness' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { loadUpdaterModule, warmUpdaterModule } from './testing/updater-test-module-loader' -import { updaterMainWindow } from './testing/updater-test-main-window' - -const { appMock, autoUpdaterMock, powerMonitorOnMock, 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()) - -warmUpdaterModule() - -describe('updater', () => { - beforeEach(() => { - resetUpdaterMocks() - vi.useFakeTimers() - }) - - it('does not load or configure electron-updater during dev setup', async () => { - appMock.isPackaged = false - const mainWindow = updaterMainWindow(vi.fn()) - - const { setupAutoUpdater } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow) - - expect(autoUpdaterMock.updateConfigPath).toBeUndefined() - expect(autoUpdaterMock.setFeedURL).not.toHaveBeenCalled() - expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled() - expect(powerMonitorOnMock).not.toHaveBeenCalled() - }) - - it('waits until the remaining interval before the next background check', async () => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-04-03T12:00:00Z')) - - const mainWindow = updaterMainWindow(vi.fn()) - const setLastUpdateCheckAt = vi.fn() - - const { setupAutoUpdater } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow, { - getLastUpdateCheckAt: () => Date.now() - 23 * 60 * 60 * 1000, - setLastUpdateCheckAt - }) - - expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(59 * 60 * 1000) - expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(60 * 1000) - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - }) - expect(setLastUpdateCheckAt).not.toHaveBeenCalled() - }) - - it('deduplicates rapid focus-triggered daily checks before checking status arrives', async () => { - let lastUpdateCheckAt = Date.now() - const mainWindow = updaterMainWindow(vi.fn()) - - autoUpdaterMock.checkForUpdates.mockImplementation(() => new Promise(() => {})) - - const { setupAutoUpdater } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow, { - getLastUpdateCheckAt: () => lastUpdateCheckAt - }) - - lastUpdateCheckAt = Date.now() - 25 * 60 * 60 * 1000 - appMock.emit('browser-window-focus') - appMock.emit('browser-window-focus') - - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - }) - }) - - it('does not persist lastUpdateCheckAt when a focus-triggered check fails benignly', async () => { - let lastUpdateCheckAt = Date.now() - const setLastUpdateCheckAt = vi.fn() - const sendMock = vi.fn() - const mainWindow = updaterMainWindow(sendMock) - - autoUpdaterMock.checkForUpdates.mockImplementation(() => { - autoUpdaterMock.emit('checking-for-update') - queueMicrotask(() => { - autoUpdaterMock.emit('error', new Error('net::ERR_FAILED')) - }) - return Promise.reject(new Error('net::ERR_FAILED')) - }) - - const { setupAutoUpdater } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow, { - getLastUpdateCheckAt: () => lastUpdateCheckAt, - setLastUpdateCheckAt - }) - - lastUpdateCheckAt = Date.now() - 25 * 60 * 60 * 1000 - appMock.emit('browser-window-focus') - - await vi.waitFor(() => { - const statuses = sendMock.mock.calls - .filter(([channel]) => channel === 'updater:status') - .map(([, status]) => status) - expect(statuses).toContainEqual({ state: 'idle' }) - }) - - expect(setLastUpdateCheckAt).not.toHaveBeenCalled() - }) - - it('retries background checks sooner after a failed automatic check', async () => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-04-03T12:00:00Z')) - - autoUpdaterMock.checkForUpdates.mockImplementation(() => { - autoUpdaterMock.emit('checking-for-update') - queueMicrotask(() => { - autoUpdaterMock.emit('error', new Error('boom')) - }) - return Promise.reject(new Error('boom')) - }) - - const sendMock = vi.fn() - const mainWindow = updaterMainWindow(sendMock) - - const { setupAutoUpdater } = await loadUpdaterModule() - - setupAutoUpdater(mainWindow, { - getLastUpdateCheckAt: () => null, - setLastUpdateCheckAt: vi.fn() - }) - - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - }) - - await vi.advanceTimersByTimeAsync(59 * 60 * 1000) - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - - await vi.advanceTimersByTimeAsync(60 * 1000) - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2) - }) - }) - - it('reschedules the next automatic check 24 hours after finding an available update', async () => { - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-04-03T12:00:00Z')) - - autoUpdaterMock.checkForUpdates.mockImplementation(() => { - autoUpdaterMock.emit('checking-for-update') - queueMicrotask(() => { - autoUpdaterMock.emit('update-available', { version: '1.0.61' }) - }) - return Promise.resolve(undefined) - }) - - const sendMock = vi.fn() - const setLastUpdateCheckAt = vi.fn() - const mainWindow = updaterMainWindow(sendMock) - - const { setupAutoUpdater } = await loadUpdaterModule() - - // Start 23h in to distinguish the result handler's re-arm from the initial startup timer. - setupAutoUpdater(mainWindow, { - getLastUpdateCheckAt: () => Date.now() - 23 * 60 * 60 * 1000, - setLastUpdateCheckAt - }) - - expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(60 * 60 * 1000) - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - }) - await vi.advanceTimersByTimeAsync(0) - - expect(setLastUpdateCheckAt).toHaveBeenCalledTimes(1) - expect(sendMock).toHaveBeenCalledWith('updater:status', { - state: 'available', - version: '1.0.61', - changelog: null - }) - - await vi.advanceTimersByTimeAsync(23 * 60 * 60 * 1000) - expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) - - await vi.advanceTimersByTimeAsync(60 * 60 * 1000) - // Other timers fire at this boundary too; assert the schedule rather than an exact global call count. - await vi.waitFor(() => { - expect(autoUpdaterMock.checkForUpdates.mock.calls.length).toBeGreaterThanOrEqual(2) - }) - }) -}) diff --git a/src/main/usage/usage-scan-worker-client.test.ts b/src/main/usage/usage-scan-worker-client.test.ts deleted file mode 100644 index 7e83a7db182..00000000000 --- a/src/main/usage/usage-scan-worker-client.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - MAX_CONSECUTIVE_DEATHS, - USAGE_SCAN_NO_PROGRESS_TIMEOUT_MS, - UsageScanWorkerClient, - scanCodexUsageOnWorker -} from './usage-scan-worker-client' -import type { UsageScanWorkerRequest, UsageScanWorkerScanBody } from './usage-scan-worker-protocol' -import type { UsageSourceCacheRef } from './usage-source-cache-file' - -// Drive transport lifecycle without a built worker bundle. -class FakeWorker { - postedRequests: UsageScanWorkerRequest[] = [] - private listeners = new Map void>>() - - on(event: string, listener: (arg?: unknown) => void): this { - const set = this.listeners.get(event) ?? new Set() - set.add(listener) - this.listeners.set(event, set) - return this - } - - off(event: string, listener: (arg?: unknown) => void): this { - this.listeners.get(event)?.delete(listener) - return this - } - - removeAllListeners(): void { - this.listeners.clear() - } - - unref(): void {} - - async terminate(): Promise { - return 1 - } - - postMessage(request: UsageScanWorkerRequest): void { - this.postedRequests.push(request) - } - - emit(event: string, arg?: unknown): void { - // Copy first: the client removes its listeners synchronously during a fault. - for (const listener of Array.from(this.listeners.get(event) ?? [])) { - listener(arg) - } - } - - lastId(): number { - return this.postedRequests.at(-1)?.id ?? -1 - } -} - -function createClient(factory: () => FakeWorker): UsageScanWorkerClient { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: FakeWorker implements the transport lifecycle; absent threadId skips optional owner cleanup. - return new UsageScanWorkerClient({ workerFactory: factory as never, log: () => {} }) -} - -const SOURCE_CACHE: UsageSourceCacheRef = { - path: '/tmp/orca-codex-usage-sources.json', - schemaVersion: 6, - worktreeFingerprint: '[]', - reuse: true -} - -const CODEX_BODY: UsageScanWorkerScanBody = { - operation: 'scan', - providerId: 'codex', - worktrees: [], - sourceCache: SOURCE_CACHE -} - -const CODEX_VALUE = { - operation: 'scan', - providerId: 'codex', - sessions: [{ sessionId: 'session-1' }], - dailyAggregates: [] -} - -describe('UsageScanWorkerClient', () => { - it('routes a scan to the worker and hands back that provider’s projection', async () => { - const worker = new FakeWorker() - const client = createClient(() => worker) - - const pending = scanCodexUsageOnWorker((body) => client.scan(body), [], SOURCE_CACHE) - await vi.waitFor(() => expect(worker.postedRequests).toHaveLength(1)) - expect(worker.postedRequests[0]).toMatchObject({ - operation: 'scan', - providerId: 'codex', - sourceCache: SOURCE_CACHE - }) - worker.emit('message', { id: worker.lastId(), ok: true, value: CODEX_VALUE }) - - await expect(pending).resolves.toEqual({ - sessions: [{ sessionId: 'session-1' }], - dailyAggregates: [] - }) - }) - - it('routes a cache split to the worker and hands back the report text', async () => { - const worker = new FakeWorker() - const client = createClient(() => worker) - - const pending = client.splitCacheFile({ - cacheFile: '/tmp/usage.json', - sourceKey: 'processedFiles' - }) - await vi.waitFor(() => expect(worker.postedRequests).toHaveLength(1)) - expect(worker.postedRequests[0]).toMatchObject({ - operation: 'splitCacheFile', - cacheFile: '/tmp/usage.json', - sourceKey: 'processedFiles' - }) - worker.emit('message', { - id: worker.lastId(), - ok: true, - value: { operation: 'splitCacheFile', reportText: '{}', migrated: true } - }) - - await expect(pending).resolves.toEqual({ reportText: '{}', migrated: true }) - }) - - it('keeps worker verification attached to the exact returned report text', async () => { - const worker = new FakeWorker() - const client = createClient(() => worker) - const pending = client.splitCacheFile({ - cacheFile: '/tmp/usage.json', - sourceKey: 'processedFiles', - providerId: 'claude' - }) - await vi.waitFor(() => expect(worker.postedRequests).toHaveLength(1)) - const reportText = '{"usageIntegrity":"verified-by-worker","schemaVersion":7}' - worker.emit('message', { - id: worker.lastId(), - ok: true, - value: { - operation: 'splitCacheFile', - reportText, - migrated: false, - reportIntegrityVerified: true - } - }) - - await expect(pending).resolves.toEqual({ - reportText, - migrated: false, - reportIntegrityVerified: true - }) - }) - - it('fails closed instead of scanning on the calling thread when spawn fails', async () => { - const client = createClient(() => { - throw new Error('no thread available') - }) - - // Stores turn rejection into lastScanError and keep the previous projection. - await expect(client.scan(CODEX_BODY)).rejects.toThrow(/spawn failed/) - }) - - it('rejects a scan whose worker goes silent', async () => { - vi.useFakeTimers() - try { - const client = createClient(() => new FakeWorker()) - const pending = client.scan(CODEX_BODY) - const assertion = expect(pending).rejects.toThrow(/no progress/) - await vi.advanceTimersByTimeAsync(USAGE_SCAN_NO_PROGRESS_TIMEOUT_MS + 1) - await assertion - } finally { - vi.useRealTimers() - } - }) - - it('keeps waiting on a scan that is slow but still reporting progress', async () => { - vi.useFakeTimers() - try { - const worker = new FakeWorker() - const client = createClient(() => worker) - const pending = client.scan(CODEX_BODY) - // Posted synchronously by dispatch; vi.waitFor would advance the fake clock. - expect(worker.postedRequests).toHaveLength(1) - - // Progress just before each deadline keeps the scan alive across four wall-clock windows. - for (let window = 1; window <= 4; window++) { - await vi.advanceTimersByTimeAsync(USAGE_SCAN_NO_PROGRESS_TIMEOUT_MS - 1) - worker.emit('message', { id: worker.lastId(), filesScanned: window * 100 }) - } - await vi.advanceTimersByTimeAsync(USAGE_SCAN_NO_PROGRESS_TIMEOUT_MS - 1) - worker.emit('message', { id: worker.lastId(), ok: true, value: CODEX_VALUE }) - - await expect(pending).resolves.toMatchObject({ sessions: [{ sessionId: 'session-1' }] }) - } finally { - vi.useRealTimers() - } - }) - - it('still kills a worker that stops reporting progress mid-scan', async () => { - vi.useFakeTimers() - try { - const worker = new FakeWorker() - const client = createClient(() => worker) - const pending = client.scan(CODEX_BODY) - expect(worker.postedRequests).toHaveLength(1) - const assertion = expect(pending).rejects.toThrow(/no progress/) - - await vi.advanceTimersByTimeAsync(USAGE_SCAN_NO_PROGRESS_TIMEOUT_MS - 1) - worker.emit('message', { id: worker.lastId(), filesScanned: 100 }) - await vi.advanceTimersByTimeAsync(USAGE_SCAN_NO_PROGRESS_TIMEOUT_MS + 1) - - await assertion - } finally { - vi.useRealTimers() - } - }) - - it('surfaces a worker-side scan failure as an error rather than an empty result', async () => { - const worker = new FakeWorker() - const client = createClient(() => worker) - - const pending = client.scan(CODEX_BODY) - await vi.waitFor(() => expect(worker.postedRequests).toHaveLength(1)) - worker.emit('message', { id: worker.lastId(), ok: false, error: 'history unreadable' }) - - await expect(pending).rejects.toThrow('history unreadable') - }) - - it('stops respawning after the consecutive-death cap', async () => { - const workers: FakeWorker[] = [] - const client = createClient(() => { - const worker = new FakeWorker() - workers.push(worker) - return worker - }) - - // One call beyond the death cap must drain instead of spawning another worker. - const pending = Array.from({ length: MAX_CONSECUTIVE_DEATHS + 1 }, () => - client.scan(CODEX_BODY) - ) - const settled = Promise.allSettled(pending) - for (let attempt = 0; attempt < MAX_CONSECUTIVE_DEATHS; attempt++) { - await vi.waitFor(() => expect(workers).toHaveLength(attempt + 1)) - workers[attempt]?.emit('error', new Error(`crash ${attempt}`)) - } - - const results = await settled - expect(results.every((result) => result.status === 'rejected')).toBe(true) - expect(workers.length).toBeLessThanOrEqual(MAX_CONSECUTIVE_DEATHS) - }) - - it('rejects a response that answers for a different provider', async () => { - const worker = new FakeWorker() - const client = createClient(() => worker) - - const pending = scanCodexUsageOnWorker((body) => client.scan(body), [], SOURCE_CACHE) - await vi.waitFor(() => expect(worker.postedRequests).toHaveLength(1)) - worker.emit('message', { - id: worker.lastId(), - ok: true, - value: { operation: 'scan', providerId: 'claude', sessions: [], dailyAggregates: [] } - }) - - await expect(pending).rejects.toThrow(/answered for claude/) - }) -}) diff --git a/src/main/window/clipboard-macos-image-paste.test.ts b/src/main/window/clipboard-macos-image-paste.test.ts index becd04db20a..66c5f3b103a 100644 --- a/src/main/window/clipboard-macos-image-paste.test.ts +++ b/src/main/window/clipboard-macos-image-paste.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as FsPromises from 'node:fs/promises' import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { CLIPBOARD_IMAGE_MAX_SOURCE_BYTES } from '../../shared/clipboard-image' +import '../../shared/clipboard-image' const mocks = vi.hoisted(() => ({ handlers: new Map unknown>(), @@ -100,74 +100,6 @@ afterEach(() => { }) describe('macOS clipboard image data beside a file URL', () => { - it.each(['public.png', 'public.tiff'])( - 'saves native %s image data as a local PNG', - async (type) => { - mocks.has.mockImplementation((format: string) => format === type) - expect(invoke('clipboard:hasImage')).toBe(true) - expect(mocks.readImage).not.toHaveBeenCalled() - - const savedPath = await invoke('clipboard:saveImageAsTempFile') - expect(savedPath).toMatch(/orca-paste-.+\.png$/) - expect(mocks.writeFile).toHaveBeenCalledWith(savedPath, PNG) - expect(mocks.readBuffer).not.toHaveBeenCalled() - } - ) - - it('does not decode or save a copied file without native image data', async () => { - mocks.has.mockReturnValue(false) - expect(invoke('clipboard:hasImage')).toBe(false) - await expect(invoke('clipboard:saveImageAsTempFile')).resolves.toBeNull() - expect(mocks.readImage).not.toHaveBeenCalled() - expect(mocks.writeFile).not.toHaveBeenCalled() - }) - - it('does not save malformed native image data or read its accompanying file', async () => { - setImage({ width: 0, height: 0 }, true) - mocks.readBuffer.mockReturnValue(Buffer.from('malformed image')) - await expect(invoke('clipboard:saveImageAsTempFile')).resolves.toBeNull() - expect(invoke('clipboard:readImageThumbnail')).toBeNull() - expect(mocks.toPNG).not.toHaveBeenCalled() - expect(mocks.writeFile).not.toHaveBeenCalled() - }) - - it('saves and previews JPEG bytes stored under the native PNG type', async () => { - const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0]) - setImage({ width: 0, height: 0 }, true) - mocks.readBuffer.mockImplementation((type: string) => - type === 'public.png' ? jpeg : Buffer.alloc(0) - ) - mocks.createFromBuffer.mockReturnValue({ - isEmpty: () => false, - getSize: () => ({ width: 32, height: 24 }), - toPNG: mocks.toPNG, - toDataURL: () => 'data:image/png;base64,PREVIEW' - }) - - expect(invoke('clipboard:hasImage')).toBe(true) - const savedPath = await invoke('clipboard:saveImageAsTempFile') - expect(savedPath).toMatch(/orca-paste-.+\.png$/) - expect(mocks.writeFile).toHaveBeenCalledWith(savedPath, PNG) - expect(invoke('clipboard:readImageThumbnail')).toEqual({ - dataUrl: 'data:image/png;base64,PREVIEW', - width: 32, - height: 24 - }) - expect(mocks.createFromBuffer).toHaveBeenCalledWith(jpeg) - }) - - it('rejects oversized raw image bytes before decoding and omits their preview', async () => { - setImage({ width: 0, height: 0 }, true) - mocks.readBuffer.mockReturnValue(Buffer.alloc(CLIPBOARD_IMAGE_MAX_SOURCE_BYTES + 1)) - - await expect(invoke('clipboard:saveImageAsTempFile')).rejects.toThrow( - 'Clipboard image is too large' - ) - expect(invoke('clipboard:readImageThumbnail')).toBeNull() - expect(mocks.createFromBuffer).not.toHaveBeenCalled() - expect(mocks.writeFile).not.toHaveBeenCalled() - }) - it('rejects oversized declared JPEG dimensions before decoding and omits their preview', async () => { const image = setImage() setImage({ width: 0, height: 0 }, true) @@ -196,24 +128,4 @@ describe('macOS clipboard image data beside a file URL', () => { expect(mocks.readImage).not.toHaveBeenCalled() expect(mocks.readBuffer).not.toHaveBeenCalled() }) - - it('checks the renderer before probing native image types', () => { - setTrustedClipboardRendererWebContentsId(42) - expect(() => invoke('clipboard:hasImage')).toThrow('Unauthorized clipboard IPC sender') - expect(mocks.has).not.toHaveBeenCalled() - }) - - it.each([false, true])('rejects oversized PNG output with raw recovery: %s', async (recover) => { - if (recover) { - const image = setImage() - setImage({ width: 0, height: 0 }, true) - mocks.readBuffer.mockReturnValue(Buffer.from([0xff, 0xd8])) - mocks.createFromBuffer.mockReturnValue(image) - } - mocks.toPNG.mockReturnValue(Buffer.alloc(CLIPBOARD_IMAGE_MAX_SOURCE_BYTES + 1)) - await expect( - invoke('clipboard:saveImageAsTempFile', { connectionId: 'ssh-1' }) - ).rejects.toThrow('Clipboard image is too large') - expect(mocks.writeFile).not.toHaveBeenCalled() - }) }) diff --git a/src/main/window/terminal-pane-move-request-relay.test.ts b/src/main/window/terminal-pane-move-request-relay.test.ts index 4073a97b0c4..cd5c63de623 100644 --- a/src/main/window/terminal-pane-move-request-relay.test.ts +++ b/src/main/window/terminal-pane-move-request-relay.test.ts @@ -94,20 +94,6 @@ describe('requestTerminalPaneMoveFromRenderer', () => { await expect(pending).resolves.toEqual({ status: 'moved', ptyId: 'pty-1' }) }) - it('leaves a commit no client asked for alone', async () => { - const { relay, sender } = await requestMove() - const commit = vi.fn(async (): Promise => ({ - status: 'moved', - ptyId: null - })) - - await expect(relay.commitRelayedPaneMove(sender, 'tab-other', commit)).resolves.toEqual({ - status: 'moved', - ptyId: null - }) - expect(commit).toHaveBeenCalledOnce() - }) - it('answers with the commit when the window goes away while it commits', async () => { const { relay, pending, sender, webContents } = await requestMove() const { commit, finish } = deferredCommit() @@ -118,26 +104,4 @@ describe('requestTerminalPaneMoveFromRenderer', () => { await expect(committing).resolves.toEqual({ status: 'moved', ptyId: 'pty-1' }) await expect(pending).resolves.toEqual({ status: 'moved', ptyId: 'pty-1' }) }) - - it('refuses a second move for a tab id a timed-out move still fences', async () => { - const first = await requestMove() - const timedOut = expect(first.pending).rejects.toThrow('terminal_pane_move_timeout') - await vi.advanceTimersByTimeAsync(10_000) - await timedOut - - const second = first.relay.requestTerminalPaneMoveFromRenderer( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the EventEmitter double implements the BrowserWindow members the relay uses. - createMainWindow().mainWindow as never, - move - ) - await expect(second).rejects.toThrow('terminal_pane_move_in_progress') - const commit = vi.fn(async (): Promise => ({ - status: 'moved', - ptyId: 'pty-1' - })) - await expect( - first.relay.commitRelayedPaneMove(first.sender, move.targetTabId, commit) - ).resolves.toEqual({ status: 'refused', reason: 'pane_unavailable' }) - expect(commit).not.toHaveBeenCalled() - }) }) diff --git a/src/main/window/terminal-pane-reveal-relay.test.ts b/src/main/window/terminal-pane-reveal-relay.test.ts index 493a954906e..1bf27204fdf 100644 --- a/src/main/window/terminal-pane-reveal-relay.test.ts +++ b/src/main/window/terminal-pane-reveal-relay.test.ts @@ -70,93 +70,6 @@ describe('revealTerminalPaneInWindow', () => { vi.useRealTimers() }) - it.each(['destroyed', 'render-process-gone', 'did-navigate', 'closed'])( - 'retires a pending reveal on %s and ignores its late reply', - async (event) => { - vi.useFakeTimers() - const revealTerminalPaneInWindow = await loadRelay() - const { webContents, mainWindow, windowEvents, sentRequest } = createWindow() - let outcome: boolean | string | undefined - const pending = revealTerminalPaneInWindow(mainWindow, target).then( - (value) => (outcome = value), - (error: Error) => (outcome = error.message) - ) - - ;(event === 'closed' ? windowEvents : webContents).emit(event) - await Promise.resolve() - await Promise.resolve() - - expect(outcome).toBe('renderer_unavailable') - await pending - reply(webContents, sentRequest().requestId, true) - expect(mocks.focusExistingMainWindow).not.toHaveBeenCalled() - expect(ipcEmitter.listenerCount('ui:terminalPaneRevealReply')).toBe(0) - expect(webContents.eventNames()).toEqual([]) - expect(windowEvents.eventNames()).toEqual([]) - expect(vi.getTimerCount()).toBe(0) - } - ) - - it('shares listeners across a burst and preserves another window after retirement', async () => { - vi.useFakeTimers() - const revealTerminalPaneInWindow = await loadRelay() - const retired = createWindow() - const survivor = createWindow() - const pending = Array.from({ length: 100 }, () => - revealTerminalPaneInWindow(retired.mainWindow, target).catch((error: Error) => error.message) - ) - const live = revealTerminalPaneInWindow(survivor.mainWindow, target) - expect(ipcEmitter.listenerCount('ui:terminalPaneRevealReply')).toBe(1) - for (const event of ['destroyed', 'render-process-gone', 'did-navigate']) { - expect(retired.webContents.listenerCount(event)).toBe(1) - } - - retired.webContents.emit('render-process-gone') - await expect(Promise.all(pending)).resolves.toEqual( - Array.from({ length: 100 }, () => 'renderer_unavailable') - ) - expect(retired.webContents.eventNames()).toEqual([]) - expect(retired.windowEvents.eventNames()).toEqual([]) - expect(vi.getTimerCount()).toBe(1) - reply(retired.webContents, retired.sentRequest().requestId, true) - expect(mocks.focusExistingMainWindow).not.toHaveBeenCalled() - reply(survivor.webContents, survivor.sentRequest().requestId, true) - await expect(live).resolves.toBe(true) - expect(mocks.focusExistingMainWindow).toHaveBeenCalledOnce() - expect(ipcEmitter.listenerCount('ui:terminalPaneRevealReply')).toBe(0) - expect(survivor.webContents.eventNames()).toEqual([]) - expect(survivor.windowEvents.eventNames()).toEqual([]) - expect(vi.getTimerCount()).toBe(0) - }) - - it('keeps same-document navigation and an uncommitted navigation attempt live', async () => { - const revealTerminalPaneInWindow = await loadRelay() - const { webContents, mainWindow, sentRequest } = createWindow() - const pending = revealTerminalPaneInWindow(mainWindow, target) - webContents.emit('did-navigate-in-page', {}, '#section', true) - webContents.emit('did-start-navigation', {}, 'https://external.test', false, true) - reply(webContents, sentRequest().requestId, true) - await expect(pending).resolves.toBe(true) - expect(mocks.focusExistingMainWindow).toHaveBeenCalledOnce() - }) - - it('releases the request when sending to the renderer throws', async () => { - vi.useFakeTimers() - const revealTerminalPaneInWindow = await loadRelay() - const { webContents, mainWindow, windowEvents } = createWindow() - webContents.send.mockImplementation(() => { - throw new Error('Render frame was disposed') - }) - await expect(revealTerminalPaneInWindow(mainWindow, target)).rejects.toThrow( - 'renderer_unavailable' - ) - expect(ipcEmitter.listenerCount('ui:terminalPaneRevealReply')).toBe(0) - expect(webContents.eventNames()).toEqual([]) - expect(windowEvents.eventNames()).toEqual([]) - expect(vi.getTimerCount()).toBe(0) - expect(mocks.focusExistingMainWindow).not.toHaveBeenCalled() - }) - it('raises the window once the targeted renderer has revealed the pane', async () => { const revealTerminalPaneInWindow = await loadRelay() const { webContents, mainWindow, sentRequest } = createWindow() @@ -176,44 +89,4 @@ describe('revealTerminalPaneInWindow', () => { expect(focus?.canOpenWindow?.()).toBe(false) expect(ipcEmitter.listenerCount('ui:terminalPaneRevealReply')).toBe(0) }) - - it('leaves the window where it is when the renderer does not know the workspace', async () => { - const revealTerminalPaneInWindow = await loadRelay() - const { webContents, mainWindow, sentRequest } = createWindow() - const pending = revealTerminalPaneInWindow(mainWindow, target) - - reply(webContents, sentRequest().requestId, false) - - await expect(pending).resolves.toBe(false) - expect(mocks.focusExistingMainWindow).not.toHaveBeenCalled() - }) - - it('fails instead of waiting when the window is gone', async () => { - const revealTerminalPaneInWindow = await loadRelay() - const { webContents, mainWindow } = createWindow({ rendererDestroyed: true }) - - await expect(revealTerminalPaneInWindow(mainWindow, target)).rejects.toThrow( - 'renderer_unavailable' - ) - expect(webContents.send).not.toHaveBeenCalled() - }) - - it('times out when the renderer never answers', async () => { - vi.useFakeTimers() - try { - const revealTerminalPaneInWindow = await loadRelay() - const { mainWindow } = createWindow() - const assertion = expect(revealTerminalPaneInWindow(mainWindow, target)).rejects.toThrow( - 'terminal_reveal_timeout' - ) - - await vi.advanceTimersByTimeAsync(10_000) - - await assertion - expect(ipcEmitter.listenerCount('ui:terminalPaneRevealReply')).toBe(0) - expect(mocks.focusExistingMainWindow).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts b/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts index 940bd1f2089..8a52338b972 100644 --- a/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts +++ b/src/main/workspace-hooks/created-worktree-setup-trust-parity.test.ts @@ -2,15 +2,12 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../shared/repo-types' + import { getSetupTrustContent } from '../../shared/orca-hook-setup-config' -import { hashOrcaHookScript } from '../../renderer/src/lib/orca-hook-trust' -import { RuntimeRepositoryHooksCommands } from '../runtime/repositories/runtime-repository-hooks-commands' +import '../../renderer/src/lib/orca-hook-trust' +import '../runtime/repositories/runtime-repository-hooks-commands' import { loadHooks } from './hooks' -import { - checkCreatedWorktreeSetupTrust, - hashOrcaHookTrustContent -} from './created-worktree-setup-trust' +import { hashOrcaHookTrustContent } from './created-worktree-setup-trust' // The prompt hashes the primary checkout's orca.yaml; the host hashes the created worktree's. // Same committed file => same hash, whatever the checkout did to line endings or a BOM. @@ -43,20 +40,6 @@ function checkout(content: string): string { return dir } -const repo = (overrides: Partial = {}): Repo => ({ - id: 'repo', - path: '/primary', - displayName: 'repo', - badgeColor: '', - addedAt: 0, - ...overrides -}) - -/** What the trust prompt approves: the renderer's hash of the primary checkout's content. */ -async function promptHash(primaryPath: string): Promise { - return hashOrcaHookScript(getSetupTrustContent(loadHooks(primaryPath))) -} - beforeEach(() => { dirs.length = 0 }) @@ -69,65 +52,6 @@ afterEach(() => { }) describe('approved setup hash parity between the trust prompt and the host', () => { - const variants: [string, (yaml: string) => string][] = [ - ['identical LF files', (yaml) => yaml], - ['a CRLF primary checkout (Windows autocrlf)', (yaml) => yaml.replace(/\n/g, '\r\n')], - ['a primary checkout saved with a UTF-8 BOM', (yaml) => `${yaml}`], - ['a primary checkout with trailing blank lines', (yaml) => `${yaml}\n\n\n`] - ] - - it.each(variants)('treats %s as the approved content', async (_label, toPrimary) => { - const primary = checkout(toPrimary(SETUP_YAML)) - const created = checkout(SETUP_YAML) - const approved = await promptHash(primary) - - expect( - checkCreatedWorktreeSetupTrust(repo(), loadHooks(created), 'run', { - approvedSetupHash: approved - }) - ).toBe(undefined) - }) - - it('agrees with the pure-JS digest the plain-HTTP web client uses', async () => { - const primary = checkout(SETUP_YAML) - const subtleHash = await promptHash(primary) - vi.stubGlobal('crypto', undefined) - const fallbackHash = await promptHash(primary) - - expect(fallbackHash).toBe(subtleHash) - expect(hashOrcaHookTrustContent(getSetupTrustContent(loadHooks(primary)))).toBe(subtleHash) - }) - - it('agrees with the hash a runtime host reports to remote and mobile clients', async () => { - const primary = checkout(SETUP_YAML) - const created = checkout(SETUP_YAML.replace(/\n/g, '\r\n')) - const hooks = await new RuntimeRepositoryHooksCommands({ - resolveRepo: async () => repo({ path: primary }) - }).getRepoHooks('id:repo') - - expect(hooks.setupTrust?.contentHash).toBe(await promptHash(primary)) - expect( - checkCreatedWorktreeSetupTrust(repo(), loadHooks(created), 'run', { - approvedSetupHash: hooks.setupTrust?.contentHash - }) - ).toBe(undefined) - }) - - it('ignores orca.yaml keys that are not setup or default tab commands', async () => { - const primary = checkout(SETUP_YAML) - const created = checkout( - SETUP_YAML.replace('issueCommand: gh issue view', 'issueCommand: gh issue view --web') - .replace(' - title: Notes', ' - title: Scratch') - .concat('scripts_extra: also ignored\n') - ) - - expect( - checkCreatedWorktreeSetupTrust(repo(), loadHooks(created), 'run', { - approvedSetupHash: await promptHash(primary) - }) - ).toBe(undefined) - }) - it('pins the digest so a format change, which would invalidate saved automation approvals, is deliberate', () => { expect(getSetupTrustContent(loadHooks(checkout(SETUP_YAML)))).toBe( [ @@ -141,69 +65,6 @@ describe('approved setup hash parity between the trust prompt and the host', () PINNED_SETUP_HASH ) }) - - it.each([ - [ - 'a changed setup line', - (yaml: string) => yaml.replace('pnpm install', 'pnpm install && curl x') - ], - ['a changed default tab command', (yaml: string) => yaml.replace('--port 3000', '--port 4000')], - [ - 'an added default tab command', - (yaml: string) => - yaml.replace(' - title: Notes', ' - title: Notes\n command: make serve') - ] - ])('still reports %s as a mismatch', async (_label, change) => { - const primary = checkout(SETUP_YAML) - const created = checkout(change(SETUP_YAML)) - - expect( - checkCreatedWorktreeSetupTrust(repo(), loadHooks(created), 'run', { - approvedSetupHash: await promptHash(primary) - }) - ).toMatchObject({ scriptContent: expect.any(String) }) - }) - - it('checks only the shared commands under run-both, as the prompt does', async () => { - const primary = checkout(SETUP_YAML) - const created = checkout(SETUP_YAML) - const runBoth = repo({ - hookSettings: { - mode: 'auto', - commandSourcePolicy: 'run-both', - scripts: { setup: 'echo my own local step', archive: '' } - } - }) - - expect( - checkCreatedWorktreeSetupTrust(runBoth, loadHooks(created), 'run', { - approvedSetupHash: await promptHash(primary) - }) - ).toBe(undefined) - }) - - it('never reports a mismatch under the local-only policy, where shared setup does not run', async () => { - const created = checkout(SETUP_YAML) - const localOnly = repo({ - hookSettings: { - mode: 'auto', - commandSourcePolicy: 'local-only', - scripts: { setup: 'echo mine', archive: '' } - } - }) - - expect( - checkCreatedWorktreeSetupTrust(localOnly, loadHooks(created), 'run', { - approvedSetupHash: 'not-the-hash' - }) - ).toBe(undefined) - }) - - it('leaves creates without an approval hash (older clients, CLI, stored decisions) unchanged', () => { - expect(checkCreatedWorktreeSetupTrust(repo(), loadHooks(checkout(SETUP_YAML)), 'run', {})).toBe( - undefined - ) - }) }) const PINNED_SETUP_HASH = '112aac76dbc70758498c2b87a2dc42e77f7ce366a5b611749ec38b6757681593' diff --git a/src/main/workspaces/catalog/worktree-lineage-pruning.test.ts b/src/main/workspaces/catalog/worktree-lineage-pruning.test.ts deleted file mode 100644 index ec7697f1c3e..00000000000 --- a/src/main/workspaces/catalog/worktree-lineage-pruning.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../shared/repo-types' -import type { WorkspaceLineage, WorktreeLineage } from '../../../shared/worktree/lineage-types' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { worktreeWorkspaceKey } from '../../../shared/workspace-scope' -import { pruneLineageForMissingRepoWorktrees } from './worktree-lineage-pruning' -import { - hostWorktreeTarget, - type HostWorktreeTarget -} from '../../../shared/worktree/host-qualified-identity' - -const repo: Repo = { - id: 'repo-1', - path: '/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 -} - -function lineage(childId: string, parentId: string): WorktreeLineage { - return { - worktreeId: childId, - worktreeInstanceId: `${childId}-instance`, - parentWorktreeId: parentId, - parentWorktreeInstanceId: `${parentId}-instance`, - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 1 - } -} - -function workspaceLineage(childId: string, parentId: string): WorkspaceLineage { - return { - childWorkspaceKey: worktreeWorkspaceKey(childId), - childInstanceId: `${childId}-instance`, - parentWorkspaceKey: worktreeWorkspaceKey(parentId), - parentInstanceId: `${parentId}-instance`, - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 1 - } -} - -function createStore( - worktreeLineageById: Record, - workspaceLineageByChildKey: Record, - metaById: Record -) { - return { - getRepos: () => [repo], - getAllWorktreeLineage: () => worktreeLineageById, - getAllWorkspaceLineage: () => workspaceLineageByChildKey, - getWorktreeMeta: (id: string) => metaById[id], - // Mirrors the store: removing a worktree's lineage also drops its workspace lineage. - removeWorktreeLineage: vi.fn(({ id }: HostWorktreeTarget) => { - delete worktreeLineageById[id] - delete workspaceLineageByChildKey[worktreeWorkspaceKey(id)] - }), - setWorktreeMeta: vi.fn(({ id }: HostWorktreeTarget, updates: Partial) => { - metaById[id] = { ...metaById[id], ...updates } - return metaById[id] - }) - } -} - -describe('pruneLineageForMissingRepoWorktrees', () => { - it('keeps lineage stored under another spelling of a live worktree path', () => { - const parentId = 'repo-1::/repo' - const childId = 'repo-1::/repo/./child' - const edge = lineage(childId, parentId) - const worktreeLineageById = { [childId]: edge } - const workspaceLineageByChildKey = { - [worktreeWorkspaceKey(childId)]: workspaceLineage(childId, parentId) - } - const metaById = { - [parentId]: { instanceId: edge.parentWorktreeInstanceId } as WorktreeMeta - } - const store = createStore(worktreeLineageById, workspaceLineageByChildKey, metaById) - - pruneLineageForMissingRepoWorktrees( - store as never, - repo, - [ - { path: '/repo', head: 'a', branch: 'main', isBare: false, isMainWorktree: true }, - { path: '/repo/child/', head: 'b', branch: 'child', isBare: false, isMainWorktree: false } - ], - { platform: 'linux' } - ) - - expect(store.removeWorktreeLineage).not.toHaveBeenCalled() - expect(store.setWorktreeMeta).not.toHaveBeenCalled() - expect(worktreeLineageById[childId]).toBe(edge) - }) - - it('keeps captured metadata lineage not removed after Git canonicalizes paths', () => { - const parentId = 'repo-1::/alias/parent' - const childId = 'repo-1::/alias/child' - const edge = lineage(childId, parentId) - const worktreeLineageById = { [childId]: edge } - const workspaceLineageByChildKey = { - [worktreeWorkspaceKey(childId)]: workspaceLineage(childId, parentId) - } - const metaById = { - [childId]: { instanceId: edge.worktreeInstanceId } as WorktreeMeta, - [parentId]: { instanceId: edge.parentWorktreeInstanceId } as WorktreeMeta - } - const store = createStore(worktreeLineageById, workspaceLineageByChildKey, metaById) - - pruneLineageForMissingRepoWorktrees( - store as never, - repo, - [ - { - path: '/canonical/parent', - head: 'a', - branch: 'parent', - isBare: false, - isMainWorktree: false - }, - { - path: '/canonical/child', - head: 'b', - branch: 'child', - isBare: false, - isMainWorktree: false - } - ], - { - platform: 'linux', - preservedMetadataCandidateIds: new Set([parentId, childId]) - } - ) - - expect(store.removeWorktreeLineage).not.toHaveBeenCalled() - expect(store.setWorktreeMeta).not.toHaveBeenCalled() - expect(worktreeLineageById[childId]).toBe(edge) - expect(workspaceLineageByChildKey[worktreeWorkspaceKey(childId)]).toBeDefined() - expect(metaById[parentId].instanceId).toBe(edge.parentWorktreeInstanceId) - }) - - it('refuses an empty scan when the repo still has registered lineage', () => { - const parentId = 'repo-1::/repo/parent' - const childId = 'repo-1::/repo/child' - const edge = lineage(childId, parentId) - const workspaceEdge = workspaceLineage(childId, parentId) - const worktreeLineageById = { [childId]: edge } - const workspaceLineageByChildKey = { [worktreeWorkspaceKey(childId)]: workspaceEdge } - const metaById = { - [parentId]: { instanceId: edge.parentWorktreeInstanceId } as WorktreeMeta - } - const store = createStore(worktreeLineageById, workspaceLineageByChildKey, metaById) - - pruneLineageForMissingRepoWorktrees(store as never, repo, []) - - expect(store.removeWorktreeLineage).not.toHaveBeenCalled() - expect(store.setWorktreeMeta).not.toHaveBeenCalled() - expect(worktreeLineageById[childId]).toBe(edge) - expect(workspaceLineageByChildKey[worktreeWorkspaceKey(childId)]).toBe(workspaceEdge) - }) - - it('prunes and rotates missing IDs absent from preserved metadata candidates', () => { - const liveParentId = 'repo-1::/repo/live-parent' - const missingChildId = 'repo-1::/repo/missing-child' - const liveChildId = 'repo-1::/repo/live-child' - const missingParentId = 'repo-1::/repo/missing-parent' - const missingChildEdge = lineage(missingChildId, liveParentId) - const missingParentEdge = lineage(liveChildId, missingParentId) - const worktreeLineageById = { - [missingChildId]: missingChildEdge, - [liveChildId]: missingParentEdge - } - const workspaceLineageByChildKey = { - [worktreeWorkspaceKey(missingChildId)]: workspaceLineage(missingChildId, liveParentId), - [worktreeWorkspaceKey(liveChildId)]: workspaceLineage(liveChildId, missingParentId) - } - const metaById = { - [liveParentId]: { instanceId: missingChildEdge.parentWorktreeInstanceId } as WorktreeMeta, - [missingParentId]: { instanceId: missingParentEdge.parentWorktreeInstanceId } as WorktreeMeta - } - const store = createStore(worktreeLineageById, workspaceLineageByChildKey, metaById) - - pruneLineageForMissingRepoWorktrees( - store as never, - repo, - [ - { - path: '/repo/live-parent', - head: 'a', - branch: 'main', - isBare: false, - isMainWorktree: false - }, - { - path: '/repo/live-child', - head: 'b', - branch: 'child', - isBare: false, - isMainWorktree: false - } - ], - { preservedMetadataCandidateIds: new Set([liveParentId, liveChildId]) } - ) - - expect(store.removeWorktreeLineage).toHaveBeenCalledWith( - hostWorktreeTarget({ id: missingChildId, hostId: 'local' }) - ) - expect(store.removeWorktreeLineage).not.toHaveBeenCalledWith( - hostWorktreeTarget({ id: liveChildId, hostId: 'local' }) - ) - expect(workspaceLineageByChildKey[worktreeWorkspaceKey(missingChildId)]).toBeUndefined() - expect(workspaceLineageByChildKey[worktreeWorkspaceKey(liveChildId)]).toBeDefined() - expect(store.setWorktreeMeta).toHaveBeenCalledWith( - hostWorktreeTarget({ id: missingParentId, hostId: 'local' }), - { - instanceId: expect.any(String) - } - ) - expect(store.setWorktreeMeta).not.toHaveBeenCalledWith( - hostWorktreeTarget({ id: liveParentId, hostId: 'local' }), - expect.anything() - ) - expect(metaById[missingParentId].instanceId).not.toBe( - missingParentEdge.parentWorktreeInstanceId - ) - }) -}) diff --git a/src/main/workspaces/removal/retirement/worktree-name-retirement.test.ts b/src/main/workspaces/removal/retirement/worktree-name-retirement.test.ts deleted file mode 100644 index 6ce5d66e634..00000000000 --- a/src/main/workspaces/removal/retirement/worktree-name-retirement.test.ts +++ /dev/null @@ -1,218 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { mkdir, mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { MARINE_CREATURES } from '../../../../shared/marine-creatures' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import type { Repo } from '../../../../shared/repo-types' -import { - ensureRetiredWorktreeNamesBackfilled, - getRetiredNameRegistryForRepo, - normalizeRetirableGeneratedName, - resetRetirementCollisionKeyCacheForTests -} from './worktree-name-retirement' - -const FIRST = MARINE_CREATURES[0].toLowerCase() -const SECOND = MARINE_CREATURES[1].toLowerCase() - -const makeRepo = (id: string, path: string): Repo => - ({ id, path, displayName: id, badgeColor: '', addedAt: 0 }) as Repo - -beforeEach(() => { - resetRetirementCollisionKeyCacheForTests() -}) - -describe('normalizeRetirableGeneratedName', () => { - it('accepts pool names and every numbered tier, not just single digits', () => { - expect(normalizeRetirableGeneratedName(` ${FIRST} `)).toBe(FIRST) - expect(normalizeRetirableGeneratedName(`${FIRST}-2`)).toBe(`${FIRST}-2`) - expect(normalizeRetirableGeneratedName(`${FIRST}-10`)).toBe(`${FIRST}-10`) - expect(normalizeRetirableGeneratedName(`${FIRST}-100`)).toBe(`${FIRST}-100`) - }) - - it('rejects legacy repeated suffixes that the canonical collision sequence never emits', () => { - expect(normalizeRetirableGeneratedName(`${FIRST}-2-3`)).toBeNull() - expect(normalizeRetirableGeneratedName(`${FIRST}-2-3-4`)).toBeNull() - expect(normalizeRetirableGeneratedName('fix-login-2-3')).toBeNull() - }) - - it('rejects names outside the pool and absurdly long input', () => { - expect(normalizeRetirableGeneratedName('fix-login')).toBeNull() - expect(normalizeRetirableGeneratedName('')).toBeNull() - expect(normalizeRetirableGeneratedName(`${FIRST}-${'9'.repeat(300)}`)).toBeNull() - }) -}) - -describe('getRetiredNameRegistryForRepo', () => { - const settingsFor = (nestWorkspaces: boolean): GlobalSettings => - ({ workspaceDir: '/workspaces', nestWorkspaces }) as GlobalSettings - const storeOf = (byRepo: Record) => { - const calls: string[] = [] - return { - calls, - mergeRetiredWorktreeNames: () => false, - getRetiredWorktreeNameRegistry: (repoId: string) => { - calls.push(repoId) - return { exhaustedTiers: 0, names: byRepo[repoId] ?? [] } - } - } - } - - it('shares retirements when two repos create into the same cwd namespace', async () => { - const store = storeOf({ 'repo-a': [FIRST], 'repo-b': [SECOND] }) - const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - - expect( - [ - ...(await getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(false))).names - ].sort() - ).toEqual([FIRST, SECOND].sort()) - }) - - it('keeps independent nested repo paths in separate retirement domains', async () => { - const store = storeOf({ 'repo-a': [FIRST], 'repo-b': [SECOND] }) - const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - - expect(await getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(true))).toEqual({ - exhaustedTiers: 0, - names: [SECOND] - }) - }) - - it('never probes a path for peers that hold no retirements', async () => { - const pathReads: string[] = [] - const spyRepo = (id: string, path: string): Repo => { - const repo = makeRepo(id, path) - return Object.defineProperty(repo, 'path', { - get: () => { - pathReads.push(id) - return path - } - }) as Repo - } - const store = storeOf({ 'repo-a': [FIRST] }) - const repos = [ - spyRepo('repo-a', '/repos/a'), - ...Array.from({ length: 20 }, (_unused, index) => spyRepo(`peer-${index}`, `/repos/${index}`)) - ] - - expect(await getRetiredNameRegistryForRepo(store, repos[0], repos, settingsFor(false))).toEqual( - { - exhaustedTiers: 0, - names: [FIRST] - } - ) - expect(pathReads.filter((id) => id.startsWith('peer-'))).toEqual([]) - }) - - it('reports nothing for a folder workspace, which has no generated worktree names', async () => { - const store = storeOf({ folder: [FIRST] }) - const folderRepo = { ...makeRepo('folder', '/repos/folder'), kind: 'folder' as const } - - expect( - (await getRetiredNameRegistryForRepo(store, folderRepo, [folderRepo], settingsFor(false))) - .names - ).toEqual([]) - }) -}) - -describe('ensureRetiredWorktreeNamesBackfilled', () => { - it('awaits the historical workspace scan before returning names to a client', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-retirement-backfill-')) - const workspaceRoot = join(root, 'workspaces') - await mkdir(join(workspaceRoot, FIRST), { recursive: true }) - const merged: { repoId: string; names: string[] }[] = [] - const store = { - mergeRetiredWorktreeNames: (repoId: string, names: Iterable) => { - merged.push({ repoId, names: [...names] }) - return true - } - } - const settings = { workspaceDir: workspaceRoot, nestWorkspaces: false } - - try { - await ensureRetiredWorktreeNamesBackfilled(store, makeRepo('repo-a', '/repos/a'), settings) - expect(merged).toEqual([{ repoId: 'repo-a', names: [FIRST] }]) - - // A shared namespace scan must still populate each repo's separate registry. - await ensureRetiredWorktreeNamesBackfilled(store, makeRepo('repo-b', '/repos/b'), settings) - expect(merged).toEqual([ - { repoId: 'repo-a', names: [FIRST] }, - { repoId: 'repo-b', names: [FIRST] } - ]) - } finally { - await rm(root, { force: true, recursive: true }) - } - }) - - it('skips repos whose agent state lives on another host', async () => { - const merged: string[] = [] - const store = { - mergeRetiredWorktreeNames: (_repoId: string, names: Iterable) => { - merged.push(...names) - return true - } - } - const sshRepo = { ...makeRepo('repo-ssh', '/remote/repo'), connectionId: 'ssh-1' } - - await ensureRetiredWorktreeNamesBackfilled(store, sshRepo, { - workspaceDir: '/workspaces', - nestWorkspaces: false - }) - - expect(merged).toEqual([]) - }) - - it('skips a runtime-owned repo, which has no connectionId but is still not local', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-retirement-runtime-')) - const workspaceRoot = join(root, 'workspaces') - await mkdir(join(workspaceRoot, FIRST), { recursive: true }) - const merged: string[] = [] - const store = { - mergeRetiredWorktreeNames: (_repoId: string, names: Iterable) => { - merged.push(...names) - return true - } - } - const runtimeRepo = { - ...makeRepo('repo-runtime', '/repos/runtime'), - executionHostId: 'runtime:env-1' - } as Repo - - try { - const collisionKey = await ensureRetiredWorktreeNamesBackfilled(store, runtimeRepo, { - workspaceDir: workspaceRoot, - nestWorkspaces: false - }) - - expect(merged).toEqual([]) - expect(collisionKey).toBeNull() - } finally { - await rm(root, { force: true, recursive: true }) - } - }) - - it('still backfills a plain local repo, so the skip is scoped to non-local hosts', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-retirement-local-')) - const workspaceRoot = join(root, 'workspaces') - await mkdir(join(workspaceRoot, FIRST), { recursive: true }) - const merged: string[] = [] - const store = { - mergeRetiredWorktreeNames: (_repoId: string, names: Iterable) => { - merged.push(...names) - return true - } - } - - try { - await ensureRetiredWorktreeNamesBackfilled(store, makeRepo('repo-local', '/repos/local'), { - workspaceDir: workspaceRoot, - nestWorkspaces: false - }) - - expect(merged).toEqual([FIRST]) - } finally { - await rm(root, { force: true, recursive: true }) - } - }) -}) diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts deleted file mode 100644 index 6ef0495b0b9..00000000000 --- a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { mkdir, mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { MARINE_CREATURES } from '../../../../shared/marine-creatures' -import { - collectRetiredNamesFromLeafNames, - discoverRetiredWorktreeNames, - extractBucketLeafCandidates -} from './worktree-retirement-discovery' - -const FIRST = MARINE_CREATURES[0].toLowerCase() -const SECOND = MARINE_CREATURES[1].toLowerCase() - -describe('extractBucketLeafCandidates', () => { - it('takes everything past the encoded parent as the leaf', () => { - expect(extractBucketLeafCandidates(`-w-orca-${FIRST}`, ['-w-orca'])).toEqual([FIRST]) - }) - - it('does not treat the parent directory as a leaf when the workspace name is numeric', () => { - expect(extractBucketLeafCandidates('-w-workspaces-orca-7474', ['-w-workspaces-orca'])).toEqual([ - '7474' - ]) - }) - - it('offers the first segment too, so an agent run in a subdirectory still retires the leaf', () => { - expect(extractBucketLeafCandidates(`-w-orca-${FIRST}-packages-api`, ['-w-orca'])).toEqual([ - `${FIRST}-packages-api`, - FIRST - ]) - }) - - it('rejects a sibling directory that shares the parent prefix', () => { - expect(extractBucketLeafCandidates(`-w-orcadyne-${FIRST}`, ['-w-orca'])).toEqual([]) - expect(extractBucketLeafCandidates(`-w-orca-secret-${FIRST}`, ['-w-orca-fix'])).toEqual([]) - }) - - it('yields nothing for the parent bucket itself', () => { - expect(extractBucketLeafCandidates('-w-orca', ['-w-orca'])).toEqual([]) - }) -}) - -describe('collectRetiredNamesFromLeafNames', () => { - it('keeps pool names and drops everything else', () => { - expect(collectRetiredNamesFromLeafNames([FIRST, SECOND, 'fix-login'])).toEqual( - new Set([FIRST, SECOND]) - ) - }) - - it('is case-insensitive and skips non-string entries without throwing', () => { - const leaves = [undefined, null, '', MARINE_CREATURES[0].toUpperCase()] as unknown as string[] - expect(collectRetiredNamesFromLeafNames(leaves)).toEqual(new Set([FIRST])) - }) -}) - -describe('discoverRetiredWorktreeNames', () => { - /** Use literal real-world bucket encodings so a mirrored encoder cannot hide a broken implementation. */ - async function withFakeHome( - buckets: readonly string[], - run: (home: string) => Promise - ): Promise { - const home = await mkdtemp(join(tmpdir(), 'orca-retirement-home-')) - try { - for (const bucket of buckets) { - await mkdir(join(home, '.claude', 'projects', bucket), { recursive: true }) - } - await run(home) - } finally { - await rm(home, { force: true, recursive: true }) - } - } - - it('calls a machine with no agent state a complete answer, not a hole to rescan forever', async () => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: [join(tmpdir(), 'orca-retirement-absent-root')], - home: join(tmpdir(), 'orca-retirement-absent-home'), - env: {} - }) - - expect(retired.names).toEqual(new Set()) - expect(retired.complete).toBe(true) - }) - - it('matches a plain POSIX workspace root', async () => { - await withFakeHome([`-Users-ada-orca-workspaces-orca-${FIRST}`], async (home) => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['/Users/ada/orca/workspaces/orca'], - home, - env: {} - }) - expect(retired.names).toEqual(new Set([FIRST])) - }) - }) - - it('matches an NFC bucket for an NFD workspace root', async () => { - const nfdRoot = '/Users/ada/cafe\u0301' - await withFakeHome([`-Users-ada-caf--${FIRST}`], async (home) => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: [nfdRoot], - home, - env: {} - }) - expect(retired.names).toEqual(new Set([FIRST])) - }) - }) - - it('matches a dot-directory root, where the separator run encodes to two dashes', async () => { - await withFakeHome([`-Users-ada--orca-worktrees-${FIRST}`], async (home) => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['/Users/ada/.orca/worktrees'], - home, - env: {} - }) - expect(retired.names).toEqual(new Set([FIRST])) - }) - }) - - it('matches a Windows drive root', async () => { - // Claude encodes drive punctuation separately; C:\ must produce C--. - await withFakeHome([`C--Users-ada-orca-workspaces-${FIRST}`], async (home) => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['C:\\Users\\ada\\orca\\workspaces'], - home, - env: {} - }) - expect(retired.names).toEqual(new Set([FIRST])) - }) - }) - - it('matches a WSL UNC root', async () => { - await withFakeHome([`--wsl--Ubuntu-home-ada-orca-workspaces-${FIRST}`], async (home) => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['\\\\wsl$\\Ubuntu\\home\\ada\\orca\\workspaces'], - home, - env: {}, - // Stub distro-home resolution so Windows tests cannot boot the developer's distro. - resolveWslHome: async () => null - }) - expect(retired.names).toEqual(new Set([FIRST])) - }) - }) - - it('ignores buckets belonging to a sibling root with the same prefix', async () => { - await withFakeHome( - [`-Users-ada-orca-workspaces-orcadyne-${FIRST}`, `-Users-ada-orca-workspaces-orca-${SECOND}`], - async (home) => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['/Users/ada/orca/workspaces/orca'], - home, - env: {} - }) - expect(retired.names).toEqual(new Set([SECOND])) - } - ) - }) - - it('reads buckets from CLAUDE_CONFIG_DIR when it is set', async () => { - const configDir = await mkdtemp(join(tmpdir(), 'orca-retirement-config-')) - await withFakeHome([`-Users-ada-w-${SECOND}`], async (home) => { - try { - await mkdir(join(configDir, 'projects', `-Users-ada-w-${FIRST}`), { recursive: true }) - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['/Users/ada/w'], - home, - env: { CLAUDE_CONFIG_DIR: configDir } - }) - expect(retired.names).toEqual(new Set([FIRST])) - } finally { - await rm(configDir, { force: true, recursive: true }) - } - }) - }) - - it("matches a WSL workspace's bucket inside the distro, keyed by its Linux cwd", async () => { - const distroHome = await mkdtemp(join(tmpdir(), 'orca-retirement-distro-')) - await withFakeHome([], async (home) => { - try { - await mkdir(join(distroHome, '.claude', 'projects', `-home-ada-orca-workspaces-${FIRST}`), { - recursive: true - }) - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['\\\\wsl.localhost\\Ubuntu\\home\\ada\\orca\\workspaces'], - home, - env: {}, - resolveWslHome: async (distro) => (distro === 'Ubuntu' ? distroHome : null) - }) - expect(retired.names).toEqual(new Set([FIRST])) - } finally { - await rm(distroHome, { force: true, recursive: true }) - } - }) - }) - - it('still reads the Windows-side home for a WSL root when the distro home cannot be resolved', async () => { - await withFakeHome( - [`--wsl-localhost-Ubuntu-home-ada-orca-workspaces-${FIRST}`], - async (home) => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: ['\\\\wsl.localhost\\Ubuntu\\home\\ada\\orca\\workspaces'], - home, - env: {}, - resolveWslHome: async () => null - }) - expect(retired.names).toEqual(new Set([FIRST])) - } - ) - }) - - it('retires live workspace directories alongside surviving buckets', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-retirement-roots-')) - await withFakeHome([], async (home) => { - try { - await mkdir(join(root, SECOND), { recursive: true }) - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: [root], - home, - env: {} - }) - expect(retired.names).toEqual(new Set([SECOND])) - } finally { - await rm(root, { force: true, recursive: true }) - } - }) - }) -}) diff --git a/src/main/workspaces/removal/worktree-background-removal-records.test.ts b/src/main/workspaces/removal/worktree-background-removal-records.test.ts index 09c4b739c60..766593102fe 100644 --- a/src/main/workspaces/removal/worktree-background-removal-records.test.ts +++ b/src/main/workspaces/removal/worktree-background-removal-records.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -16,11 +16,7 @@ import { snapshotPendingWorktreeRemovals } from './worktree-removal-listing' import type * as WorktreeRemovalRecords from './worktree-removal-records' -import { - readWorktreeRemovalRecords, - worktreeRemovalRecordsFile, - writeWorktreeRemovalRecords -} from './worktree-removal-records' +import { readWorktreeRemovalRecords } from './worktree-removal-records' vi.mock('./worktree-removal-records', async (importOriginal) => { const actual = await importOriginal() @@ -104,79 +100,6 @@ describe('durable worktree removal records', () => { expect(await readWorktreeRemovalRecords(directory)).toEqual([]) }) - it('clears the record when the delete fails so the row returns live and retryable', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const publish = vi.fn() - const result = startBackgroundWorktreeRemoval({ - removal, - run: async () => { - throw new Error('Permission denied') - }, - publish - }) - await expect(result).rejects.toThrow('Permission denied') - await _settlePendingWorktreeRemovalsForTests() - - expect(await readWorktreeRemovalRecords(directory)).toEqual([]) - expect(isPending()).toBe(false) - expect(publish).toHaveBeenCalledTimes(2) - }) - - it('starts Git after a bounded wait when the record write stalls', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - vi.mocked(writeWorktreeRemovalRecords).mockReturnValueOnce(new Promise(() => {})) - const run = vi.fn(async () => ({})) - void startBackgroundWorktreeRemoval({ - removal, - run, - publish: () => {} - }) - - await vi.advanceTimersByTimeAsync(1_000) - expect(run).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1_000) - expect(run).toHaveBeenCalledTimes(1) - vi.useRealTimers() - await _settlePendingWorktreeRemovalsForTests() - }) - - it('replies without waiting for the record to be cleared on disk', async () => { - let finishClear = (): void => {} - const publish = vi.fn() - const result = startBackgroundWorktreeRemoval({ - removal, - run: async () => { - vi.mocked(writeWorktreeRemovalRecords).mockReturnValueOnce( - new Promise((resolve) => { - finishClear = resolve - }) - ) - return {} - }, - publish - }) - - await expect(result).resolves.toEqual({}) - expect(publish).toHaveBeenCalledTimes(2) - finishClear() - await _settlePendingWorktreeRemovalsForTests() - }) - - it('stops Git on quit without waiting and keeps the record for the next start', async () => { - const job = interruptedJob() - void startBackgroundWorktreeRemoval({ removal, ...job }) - await vi.waitFor(() => expect(job.started()).toBe(true)) - - expect(stopBackgroundWorktreeRemovals()).toBeUndefined() - expect(job.stopped()).toBe(true) - await _settlePendingWorktreeRemovalsForTests() - - expect(await readWorktreeRemovalRecords(directory)).toHaveLength(1) - // Quit publishes no completion; the interrupted record must remain resumable. - expect(job.publish).toHaveBeenCalledTimes(1) - }) - it('marks the row as removing after a restart and finishes it with the same job', async () => { const job = interruptedJob() void startBackgroundWorktreeRemoval({ removal, ...job }) @@ -221,60 +144,4 @@ describe('durable worktree removal records', () => { await expect(joined).resolves.toEqual({}) expect(publish).toHaveBeenCalledTimes(1) }) - - it('does not start a second job for a removal that is still running', async () => { - void startBackgroundWorktreeRemoval({ removal, ...interruptedJob() }) - const jobFor = vi.fn() - resumeInterruptedWorktreeRemovals(jobFor) - expect(jobFor).not.toHaveBeenCalled() - stopBackgroundWorktreeRemovals() - await _settlePendingWorktreeRemovalsForTests() - }) - - it('reads back only well-formed records from the file', async () => { - const valid = { - worktreeId: 'repo-1::/work/a', - repoId: 'repo-1', - repoPath: '/work/repo', - worktreePath: '/work/a', - branch: '', - head: '', - deleteBranch: false, - force: true, - requestedAt: 5 - } - await writeFile( - worktreeRemovalRecordsFile(directory), - JSON.stringify({ version: 1, removals: [valid, { worktreeId: 'x' }, null] }) - ) - expect(await readWorktreeRemovalRecords(directory)).toEqual([valid]) - - await writeFile(worktreeRemovalRecordsFile(directory), '{not json') - expect(await readWorktreeRemovalRecords(directory)).toEqual([]) - }) - - it('reads a record that carries a field this version does not know, ignoring the field', async () => { - const record = { - worktreeId: 'repo-1::/work/a', - repoId: 'repo-1', - repoPath: '/work/repo', - worktreePath: '/work/a', - branch: 'feature', - head: 'abc', - deleteBranch: true, - force: false, - requestedAt: 5, - failure: { message: 'Operation not permitted', failedAt: 6 } - } - // Accept the older daily-build record format with checkout identity fields. - await writeFile( - worktreeRemovalRecordsFile(directory), - JSON.stringify({ - version: 1, - removals: [{ ...record, checkoutIdentity: { dev: 1, ino: 2, birthtimeMs: 3 } }] - }) - ) - - expect(await readWorktreeRemovalRecords(directory)).toEqual([record]) - }) }) diff --git a/src/main/workspaces/removal/worktree-removal-home-guard.test.ts b/src/main/workspaces/removal/worktree-removal-home-guard.test.ts deleted file mode 100644 index 43b7890dd4b..00000000000 --- a/src/main/workspaces/removal/worktree-removal-home-guard.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeOs from 'node:os' - -const homedirMock = vi.hoisted(() => vi.fn<() => string>()) - -vi.mock('node:os', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, homedir: homedirMock } -}) - -const { - CLIENT_REMOVAL_HOME, - executionHostRemovalHome, - getPathOps, - isHomeDirectoryRemovalPath, - isRemovalHomeAuthorityResolved -} = await import('./worktree-removal-home-guard') - -function isHome( - worktreePath: string, - home: Parameters[2] -): boolean { - return isHomeDirectoryRemovalPath(worktreePath, getPathOps(worktreePath), home) -} - -function isHomeForPair( - worktreePath: string, - repoPath: string, - home: Parameters[2] -): boolean { - return isHomeDirectoryRemovalPath(worktreePath, getPathOps(worktreePath, repoPath), home) -} - -function withProcessPlatform(platform: NodeJS.Platform, callback: () => T): T { - const original = Object.getOwnPropertyDescriptor(process, 'platform') - Object.defineProperty(process, 'platform', { value: platform }) - try { - return callback() - } finally { - if (original) { - Object.defineProperty(process, 'platform', original) - } - } -} - -beforeEach(() => { - homedirMock.mockClear() - homedirMock.mockReturnValue('/Users/ci') -}) - -describe('path-shape home detection', () => { - it.each([ - ['/home', true], - ['/root', true], - ['/Users', true], - ['/home/alice', true], - ['/Users/alice', true], - ['/home/alice/wt/foo', false], - ['/Users/alice/wt/foo', false], - ['/opt/src/checkout', false] - ])('POSIX %s -> %s', (worktreePath, expected) => { - expect(isHome(worktreePath, CLIENT_REMOVAL_HOME)).toBe(expected) - }) - - it.each([ - ['C:\\Users', true], - ['C:\\Users\\bob', true], - ['c:\\users\\bob', true], - ['D:\\Users\\bob', true], - ['\\\\server\\share\\Users\\bob', true], - ['C:\\Users\\bob\\wt\\foo', false], - ['C:\\src\\repo', false] - ])('Windows %s -> %s from a POSIX client', (worktreePath, expected) => { - expect(withProcessPlatform('darwin', () => isHome(worktreePath, CLIENT_REMOVAL_HOME))).toBe( - expected - ) - }) - - it.each([ - ['\\\\wsl.localhost\\Ubuntu', true], - ['\\\\wsl.localhost\\Ubuntu\\home\\alice', true], - ['\\\\wsl$\\Ubuntu\\home\\alice', true], - ['\\\\wsl.localhost\\Ubuntu\\root', true], - ['\\\\wsl.localhost\\Ubuntu\\home\\alice\\wt', false], - ['\\\\wsl.localhost\\Ubuntu\\srv\\work', false] - ])('WSL UNC %s -> %s', (worktreePath, expected) => { - expect(isHome(worktreePath, CLIENT_REMOVAL_HOME)).toBe(expected) - }) - - it.each([ - // drvfs maps this Linux spelling to the Windows profile C:\Users\bob. - ['\\\\wsl.localhost\\Ubuntu\\mnt\\c\\Users\\bob', true], - ['\\\\wsl$\\Ubuntu\\mnt\\c\\Users', true], - ['\\\\wsl.localhost\\Ubuntu\\mnt\\c', true], - ['\\\\wsl.localhost\\Ubuntu\\mnt\\c\\', true], - ['\\\\wsl.localhost\\Ubuntu\\mnt', true], - ['\\\\wsl.localhost\\Ubuntu\\mnt\\c\\Users\\bob\\ws\\wt', false], - ['\\\\wsl.localhost\\Ubuntu\\mnt\\c\\src\\repo', false], - // `/MNT` is an ordinary case-sensitive Linux directory, never the automount. - ['\\\\wsl.localhost\\Ubuntu\\MNT\\c\\Users\\bob', false] - ])('WSL drvfs %s -> %s', (worktreePath, expected) => { - expect(withProcessPlatform('darwin', () => isHome(worktreePath, CLIENT_REMOVAL_HOME))).toBe( - expected - ) - }) -}) - -describe('whose home the guard consults', () => { - it('never lets the client homedir answer for a foreign-syntax path', () => { - homedirMock.mockReturnValue('/Users/ci') - expect(withProcessPlatform('darwin', () => isHome('C:\\Users\\bob', CLIENT_REMOVAL_HOME))).toBe( - true - ) - expect(homedirMock).not.toHaveBeenCalled() - }) - - it('still consults the client homedir for paths in this platform s syntax', () => { - homedirMock.mockReturnValue('/srv/homes/ci') - expect(withProcessPlatform('linux', () => isHome('/srv', CLIENT_REMOVAL_HOME))).toBe(true) - expect( - withProcessPlatform('linux', () => isHome('/srv/homes/ci/wt', CLIENT_REMOVAL_HOME)) - ).toBe(false) - }) - - it('protects a non-standard home the execution host reported', () => { - homedirMock.mockReturnValue('/Users/ci') - const hostHome = executionHostRemovalHome('/srv/homes/alice') - expect(isHome('/srv/homes/alice', hostHome)).toBe(true) - // Nonstandard home paths require the executing host's answer. - expect(isHome('/srv/homes/alice', CLIENT_REMOVAL_HOME)).toBe(false) - }) - - it('reports an unanswered execution host as unresolved, never as this client s home', () => { - // A coinciding client home cannot resolve an unknown execution-host home. - homedirMock.mockReturnValue('/srv/homes/alice') - expect(isRemovalHomeAuthorityResolved(executionHostRemovalHome(null))).toBe(false) - expect(isHome('/srv/homes/alice', executionHostRemovalHome(null))).toBe(false) - expect(isHome('/home/alice', executionHostRemovalHome(null))).toBe(true) - expect(homedirMock).not.toHaveBeenCalled() - }) - - it('treats an empty execution-host home as unknown rather than as a resolved answer', () => { - expect(executionHostRemovalHome('')).toEqual({ kind: 'executionHost', homePath: null }) - expect(isRemovalHomeAuthorityResolved(executionHostRemovalHome(''))).toBe(false) - }) - - it('treats the client and an answering host as resolved', () => { - expect(isRemovalHomeAuthorityResolved(CLIENT_REMOVAL_HOME)).toBe(true) - expect(isRemovalHomeAuthorityResolved(executionHostRemovalHome('/srv/homes/alice'))).toBe(true) - }) - - it('honours a Windows execution-host home in the forward-slash form the relay reports', () => { - // `normalizeRemoteHome` folds a Windows host's `$HOME` to `C:/Users/bob`, not `C:\Users\bob`. - const hostHome = executionHostRemovalHome('C:/Users/bob/OneDrive') - expect(withProcessPlatform('darwin', () => isHome('C:\\Users\\bob\\OneDrive', hostHome))).toBe( - true - ) - expect( - withProcessPlatform('darwin', () => isHome('C:\\Users\\bob\\OneDrive\\wt\\feature', hostHome)) - ).toBe(false) - }) - - it('keeps a linked worktree under the execution host home deletable', () => { - expect( - isHome('/srv/homes/alice/wt/feature', executionHostRemovalHome('/srv/homes/alice')) - ).toBe(false) - }) - - it('ignores an execution-host home written in the other platform s syntax', () => { - expect(isHome('/srv/work', executionHostRemovalHome('C:\\Users\\bob'))).toBe(false) - expect(isHome('C:\\work', executionHostRemovalHome('/home/alice'))).toBe(false) - // Cross-syntax resolve invents /C:/Users/bob and false ancestor containment. - expect(isHome(process.cwd(), executionHostRemovalHome('C:/Users/bob'))).toBe(false) - }) - - it('honours a Windows execution-host home from a POSIX client', () => { - expect( - withProcessPlatform('darwin', () => - isHome('C:\\Users\\bob\\OneDrive', executionHostRemovalHome('C:\\Users\\bob\\OneDrive')) - ) - ).toBe(true) - }) -}) - -describe('path ops chosen from the worktree/repo pair', () => { - it('still recognises a POSIX home when the repo path drags the pair into win32 ops', () => { - homedirMock.mockReturnValue('/Users/ci') - expect(isHomeForPair('/home/alice', '//nas/share/repo', CLIENT_REMOVAL_HOME)).toBe(true) - expect(isHomeForPair('/home', '//nas/share/repo', CLIENT_REMOVAL_HOME)).toBe(true) - expect(isHomeForPair('/root', 'C:\\src\\repo', CLIENT_REMOVAL_HOME)).toBe(true) - }) - - it('still recognises the client home itself under the same contaminated ops', () => { - homedirMock.mockReturnValue('/srv/homes/ci') - expect( - withProcessPlatform('linux', () => - isHomeForPair('/srv/homes/ci', '//nas/share/repo', CLIENT_REMOVAL_HOME) - ) - ).toBe(true) - expect( - withProcessPlatform('linux', () => - isHomeForPair('/srv/homes/ci', 'C:\\src\\repo', CLIENT_REMOVAL_HOME) - ) - ).toBe(true) - }) - - it('still recognises an execution-host home under the same contaminated ops', () => { - expect( - isHomeForPair( - '/srv/homes/alice', - 'C:\\src\\repo', - executionHostRemovalHome('/srv/homes/alice') - ) - ).toBe(true) - }) - - it('keeps a linked worktree deletable when the pair is mixed-syntax', () => { - homedirMock.mockReturnValue('/srv/homes/ci') - expect( - withProcessPlatform('linux', () => - isHomeForPair('/srv/homes/ci/wt/feature', '//nas/share/repo', CLIENT_REMOVAL_HOME) - ) - ).toBe(false) - expect(isHomeForPair('/opt/src/checkout', '//nas/share/repo', CLIENT_REMOVAL_HOME)).toBe(false) - }) -}) diff --git a/src/main/wsl/discovery/wsl-background-distro-gate.test.ts b/src/main/wsl/discovery/wsl-background-distro-gate.test.ts index 428a641495f..ed700afa060 100644 --- a/src/main/wsl/discovery/wsl-background-distro-gate.test.ts +++ b/src/main/wsl/discovery/wsl-background-distro-gate.test.ts @@ -9,21 +9,12 @@ vi.mock('./distro-catalog', () => wslMocks) import { _resetWslBackgroundDistroGateForTests, - deferUntilWslDistroRunning, - isWslDistroRunning, - isWslDistroRunningForBackgroundWork, noteWslDistroMayHaveStopped, noteWslDistroWoken, - noteWslDistrosRunning, - onWslDistroGateNote, - readSettledConfirmedRunningWslDistros, - WSL_STOP_SETTLE_MS + onWslDistroGateNote } from './wsl-background-distro-gate' import { isWslUserActFor, runAsWslUserAct } from './wsl-user-act-scope' -import { - _resetRunningWslDistroCacheForTests, - resolveRunningWslDistros -} from './wsl-running-distro-cache' +import { _resetRunningWslDistroCacheForTests } from './wsl-running-distro-cache' const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') @@ -43,170 +34,6 @@ afterEach(() => { vi.resetAllMocks() }) -describe('isWslDistroRunning', () => { - it('reads a distro as stopped when the probe fails, not as its last-known state', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - let probe: () => Promise = async () => ['Ubuntu'] - wslMocks.listRunningWslDistrosAsync.mockImplementation((options) => - resolveRunningWslDistros(() => probe(), options) - ) - await expect(isWslDistroRunning('Ubuntu')).resolves.toBe(true) - - probe = () => Promise.reject(new Error('wsl.exe wedged')) - await expect(isWslDistroRunning('Ubuntu')).resolves.toBe(false) - await expect(isWslDistroRunning('Ubuntu')).resolves.toBe(false) - }) -}) - -describe('the stop settle window', () => { - it('starts no running read inside the window, even when a timer fires early', async () => { - // Node timers can wake ~2ms short; firing far earlier makes a single sleep fail every time. - const realSetTimeout = globalThis.setTimeout - vi.spyOn(globalThis, 'setTimeout').mockImplementation((handler, ms, ...args) => - realSetTimeout(handler, Math.max(0, (ms ?? 0) - 100), ...args) - ) - const probeStarts: number[] = [] - wslMocks.listRunningWslDistrosAsync.mockImplementation((options) => - resolveRunningWslDistros(async () => { - probeStarts.push(performance.now()) - return [] - }, options) - ) - const settledAt = performance.now() + WSL_STOP_SETTLE_MS - noteWslDistroMayHaveStopped('Ubuntu') - - await expect(isWslDistroRunning('Ubuntu')).resolves.toBe(false) - expect(probeStarts).toHaveLength(1) - expect(probeStarts[0]).toBeGreaterThanOrEqual(settledAt) - }) -}) - -describe('readSettledConfirmedRunningWslDistros', () => { - it('never answers from a probe that started inside the window, even one still in flight', async () => { - let finishStale: (distros: string[]) => void = () => {} - const probe = vi - .fn<() => Promise>() - .mockImplementationOnce(() => new Promise((resolve) => (finishStale = resolve))) - .mockResolvedValueOnce([]) - wslMocks.listRunningWslDistrosAsync.mockImplementation((options) => - resolveRunningWslDistros(probe, options) - ) - const stale = isWslDistroRunning('Ubuntu') - await vi.waitFor(() => expect(probe).toHaveBeenCalledOnce()) - - const settled = readSettledConfirmedRunningWslDistros('Ubuntu', performance.now()) - finishStale(['Ubuntu']) - - await expect(stale).resolves.toBe(true) - await expect(settled).resolves.toEqual({ status: 'confirmed', distros: [] }) - expect(probe).toHaveBeenCalledTimes(2) - }) -}) - -describe('resolveRunningWslDistros startedAfter', () => { - it('answers from a confirmed read that started after the anchor, and reads again for a later one', async () => { - const probe = vi.fn(async () => ['Ubuntu']) - const anchor = performance.now() - await resolveRunningWslDistros(probe) - await expect(resolveRunningWslDistros(probe, { startedAfter: anchor })).resolves.toEqual([ - 'Ubuntu' - ]) - expect(probe).toHaveBeenCalledTimes(1) - await resolveRunningWslDistros(probe, { startedAfter: performance.now() }) - expect(probe).toHaveBeenCalledTimes(2) - }) - - it('never answers an anchored caller from a failed read', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const anchor = performance.now() - await resolveRunningWslDistros(() => Promise.reject(new Error('wsl.exe wedged'))) - await expect( - resolveRunningWslDistros(async () => ['Ubuntu'], { - startedAfter: anchor, - requireConfirmed: true - }) - ).rejects.toThrow() - }) -}) - -describe('deferUntilWslDistroRunning cancel', () => { - it('drops the task it registered, but not a newer one under the same key', () => { - const first = vi.fn() - const second = vi.fn() - const cancelFirst = deferUntilWslDistroRunning('Ubuntu', 'k', first) - const cancelSecond = deferUntilWslDistroRunning('Ubuntu', 'k', second) - cancelFirst() - noteWslDistrosRunning(['Ubuntu']) - expect(second).toHaveBeenCalledTimes(1) - const third = vi.fn() - deferUntilWslDistroRunning('Ubuntu', 'k', third) - cancelSecond() - cancelFirst() - noteWslDistrosRunning(['Ubuntu']) - expect(third).toHaveBeenCalledTimes(1) - expect(first).not.toHaveBeenCalled() - }) -}) - -describe('isWslDistroRunningForBackgroundWork', () => { - it('checks the default distro when none is named', async () => { - await expect(isWslDistroRunningForBackgroundWork(null)).resolves.toBe(false) - wslMocks.listWslDistrosAsync.mockResolvedValue(['Ubuntu']) - await expect(isWslDistroRunningForBackgroundWork(undefined)).resolves.toBe(true) - }) - - it('treats a host with no distros, or no WSL at all, as not running', async () => { - wslMocks.listWslDistrosAsync.mockResolvedValue([]) - await expect(isWslDistroRunningForBackgroundWork(null)).resolves.toBe(false) - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - await expect(isWslDistroRunningForBackgroundWork('Ubuntu')).resolves.toBe(false) - expect(wslMocks.listRunningWslDistrosAsync).not.toHaveBeenCalled() - }) -}) - -describe('deferUntilWslDistroRunning', () => { - it('runs deferred work once, when its distro is seen running', () => { - const ubuntuTask = vi.fn() - const debianTask = vi.fn() - deferUntilWslDistroRunning('Ubuntu', 'work', ubuntuTask) - deferUntilWslDistroRunning('Debian', 'work', debianTask) - - noteWslDistrosRunning(['UBUNTU']) - noteWslDistrosRunning(['Ubuntu']) - - expect(ubuntuTask).toHaveBeenCalledTimes(1) - expect(debianTask).not.toHaveBeenCalled() - }) - - it('drains on a confirmed running-distro probe but not on a failed one', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const task = vi.fn() - deferUntilWslDistroRunning('Ubuntu', 'work', task) - - await resolveRunningWslDistros(() => Promise.reject(new Error('wsl.exe wedged'))) - expect(task).not.toHaveBeenCalled() - - _resetRunningWslDistroCacheForTests() - await resolveRunningWslDistros(async () => ['Ubuntu']) - expect(task).toHaveBeenCalledTimes(1) - }) - - it('isolates a failing task from the rest of the drain', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const after = vi.fn() - deferUntilWslDistroRunning('Ubuntu', 'throws', () => { - throw new Error('boom') - }) - deferUntilWslDistroRunning('Ubuntu', 'rejects', () => Promise.reject(new Error('later'))) - deferUntilWslDistroRunning('Ubuntu', 'after', after) - - noteWslDistrosRunning(['Ubuntu']) - await vi.waitFor(() => expect(warn).toHaveBeenCalledTimes(2)) - - expect(after).toHaveBeenCalledTimes(1) - }) -}) - describe('gate note listeners (E9)', () => { it("never run inside the user act whose wake or stop they hear, so their work can't borrow it", async () => { const insideAct: boolean[] = [] diff --git a/src/main/wsl/discovery/wsl-background-exec-gate.test.ts b/src/main/wsl/discovery/wsl-background-exec-gate.test.ts index fa93ff1f819..5617fa0387f 100644 --- a/src/main/wsl/discovery/wsl-background-exec-gate.test.ts +++ b/src/main/wsl/discovery/wsl-background-exec-gate.test.ts @@ -24,11 +24,7 @@ vi.mock('./wsl-background-distro-gate', () => ({ noteWslDistroMayHaveStopped: vi.fn() })) -import { - assertWslDistroRunningForExec, - blockedWslDistroForExec, - runAsWslExecUserAct -} from './wsl-background-exec-gate' +import { runAsWslExecUserAct } from './wsl-background-exec-gate' import { resetWslDefaultDistroForTests, resolveWslDefaultDistro } from './wsl-default-distro' const UBUNTU_ID = '0e3a7f2c-1b4d-4c5e-9f60-7a8b9c0d1e2f' @@ -65,99 +61,6 @@ describe('blockedWslDistroForExec', () => { Object.defineProperty(process, 'platform', { value: platform }) }) - it('refuses an unnamed run when the default distro cannot be read', async () => { - runProcess.mockResolvedValue({ code: 1, stdout: '' }) - await expect(blockedWslDistroForExec(null)).resolves.toEqual({ - distro: 'the default distro', - state: 'unverifiable' - }) - await expect(assertWslDistroRunningForExec(undefined)).rejects.toMatchObject({ - code: 'WSL_DISTRO_UNVERIFIABLE' - }) - expect(readWslDistroRunningState).not.toHaveBeenCalled() - }) - - it('refuses when the registry read throws or names no registered default', async () => { - runProcess.mockRejectedValueOnce(new Error('timed out')) - await expect(blockedWslDistroForExec(null)).resolves.toMatchObject({ state: 'unverifiable' }) - resetWslDefaultDistroForTests() - runProcess.mockResolvedValueOnce({ code: 0, stdout: lxss(null, [[UBUNTU_ID, 'Ubuntu']]) }) - await expect(blockedWslDistroForExec(null)).resolves.toMatchObject({ state: 'unverifiable' }) - }) - - it('gates the current default, read fresh after a set-default', async () => { - const both: [string, string][] = [ - [UBUNTU_ID, 'Ubuntu'], - [DEBIAN_ID, 'Debian'] - ] - readWslDistroRunningState.mockImplementation(async (distro: string) => - distro === 'Debian' ? 'stopped' : 'running' - ) - runProcess.mockResolvedValueOnce({ code: 0, stdout: lxss(UBUNTU_ID, both) }) - await expect(blockedWslDistroForExec(null)).resolves.toBeNull() - // A list read that saw the change invalidates the short-lived default. - cachedList.current = ['Debian', 'Ubuntu'] - runProcess.mockResolvedValueOnce({ code: 0, stdout: lxss(DEBIAN_ID, both) }) - await expect(blockedWslDistroForExec(null)).resolves.toEqual({ - distro: 'Debian', - state: 'stopped' - }) - }) - - it('allows an unnamed run when no distro is registered: wsl.exe has nothing to start', async () => { - runProcess.mockResolvedValue({ code: 0, stdout: lxss(null, []) }) - await expect(blockedWslDistroForExec(null)).resolves.toBeNull() - }) - - it('a named distro skips the registry read', async () => { - readWslDistroRunningState.mockResolvedValue('stopped') - await expect(blockedWslDistroForExec(' Ubuntu ')).resolves.toEqual({ - distro: 'Ubuntu', - state: 'stopped' - }) - expect(runProcess).not.toHaveBeenCalled() - }) - - it('a user act on an unresolved default passes inside the act only', async () => { - runProcess.mockResolvedValue({ code: 1, stdout: '' }) - await expect(runAsWslExecUserAct(null, () => blockedWslDistroForExec(null))).resolves.toBeNull() - await expect(blockedWslDistroForExec(null)).resolves.toMatchObject({ state: 'unverifiable' }) - }) - - it('names the default from wsl --list when only the registry is blocked', async () => { - runProcess.mockResolvedValue({ code: 1, stdout: '' }) - listWslDistrosAsync.mockResolvedValue(['Ubuntu', 'Debian']) - readWslDistroRunningState.mockResolvedValue('stopped') - await expect(blockedWslDistroForExec(null)).resolves.toEqual({ - distro: 'Ubuntu', - state: 'stopped' - }) - }) - - it('a user act and every gate inside it agree on one default, even if the registry flips', async () => { - // The registry answers once, then is blocked (policy, timeout); wsl.exe still lists distros. - runProcess.mockResolvedValueOnce({ - code: 0, - stdout: lxss(DEBIAN_ID, [ - [UBUNTU_ID, 'Ubuntu'], - [DEBIAN_ID, 'Debian'] - ]) - }) - runProcess.mockResolvedValue({ code: 1, stdout: '' }) - listWslDistrosAsync.mockResolvedValue(['Ubuntu']) - readWslDistroRunningState.mockResolvedValue('stopped') - const inside = await runAsWslExecUserAct(null, async () => { - resetWslDefaultDistroForTests() - // The hook relay names the default itself, then gates it by name. - const named = await resolveWslDefaultDistro() - return { - named, - relayGate: await blockedWslDistroForExec(typeof named === 'string' ? named : null) - } - }) - expect(inside).toEqual({ named: 'Debian', relayGate: null }) - }) - it('work an unnamed act left behind reads the default fresh once the act settles', async () => { const both: [string, string][] = [ [UBUNTU_ID, 'Ubuntu'], @@ -179,22 +82,4 @@ describe('blockedWslDistroForExec', () => { release() await expect(later).resolves.toBe('Ubuntu') }) - - it('shares one registry read across a burst of unnamed checks within its TTL', async () => { - runProcess.mockResolvedValue({ code: 0, stdout: lxss(UBUNTU_ID, [[UBUNTU_ID, 'Ubuntu']]) }) - await Promise.all([1, 2, 3].map(() => blockedWslDistroForExec(null))) - await blockedWslDistroForExec(undefined) - expect(runProcess).toHaveBeenCalledTimes(1) - const now = performance.now() - vi.spyOn(performance, 'now').mockReturnValue(now + 6_000) - await blockedWslDistroForExec(null) - expect(runProcess).toHaveBeenCalledTimes(2) - vi.restoreAllMocks() - }) - - it('never reads the registry off Windows', async () => { - Object.defineProperty(process, 'platform', { value: 'darwin' }) - await expect(blockedWslDistroForExec(null)).resolves.toBeNull() - expect(runProcess).not.toHaveBeenCalled() - }) }) diff --git a/src/main/wsl/execution/wsl-interop-health.test.ts b/src/main/wsl/execution/wsl-interop-health.test.ts deleted file mode 100644 index dcfd6957b38..00000000000 --- a/src/main/wsl/execution/wsl-interop-health.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('../discovery/distro-catalog', () => ({ - listWslDistrosAsync: vi.fn() -})) -vi.mock('../discovery/wsl-background-distro-gate', () => ({ isWslDistroRunning: vi.fn() })) -vi.mock('./wsl-runner', () => ({ runWslProcess: vi.fn() })) - -import { - ACTIVITY_CHECK_INTERVAL_MS, - REPAIR_FAILURE_BACKOFF_MS, - STOP_CHECK_FLOOR_MS, - WslInteropHealthMonitor, - type WslInteropHealthDeps -} from './wsl-interop-health' - -import { WSL_INTEROP_PROBE_SCRIPT, WSL_INTEROP_REPAIR_SCRIPT } from './wsl-interop-registration' - -const PRESENT = 'orca-wsl-interop:present\n' -const MISSING = 'orca-wsl-interop:missing\norca-wsl-interop:conf\n' -const MISSING_DISABLED = `${MISSING}[interop]\nenabled=false\n` - -function harness(overrides: Partial = {}) { - let now = 1_000_000 - const timers: { fn: () => void; delayMs: number }[] = [] - let stopListener: ((stopped: string[], running: string[]) => void) | null = null - const deps: WslInteropHealthDeps = { - platform: () => 'win32', - isRunning: vi.fn(async (distro: string) => distro === 'Ubuntu'), - resolveDefaultDistro: vi.fn(async () => 'Ubuntu'), - runScript: vi.fn(async () => ({ code: 0, stdout: PRESENT })), - subscribeStops: (listener) => { - stopListener = listener - return () => { - stopListener = null - } - }, - now: () => now, - schedule: (fn, delayMs) => { - timers.push({ fn, delayMs }) - }, - log: vi.fn(), - ...overrides - } - const monitor = new WslInteropHealthMonitor(deps) - return { - deps, - monitor, - timers, - advance: (ms: number) => { - now += ms - }, - runTimers: () => { - for (const timer of timers.splice(0)) { - timer.fn() - } - }, - emitStop: (stopped: string[], running: string[]) => stopListener?.(stopped, running) - } -} - -const flush = () => new Promise((resolve) => setTimeout(resolve, 0)) - -describe('WslInteropHealthMonitor.check', () => { - it('repairs as root when the entry is missing', async () => { - const runScript = vi - .fn() - .mockResolvedValueOnce({ code: 0, stdout: MISSING }) - .mockResolvedValueOnce({ code: 0, stdout: 'orca-wsl-interop:repaired\n' }) - const h = harness({ runScript }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('repaired') - expect(runScript).toHaveBeenLastCalledWith('Ubuntu', WSL_INTEROP_REPAIR_SCRIPT, 'root') - expect(h.deps.log).toHaveBeenCalledWith(expect.stringContaining('wsl --update')) - }) - - it('respects interop disabled in wsl.conf', async () => { - const runScript = vi.fn(async () => ({ code: 0, stdout: MISSING_DISABLED })) - const h = harness({ runScript }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('interop-disabled') - expect(runScript).toHaveBeenCalledTimes(1) - }) - - it('never runs inside a distro that is not running', async () => { - const h = harness({ isRunning: vi.fn(async (distro: string) => distro === 'Debian') }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('not-running') - expect(h.deps.runScript).not.toHaveBeenCalled() - }) - - it('treats an unconfirmed running list as not running', async () => { - const h = harness({ - isRunning: vi.fn(async () => { - throw new Error('unavailable') - }) - }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('not-running') - expect(h.deps.runScript).not.toHaveBeenCalled() - }) - - it('is single-flight per distro', async () => { - let release: (value: { code: number; stdout: string }) => void = () => undefined - const runScript = vi.fn( - () => - new Promise<{ code: number; stdout: string }>((resolve) => { - release = resolve - }) - ) - const h = harness({ runScript }) - const first = h.monitor.check('Ubuntu') - const second = h.monitor.check('ubuntu') - expect(second).toBe(first) - await flush() - release({ code: 0, stdout: PRESENT }) - await expect(first).resolves.toBe('intact') - expect(runScript).toHaveBeenCalledTimes(1) - }) - - it('backs off after a failed repair', async () => { - const runScript = vi.fn(async (_distro: string, script: string) => - script === WSL_INTEROP_PROBE_SCRIPT ? { code: 0, stdout: MISSING } : { code: 1, stdout: '' } - ) - const h = harness({ runScript }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('repair-failed') - await expect(h.monitor.check('Ubuntu')).resolves.toBe('repair-failed') - expect(runScript).toHaveBeenCalledTimes(3) - h.advance(REPAIR_FAILURE_BACKOFF_MS) - await h.monitor.check('Ubuntu') - expect(runScript).toHaveBeenCalledTimes(5) - }) - - it('reports unknown when the probe throws', async () => { - const h = harness({ - runScript: vi.fn(async () => { - throw new Error('timeout') - }) - }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('unknown') - }) -}) - -describe('WslInteropHealthMonitor triggers', () => { - it('does nothing off Windows', async () => { - const h = harness({ platform: () => 'darwin' }) - h.monitor.noteActivity('Ubuntu') - await flush() - expect(h.timers).toHaveLength(0) - }) - - it('re-checks used distros that are still running when another distro stops', async () => { - const h = harness() - h.monitor.noteActivity('Ubuntu') - await flush() - h.runTimers() - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(1) - h.advance(10_000) - h.emitStop(['docker-desktop'], ['Ubuntu']) - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(2) - // The list that reported the stop can still name a stopping distro: the re-check reads again. - expect(h.deps.isRunning).toHaveBeenCalledTimes(2) - h.advance(10_000) - h.emitStop(['Ubuntu'], []) - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(2) - }) - - it('bounds probes under bursts of activity and stop events', async () => { - const h = harness() - for (let i = 0; i < 50; i++) { - h.monitor.noteActivity('Ubuntu') - } - await flush() - h.runTimers() - await flush() - for (let elapsed = 0; elapsed < ACTIVITY_CHECK_INTERVAL_MS - 1_000; elapsed += 1_000) { - h.advance(1_000) - h.monitor.noteActivity('Ubuntu') - await flush() - h.runTimers() - await flush() - } - expect(h.deps.runScript).toHaveBeenCalledTimes(1) - - // Stop-triggered checks are rate-floored and skip distros the list no longer shows. - h.emitStop(['docker-desktop'], ['Ubuntu']) - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(2) - h.advance(STOP_CHECK_FLOOR_MS - 1) - h.emitStop(['Debian'], ['Ubuntu']) - h.emitStop(['Debian'], ['Ubuntu']) - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(2) - h.advance(1) - h.emitStop(['Ubuntu'], []) - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(2) - }) - - it('never probes a distro a stop event lists but a settled read finds stopping (E9)', async () => { - const isRunning = vi.fn(async () => true) - const h = harness({ isRunning }) - h.monitor.noteActivity('Ubuntu') - await flush() - h.runTimers() - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(1) - h.advance(10_000) - isRunning.mockResolvedValue(false) - h.emitStop(['docker-desktop'], ['Ubuntu']) - await flush() - expect(h.deps.runScript).toHaveBeenCalledTimes(1) - }) - - it('skips the root repair when the distro stops after the probe (E9)', async () => { - const isRunning = vi.fn().mockResolvedValueOnce(true).mockResolvedValue(false) - const runScript = vi.fn(async () => ({ code: 0, stdout: MISSING })) - const h = harness({ isRunning, runScript }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('not-running') - expect(runScript).toHaveBeenCalledTimes(1) - expect(runScript).toHaveBeenCalledWith('Ubuntu', WSL_INTEROP_PROBE_SCRIPT) - }) - - it('treats an entry restored between probe and repair as intact', async () => { - const h = harness({ - runScript: vi.fn(async (_distro: string, script: string) => ({ - code: 0, - stdout: script === WSL_INTEROP_PROBE_SCRIPT ? MISSING : PRESENT - })) - }) - await expect(h.monitor.check('Ubuntu')).resolves.toBe('intact') - expect(h.deps.log).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/wsl/filesystem/wsl-drive-project-windows-git.test.ts b/src/main/wsl/filesystem/wsl-drive-project-windows-git.test.ts deleted file mode 100644 index ac02aead88c..00000000000 --- a/src/main/wsl/filesystem/wsl-drive-project-windows-git.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - resolveProjectExecutionRuntime, - type LocalWindowsRuntimePreference -} from '../../../shared/project-execution-runtime' -import type { Project } from '../../../shared/project-types' -import type { Repo } from '../../../shared/repo-types' -import { - convertWslDriveProjectToWindowsGit, - previewWslDriveProjectWindowsGit, - type WslDriveProjectDeps -} from './wsl-drive-project-windows-git' - -const REPO_PATH = String.raw`C:\src\app` - -function setup( - options: { - preference?: LocalWindowsRuntimePreference - globalDistro?: string | null - repo?: Partial - links?: string[] - windowsAutocrlf?: string | null - localAutocrlf?: string | null - gitMissing?: boolean - distros?: string[] - } = {} -) { - const project: Project = { - id: 'p1', - displayName: 'app', - badgeColor: '#000', - sourceRepoIds: ['r1'], - createdAt: 0, - updatedAt: 0, - ...(options.preference ? { localWindowsRuntimePreference: options.preference } : {}) - } - const repo: Repo = { - id: 'r1', - displayName: 'app', - path: REPO_PATH, - badgeColor: '#000', - addedAt: 0, - ...options.repo - } - const runWindowsGit = vi.fn(async (args: string[], _cwd: string) => { - if (options.gitMissing) { - throw Object.assign(new Error('spawn git ENOENT'), { code: 'ENOENT' }) - } - const key = args.join(' ') - if (key === '--version') { - return 'git version 2.47.1.windows.1\n' - } - if (key === 'rev-parse --git-common-dir') { - return '.git\n' - } - const configValue = - key === 'config --get core.autocrlf' - ? options.windowsAutocrlf - : key === 'config --local --get core.autocrlf' - ? options.localAutocrlf - : undefined - if (configValue !== undefined) { - if (configValue === null) { - throw Object.assign(new Error('exit 1'), { code: 1 }) - } - return `${configValue}\n` - } - return '' - }) - const readWorktreeLinks = vi.fn(async () => options.links ?? []) - const deps: WslDriveProjectDeps = { - getProjects: () => [project], - getRepos: () => [repo], - resolveRuntime: (entry) => - resolveProjectExecutionRuntime({ - appPlatform: 'win32', - projectId: entry.id, - projectRuntimePreference: entry.localWindowsRuntimePreference, - globalWindowsRuntimeDefault: - options.globalDistro === undefined - ? { kind: 'windows-host' } - : { kind: 'wsl', distro: options.globalDistro }, - wslAvailable: true, - availableWslDistros: options.distros ?? ['Ubuntu'] - }), - runWindowsGit, - readWorktreeLinks - } - return { deps, runWindowsGit, readWorktreeLinks } -} - -describe('converting a WSL project on a Windows drive to Windows Git', () => { - it('keeps WSL for terminals and switches only Git, for a project override', async () => { - const { deps } = setup({ preference: { kind: 'wsl', distro: 'Ubuntu' } }) - await expect( - convertWslDriveProjectToWindowsGit(deps, 'p1', { alignLineEndings: false }) - ).resolves.toEqual({ - ok: true, - preference: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' }, - alignedLineEndingRepoIds: [] - }) - }) - - it('pins the global default distro on a project that inherits it', async () => { - const { deps } = setup({ globalDistro: 'Ubuntu' }) - await expect( - convertWslDriveProjectToWindowsGit(deps, 'p1', { alignLineEndings: false }) - ).resolves.toMatchObject({ - preference: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' } - }) - }) - - it('refuses a repo with worktrees WSL Git made, naming them, and changes nothing', async () => { - const { deps, runWindowsGit, readWorktreeLinks } = setup({ - preference: { kind: 'wsl', distro: 'Ubuntu' }, - links: [ - 'C:/src/app-feature/.git', - // Windows Git reaches a worktree inside the distro over UNC; that link is its own. - '//wsl.localhost/Ubuntu/home/me/trees/app-unc/.git', - '/home/me/orca/workspaces/app/fix/.git', - '/mnt/c/src/app-wsl/.git' - ] - }) - await expect( - convertWslDriveProjectToWindowsGit(deps, 'p1', { alignLineEndings: true }) - ).resolves.toEqual({ - ok: false, - blockers: [ - { - kind: 'wsl-authored-worktrees', - repoId: 'r1', - paths: ['/home/me/orca/workspaces/app/fix', '/mnt/c/src/app-wsl'] - } - ] - }) - expect(readWorktreeLinks).toHaveBeenCalledWith(String.raw`C:\src\app\.git`) - expect(runWindowsGit).not.toHaveBeenCalledWith( - ['config', '--local', 'core.autocrlf', 'true'], - REPO_PATH - ) - }) - - it.each([ - [ - 'a folder inside the distro', - { repo: { path: String.raw`\\wsl.localhost\Ubuntu\home\me\app` } }, - { kind: 'not-windows-drive', repoId: 'r1' } - ], - [ - 'a worktree folder inside the distro', - { repo: { worktreeBasePath: String.raw`\\wsl.localhost\Ubuntu\home\me\trees` } }, - { kind: 'worktree-folder-in-distro', repoId: 'r1' } - ], - ['no Windows Git', { gitMissing: true }, { kind: 'windows-git-missing' }] - ])('refuses %s', async (_case, extra, blocker) => { - const { deps } = setup({ - preference: { kind: 'wsl', distro: 'Ubuntu' }, - ...extra - }) - await expect(previewWslDriveProjectWindowsGit(deps, 'p1')).resolves.toMatchObject({ - blockers: [blocker] - }) - await expect( - convertWslDriveProjectToWindowsGit(deps, 'p1', { alignLineEndings: false }) - ).resolves.toEqual({ ok: false, blockers: [blocker] }) - }) - - it('leaves a folder repo out: it runs no Git, so there is nothing to check', async () => { - const { deps, runWindowsGit } = setup({ - preference: { kind: 'wsl', distro: 'Ubuntu' }, - repo: { kind: 'folder', path: String.raw`\\wsl.localhost\Ubuntu\home\me\notes` } - }) - await expect(previewWslDriveProjectWindowsGit(deps, 'p1')).resolves.toMatchObject({ - repos: [], - blockers: [] - }) - expect(runWindowsGit).not.toHaveBeenCalled() - }) - - it.each([ - ['a Windows runtime', { preference: { kind: 'windows-host' } as const }, 'not-wsl-runtime'], - [ - 'an already converted project', - { preference: { kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' } as const }, - 'not-wsl-runtime' - ], - [ - 'a distro that is gone', - { preference: { kind: 'wsl', distro: 'Ubuntu' } as const, distros: ['Debian'] }, - 'runtime-needs-repair' - ] - ])('has nothing to convert for %s', async (_case, extra, kind) => { - const { deps } = setup(extra) - await expect(previewWslDriveProjectWindowsGit(deps, 'p1')).resolves.toMatchObject({ - blockers: [{ kind }] - }) - }) - - it('writes autocrlf into the repo only when asked and Windows Git uses it', async () => { - const asked = setup({ - preference: { kind: 'wsl', distro: 'Ubuntu' }, - windowsAutocrlf: 'true', - localAutocrlf: null - }) - await expect( - convertWslDriveProjectToWindowsGit(asked.deps, 'p1', { alignLineEndings: true }) - ).resolves.toMatchObject({ ok: true, alignedLineEndingRepoIds: ['r1'] }) - expect(asked.runWindowsGit).toHaveBeenCalledWith( - ['config', '--local', 'core.autocrlf', 'true'], - REPO_PATH - ) - - const notAsked = setup({ - preference: { kind: 'wsl', distro: 'Ubuntu' }, - windowsAutocrlf: 'true', - localAutocrlf: null - }) - await convertWslDriveProjectToWindowsGit(notAsked.deps, 'p1', { alignLineEndings: false }) - const alreadySet = setup({ - preference: { kind: 'wsl', distro: 'Ubuntu' }, - windowsAutocrlf: 'true', - localAutocrlf: 'false' - }) - await convertWslDriveProjectToWindowsGit(alreadySet.deps, 'p1', { alignLineEndings: true }) - for (const { runWindowsGit } of [notAsked, alreadySet]) { - expect(runWindowsGit).not.toHaveBeenCalledWith( - ['config', '--local', 'core.autocrlf', 'true'], - REPO_PATH - ) - } - }) - - it('previews the line-ending settings the dialog offers to align', async () => { - const { deps } = setup({ - preference: { kind: 'wsl', distro: 'Ubuntu' }, - windowsAutocrlf: 'true', - localAutocrlf: null - }) - await expect(previewWslDriveProjectWindowsGit(deps, 'p1')).resolves.toEqual({ - projectId: 'p1', - distro: 'Ubuntu', - repos: [{ repoId: 'r1', path: REPO_PATH, windowsAutocrlf: 'true', localAutocrlf: null }], - blockers: [] - }) - }) -}) diff --git a/src/main/wsl/filesystem/wsl-drive-unc-project-scope.test.ts b/src/main/wsl/filesystem/wsl-drive-unc-project-scope.test.ts deleted file mode 100644 index 4add60821cc..00000000000 --- a/src/main/wsl/filesystem/wsl-drive-unc-project-scope.test.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import type { Repo } from '../../../shared/repo-types' -import type { WindowsDriveMount } from '../../runtime/wsl-guest-drive-mountinfo' -import { collectWslDriveUncScope, wslDriveUncWorktreeId } from './wsl-drive-unc-project-scope' -import { wslUncDrivePathToWindows } from '../../../shared/wsl-paths' - -function repo(id: string, path: string, extra: Partial = {}): Repo { - return { id, displayName: id, path, badgeColor: '', addedAt: 0, ...extra } -} - -function folder(id: string, folderPath: string): FolderWorkspace { - return { - id, - projectGroupId: 'g1', - name: id, - folderPath, - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } -} - -const DRIVES: WindowsDriveMount[] = [ - { mountPoint: '/mnt/c', windowsRoot: 'C:\\' }, - { mountPoint: '/mnt/d', windowsRoot: 'D:\\' } -] - -describe('wslUncDrivePathToWindows', () => { - it.each([ - [String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app`, String.raw`C:\src\app`], - ['//wsl$/ubuntu/mnt/D/work/', String.raw`D:\work`], - // `/MNT` is an ordinary, case-sensitive Linux folder, as foldWslUncPathCaseInsensitiveParts says. - ['//wsl$/ubuntu/MNT/d/work/', null], - [String.raw`\\wsl.localhost\Ubuntu\mnt\c`, 'C:\\'], - [String.raw`\\wsl.localhost\Ubuntu\home\me\app`, null], - [String.raw`\\wsl.localhost\Debian\mnt\c\src\app`, null], - [String.raw`C:\src\app`, null] - ])('%s → %s', (path, expected) => { - expect(wslUncDrivePathToWindows(path, 'Ubuntu')).toBe(expected) - }) -}) - -describe('collectWslDriveUncScope', () => { - it('takes local drive-path projects and refuses mixed, remote and duplicate ones', () => { - const repos = [ - repo('drive', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app`, { - worktreeBasePath: 'trees' - }), - repo('mixed', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\mixed`, { - worktreeBasePath: String.raw`\\wsl.localhost\Ubuntu\home\me\trees` - }), - repo('remote', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\remote`, { - executionHostId: 'runtime:env-1' - }), - repo('dup', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\dup`), - repo('already', String.raw`c:\SRC\dup`), - repo('home', String.raw`\\wsl.localhost\Ubuntu\home\me\app`) - ] - expect( - collectWslDriveUncScope( - { - repos, - folderWorkspaces: [folder('f1', String.raw`\\wsl.localhost\Ubuntu\mnt\d\notes`)], - projectGroups: [] - }, - 'Ubuntu', - DRIVES - ) - ).toEqual({ - repoIds: ['drive'], - folderWorkspaceIds: ['f1'], - refused: [ - { kind: 'repo', id: 'mixed', reason: 'mixed-locations' }, - { kind: 'repo', id: 'remote', reason: 'not-local' }, - { kind: 'repo', id: 'dup', reason: 'duplicate-windows-project' } - ] - }) - }) -}) - -describe('collectWslDriveUncScope: one folder, one project', () => { - it('converts one UNC spelling of a drive folder and refuses the others as duplicates', () => { - const state = { - repos: [ - repo('first', String.raw`\\wsl$\Ubuntu\mnt\c\src\app`), - repo('alias', '//wsl.localhost/ubuntu/mnt/c/src/app/') - ], - folderWorkspaces: [ - folder('f-first', String.raw`\\wsl.localhost\Ubuntu\mnt\d\notes`), - folder('f-alias', '//wsl$/ubuntu/mnt/d/notes/'), - folder('f-drive', String.raw`D:\docs`), - folder('f-taken', String.raw`\\wsl.localhost\Ubuntu\mnt\d\docs`) - ], - projectGroups: [] - } - expect(collectWslDriveUncScope(state, 'Ubuntu', DRIVES)).toEqual({ - repoIds: ['first'], - folderWorkspaceIds: ['f-first'], - refused: [ - { kind: 'repo', id: 'alias', reason: 'duplicate-windows-project' }, - { kind: 'folder-workspace', id: 'f-alias', reason: 'duplicate-windows-project' }, - { kind: 'folder-workspace', id: 'f-taken', reason: 'duplicate-windows-project' } - ] - }) - }) -}) - -describe('collectWslDriveUncScope: only real Windows drive folders', () => { - const state = { - repos: [ - repo('drive', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app`), - repo('ext4', String.raw`\\wsl.localhost\Ubuntu\mnt\e\src\app`), - repo('bind', String.raw`\\wsl.localhost\Ubuntu\mnt\c\shared\app`) - ], - folderWorkspaces: [folder('f-ext4', String.raw`\\wsl.localhost\Ubuntu\mnt\e\notes`)], - projectGroups: [] - } - - it('refuses a /mnt/ folder the distro does not mount from that Windows drive', () => { - const mounts: WindowsDriveMount[] = [ - ...DRIVES, - // A subfolder bind mount: its Windows folder is unknown, so it cannot be the drive path. - { mountPoint: '/mnt/c/shared', windowsRoot: null } - ] - expect(collectWslDriveUncScope(state, 'Ubuntu', mounts)).toEqual({ - repoIds: ['drive'], - folderWorkspaceIds: [], - refused: [ - { kind: 'repo', id: 'ext4', reason: 'not-windows-drive-mount' }, - { kind: 'repo', id: 'bind', reason: 'not-windows-drive-mount' }, - { kind: 'folder-workspace', id: 'f-ext4', reason: 'not-windows-drive-mount' } - ] - }) - }) - - it('refuses a drive mounted under another letter, and everything when the mounts are unknown', () => { - const swapped: WindowsDriveMount[] = [{ mountPoint: '/mnt/c', windowsRoot: 'D:\\' }] - expect(collectWslDriveUncScope(state, 'Ubuntu', swapped).repoIds).toEqual([]) - expect(collectWslDriveUncScope(state, 'Ubuntu', []).repoIds).toEqual([]) - }) - - it('refuses a real /mnt/C directory: only the exact /mnt/c mount point is the C: drive', () => { - const upper = { - repos: [repo('upper', String.raw`\\wsl.localhost\Ubuntu\mnt\C\src\app`)], - folderWorkspaces: [], - projectGroups: [] - } - expect(collectWslDriveUncScope(upper, 'Ubuntu', DRIVES)).toEqual({ - repoIds: [], - folderWorkspaceIds: [], - refused: [{ kind: 'repo', id: 'upper', reason: 'not-windows-drive-mount' }] - }) - }) -}) - -describe('collectWslDriveUncScope overlaps', () => { - it('refuses a project nested with a refused one, whose shared folders would split', () => { - const repos = [ - repo('outer', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src`, { - worktreeBasePath: String.raw`\\wsl.localhost\Ubuntu\home\me\trees` - }), - repo('inner', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app`), - repo('beside', String.raw`\\wsl.localhost\Ubuntu\mnt\c\srcx`) - ] - expect( - collectWslDriveUncScope({ repos, folderWorkspaces: [], projectGroups: [] }, 'Ubuntu', DRIVES) - ).toEqual({ - repoIds: ['beside'], - folderWorkspaceIds: [], - refused: [ - { kind: 'repo', id: 'outer', reason: 'mixed-locations' }, - { kind: 'repo', id: 'inner', reason: 'overlaps-refused-project' } - ] - }) - }) - - it('converts a project nested under a refused duplicate, since its original converts too', () => { - const repos = [ - repo('outer', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src`), - repo('outer-alias', '//wsl$/Ubuntu/mnt/c/src/'), - repo('inner', String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app`) - ] - expect( - collectWslDriveUncScope({ repos, folderWorkspaces: [], projectGroups: [] }, 'Ubuntu', DRIVES) - ).toEqual({ - repoIds: ['outer', 'inner'], - folderWorkspaceIds: [], - refused: [{ kind: 'repo', id: 'outer-alias', reason: 'duplicate-windows-project' }] - }) - }) -}) - -describe('wslDriveUncWorktreeId', () => { - it('keeps the repo id and a folder workspace suffix, and maps only drive paths', () => { - expect( - wslDriveUncWorktreeId(String.raw`r1::\\wsl.localhost\Ubuntu\mnt\c\src\app`, 'Ubuntu') - ).toBe(String.raw`r1::C:\src\app`) - const suffix = '::workspace:0b6f7c3e-8d0f-4b8e-9a51-1f2c3d4e5f60' - expect( - wslDriveUncWorktreeId(String.raw`r1::\\wsl.localhost\Ubuntu\mnt\c\src\app${suffix}`, 'Ubuntu') - ).toBe(String.raw`r1::C:\src\app${suffix}`) - const home = String.raw`r1::\\wsl.localhost\Ubuntu\home\me\app` - expect(wslDriveUncWorktreeId(home, 'Ubuntu')).toBe(home) - }) -}) diff --git a/src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts b/src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts index 7715ab0de1d..ed55330e8e1 100644 --- a/src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts +++ b/src/main/wsl/filesystem/wsl-sh-cwd-report.node-pty.test.ts @@ -1,7 +1,7 @@ // Real sh/dash/ash under a pty: an interactive shell reads $ENV only with a terminal attached. // Locally this covers /bin/sh and whichever of dash and busybox are installed. The PR body records a // docker run against dash 0.5.8, 0.5.10, 0.5.11 and 0.5.12, busybox ash and bash-as-sh. -import { execFileSync } from 'node:child_process' +import 'node:child_process' import { chmodSync, existsSync, @@ -153,86 +153,3 @@ describe.skipIf(process.platform === 'win32')('a WSL bridge sh pane reports its 60_000 ) }) - -describe.skipIf(process.platform === 'win32')('the WSL bridge sh ENV file', () => { - let home: string - beforeEach(() => { - home = realpathSync(mkdtempSync(path.join(tmpdir(), 'wsl-sh-env-'))) - writeFileSync(path.join(home, 'env'), SH_WSL_ENV_FILE) - writeFileSync(path.join(home, 'user-env'), 'echo USER_ENV_SOURCED\n') - }) - afterEach(() => rmSync(home, { recursive: true, force: true })) - - it('is never read by a non-interactive sh -c', () => { - const out = execFileSync( - '/bin/sh', - ['-c', 'command -v __orca_wsl_cwd_report >/dev/null && echo HOOKED || echo PLAIN'], - { - encoding: 'utf8', - env: { - PATH: '/usr/bin:/bin', - ENV: path.join(home, 'env'), - ORCA_WSL_USER_ENV: path.join(home, 'user-env'), - WSL_DISTRO_NAME: 'Ubuntu' - } - } - ) - expect(out).toBe('PLAIN\n') - }) - - it.each(DASH ? ['/bin/sh', DASH] : ['/bin/sh'])( - '%s starts quietly when the file is gone (Orca updated away or uninstalled)', - (shell) => { - const out = execFileSync(shell, ['-i'], { - encoding: 'utf8', - input: 'echo ALIVE\nexit\n', - env: { PATH: '/usr/bin:/bin', ENV: path.join(home, 'gone', 'env'), PS1: '' } - }) - expect(out).toContain('ALIVE') - } - ) -}) - -describe.skipIf(process.platform === 'win32')('the WSL bridge launch for sh', () => { - // A stub shell named dash that reports the ENV it was given instead of starting. - function envGiven(root: string, inherited: Record = {}): string { - const home = realpathSync(mkdtempSync(path.join(tmpdir(), 'wsl-sh-launch-'))) - try { - const stub = path.join(home, 'dash') - writeFileSync( - stub, - '#!/bin/sh\nprintf "ENV=[%s] USER=[%s]\\n" "${ENV-unset}" "${ORCA_WSL_USER_ENV-unset}"\n' - ) - chmodSync(stub, 0o755) - writeFileSync(path.join(home, 'getent'), `#!/bin/sh\nprintf '%s\\n' "u:x:1:1::/:${stub}"\n`) - chmodSync(path.join(home, 'getent'), 0o755) - mkdirSync(path.join(root, 'sh'), { recursive: true }) - writeFileSync(path.join(root, 'sh', 'env'), SH_WSL_ENV_FILE) - return execFileSync('/bin/sh', ['-c', buildWslInteractiveLoginShellCommand()], { - encoding: 'utf8', - env: { PATH: `${home}:/usr/bin:/bin`, ORCA_SHELL_READY_ROOT: root, ...inherited } - }).trim() - } finally { - rmSync(home, { recursive: true, force: true }) - } - } - - it('points ENV at the published file and saves the user value', () => { - const root = realpathSync(mkdtempSync(path.join(tmpdir(), 'wsl-sh-root-'))) - try { - expect(envGiven(root, { ENV: '$HOME/.shrc' })).toBe(`ENV=[${root}/sh/env] USER=[$HOME/.shrc]`) - expect(envGiven(root)).toBe(`ENV=[${root}/sh/env] USER=[unset]`) - } finally { - rmSync(root, { recursive: true, force: true }) - } - }) - - it('leaves ENV alone when the root would be mangled by ENV expansion', () => { - const base = realpathSync(mkdtempSync(path.join(tmpdir(), 'wsl-sh-root-'))) - try { - expect(envGiven(path.join(base, 'a$b'), { ENV: '/u/env' })).toBe('ENV=[/u/env] USER=[unset]') - } finally { - rmSync(base, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/wsl/host-lifecycle/wsl-host-connector.test.ts b/src/main/wsl/host-lifecycle/wsl-host-connector.test.ts deleted file mode 100644 index 03e965a4067..00000000000 --- a/src/main/wsl/host-lifecycle/wsl-host-connector.test.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { createWslHostConnector } from './wsl-host-connector' -import type { WslRunningDistrosRead } from '../discovery/wsl-background-distro-gate' -import type * as TunnelIdentity from '../../managed-server/lifecycle/orcad-managed-tunnel-identity' - -const mocks = vi.hoisted(() => ({ - readRunning: vi.fn<(distro: string) => Promise>(), - connect: vi.fn(), - stopServer: vi.fn(async () => ({ stopped: true })), - verify: vi.fn(), - ready: vi.fn(() => false), - lastSeenRunning: vi.fn((_distro: string) => true), - managerGet: vi.fn((): unknown => null), - managerEnsure: vi.fn(), - managerIsConnecting: vi.fn(() => false) -})) -vi.mock('../orcad/wsl-orcad-connection', async (importOriginal) => ({ - ...(await importOriginal>()), - WslOrcadConnectionManager: class { - get = mocks.managerGet - ensure = mocks.managerEnsure - isConnecting = mocks.managerIsConnecting - } -})) -vi.mock('../discovery/wsl-background-distro-gate', () => ({ - // Settled per distro: a list taken while it stops still names it (E9). - readSettledConfirmedRunningWslDistros: mocks.readRunning, - wasWslDistroLastSeenRunningSettled: mocks.lastSeenRunning, - noteWslDistroMayHaveStopped: vi.fn(), - listConfirmedRunningWslDistros: vi.fn(async () => []) -})) -vi.mock('../../managed-server/lifecycle/orcad-managed-tunnel-identity', async (importOriginal) => ({ - ...(await importOriginal()), - verifyOrcadPairingIdentity: mocks.verify -})) -vi.mock('../orcad/wsl-orcad-liveness-wiring', () => ({ - createWslOrcadLivenessSupervisor: () => ({ connect: mocks.connect }) -})) -vi.mock('./wsl-host-server-stop', () => ({ - stopWslHostServer: mocks.stopServer, - wslHostRuntimeStopSteps: vi.fn(() => ({})), - decommissionWslHostOrcad: vi.fn() -})) - -it('uses owned readiness without discovery and coalesces cold cleanup without waking stopped or unknown guests', async () => { - const connector = createWslHostConnector({ - userDataPath: '/unused', - onChange: vi.fn(), - hasUserVisibleWork: () => false, - isKnownDistro: () => true, - runtime: { isReady: mocks.ready, call: vi.fn(), census: vi.fn() } - }) - mocks.ready.mockReturnValue(true) - await expect(connector.isReachable('Ubuntu', 'wsl:ubuntu')).resolves.toBe(true) - expect(mocks.readRunning).not.toHaveBeenCalled() - expect(mocks.verify).not.toHaveBeenCalled() - mocks.ready.mockReturnValue(false) - mocks.readRunning.mockResolvedValueOnce({ status: 'confirmed', distros: [] }) - const passive = connector.isReachable('Ubuntu', 'wsl:ubuntu') - const removal = connector.stopServer('Ubuntu', 'wsl:ubuntu') - await expect(passive).resolves.toBe(false) - await expect(removal).resolves.toEqual({ stopped: true }) - expect(mocks.readRunning).toHaveBeenCalledTimes(1) - expect(mocks.readRunning).toHaveBeenCalledWith('Ubuntu') - mocks.readRunning.mockResolvedValueOnce({ status: 'unavailable' }) - await expect(connector.stopServer('Ubuntu', 'wsl:ubuntu')).resolves.toMatchObject({ - stopped: false - }) - expect(mocks.connect).not.toHaveBeenCalled() - expect(mocks.verify).not.toHaveBeenCalled() - expect(mocks.stopServer).not.toHaveBeenCalled() - mocks.readRunning.mockResolvedValueOnce({ status: 'confirmed', distros: ['Ubuntu'] }) - await expect(connector.stopServer('Ubuntu', 'wsl:ubuntu')).resolves.toEqual({ stopped: true }) - expect(mocks.connect).toHaveBeenCalledOnce() - expect(mocks.stopServer).toHaveBeenCalledOnce() -}) - -it('a ready client never stands in for a running read once the distro may have stopped (E9)', async () => { - const connector = createWslHostConnector({ - userDataPath: '/unused', - onChange: vi.fn(), - hasUserVisibleWork: () => false, - isKnownDistro: () => true, - runtime: { isReady: mocks.ready, call: vi.fn(), census: vi.fn() } - }) - mocks.ready.mockReturnValue(true) - // Its control socket has not closed yet, but the last settled list no longer names it. - mocks.lastSeenRunning.mockReturnValueOnce(false).mockReturnValueOnce(false) - mocks.readRunning.mockReset().mockResolvedValue({ status: 'confirmed', distros: [] }) - await expect(connector.reachability('Ubuntu', 'wsl:ubuntu')).resolves.toBe('stopped') - await expect(connector.isReachable('Ubuntu', 'wsl:ubuntu')).resolves.toBe(false) - expect(mocks.readRunning).toHaveBeenCalledWith('Ubuntu') - mocks.ready.mockReturnValue(false) -}) - -function joinFixture() { - mocks.connect.mockReset() - mocks.managerGet.mockReset().mockReturnValue(null) - mocks.managerEnsure.mockReset() - mocks.managerIsConnecting.mockReset().mockReturnValue(false) - const bridge = { distro: 'Ubuntu', localPort: 41000 } - mocks.managerEnsure.mockResolvedValue(bridge) - let finish: (connection: unknown) => void = () => {} - mocks.connect.mockReturnValueOnce( - new Promise((resolve) => { - finish = resolve - }) - ) - const connector = createWslHostConnector({ - userDataPath: '/unused', - onChange: vi.fn(), - hasUserVisibleWork: () => true, - isKnownDistro: () => true, - runtime: { isReady: () => false, call: vi.fn(), census: vi.fn() } - }) - return { connector, bridge, finish: () => finish(bridge) } -} - -it('joins a plain connect already in flight instead of re-arming liveness for it', async () => { - const { connector, bridge, finish } = joinFixture() - const first = connector.connect('Ubuntu') - await expect(connector.connect('Ubuntu')).resolves.toBe(bridge) - expect(mocks.connect).toHaveBeenCalledOnce() - // Once the bridge is up, a call needs no wait at all, even while liveness still arms. - mocks.managerGet.mockReturnValue(bridge) - await expect(connector.connect('ubuntu')).resolves.toBe(bridge) - expect(mocks.managerEnsure).toHaveBeenCalledOnce() - - finish() - await first - mocks.connect.mockResolvedValueOnce(bridge) - await connector.connect('Ubuntu') - expect(mocks.connect).toHaveBeenCalledTimes(2) -}) - -it('a no-boot call joins a booting connect but stays no-boot itself (E9)', async () => { - const { connector, finish } = joinFixture() - const first = connector.connect('Ubuntu') - await connector.connect('Ubuntu', { noBoot: true }) - expect(mocks.connect).toHaveBeenCalledOnce() - // It reaches the manager with its running check, so it can only ride the boot already happening. - expect(mocks.managerEnsure).toHaveBeenCalledWith( - 'Ubuntu', - expect.objectContaining({ requireRunning: expect.any(Function) }) - ) - // That check is a settled read, so a distro still stopping counts as stopped. - const [, ensureOptions] = mocks.managerEnsure.mock.lastCall ?? [] - mocks.readRunning.mockClear().mockResolvedValueOnce({ status: 'confirmed', distros: ['Ubuntu'] }) - await expect(ensureOptions?.requireRunning('Ubuntu')).resolves.toBe(true) - expect(mocks.readRunning).toHaveBeenCalledWith('Ubuntu') - finish() - await first -}) - -it('a connect that may boot never rides a no-boot one, and intents never join (E9)', async () => { - const { connector, bridge, finish } = joinFixture() - const first = connector.connect('Ubuntu', { noBoot: true }) - mocks.connect.mockResolvedValue(bridge) - await connector.connect('Ubuntu') - expect(mocks.connect).toHaveBeenCalledTimes(2) - expect(mocks.connect).toHaveBeenLastCalledWith('Ubuntu', {}) - await connector.connect('Ubuntu', { intent: 'update' }) - expect(mocks.connect).toHaveBeenCalledTimes(3) - expect(mocks.managerEnsure).not.toHaveBeenCalled() - finish() - await first -}) - -it('never hands a joined call the server an in-flight connect is replacing', async () => { - const { connector, bridge, finish } = joinFixture() - const incumbent = { distro: 'Ubuntu', localPort: 40000 } - mocks.managerGet.mockReturnValue(incumbent) - mocks.managerIsConnecting.mockReturnValue(true) - - // A plain connect redeploying: a call waits for the new bridge, not the outgoing one. - const first = connector.connect('Ubuntu') - await expect(connector.connect('Ubuntu')).resolves.toBe(bridge) - expect(mocks.managerEnsure).toHaveBeenCalledOnce() - finish() - await first - - // An Update in flight is never joined: the call goes through liveness, as before. - const replacement = { distro: 'Ubuntu', localPort: 42000 } - let finishUpdate: (connection: unknown) => void = () => {} - mocks.connect.mockReturnValueOnce( - new Promise((resolve) => { - finishUpdate = resolve - }) - ) - const update = connector.connect('Ubuntu', { intent: 'update' }) - mocks.connect.mockResolvedValueOnce(replacement) - const call = connector.connect('Ubuntu') - await expect(call).resolves.toBe(replacement) - expect(mocks.connect).toHaveBeenCalledTimes(3) - expect(mocks.managerEnsure).toHaveBeenCalledOnce() - finishUpdate(replacement) - await update -}) diff --git a/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.test.ts b/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.test.ts index f7b37919dc2..e386f364d39 100644 --- a/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.test.ts +++ b/src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.test.ts @@ -1,18 +1,13 @@ -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - parseWslHostsPolicy, - wslHostsPolicyMovedProjects, - wslHostsPolicyState -} from '../../../shared/wsl-hosts-policy' +import '../../../shared/wsl-hosts-policy' import { readCachedWslHostsPolicy, WslHostsPolicyLiveUpdater, wslHostsPolicyCacheFileName, - wslHostsPolicyChannelForAppVersion, - wslHostsPolicyDownloadUrl + wslHostsPolicyChannelForAppVersion } from './wsl-hosts-policy-live-update' const STABLE = '1.4.2' @@ -21,54 +16,6 @@ const RC = '1.4.3-rc.1' const policy = (revision: number, wslHosts: 'allow' | 'block'): string => JSON.stringify({ version: 1, revision, wslHosts }) -describe('WSL hosts policy parsing', () => { - it('accepts a known policy and ignores fields added later', () => { - const parsed = parseWslHostsPolicy( - JSON.stringify({ version: 1, revision: 3, wslHosts: 'block', note: 'later field' }) - ) - - expect(parsed).toEqual({ ok: true, policy: { version: 1, revision: 3, wslHosts: 'block' } }) - }) - - it.each([ - ['not JSON', '{'], - ['an unknown format', JSON.stringify({ version: 2, revision: 1, wslHosts: 'block' })], - ['an unknown switch value', JSON.stringify({ version: 1, revision: 1, wslHosts: 'drain' })], - ['no revision', JSON.stringify({ version: 1, wslHosts: 'block' })], - ['an oversized file', `${policy(1, 'block')}${' '.repeat(17 * 1024)}`] - ])('rejects %s', (_label, text) => { - expect(parseWslHostsPolicy(text).ok).toBe(false) - }) - - it('reads moved projects as keep unless a block asks for them back', () => { - const parse = (fields: Record) => { - const parsed = parseWslHostsPolicy(JSON.stringify({ version: 1, revision: 1, ...fields })) - if (!parsed.ok) { - throw new Error(parsed.error) - } - return parsed.policy - } - expect(wslHostsPolicyMovedProjects(null)).toBe('keep') - expect(wslHostsPolicyMovedProjects(parse({ wslHosts: 'block' }))).toBe('keep') - expect( - wslHostsPolicyMovedProjects(parse({ wslHosts: 'block', movedProjects: 'bring-back' })) - ).toBe('bring-back') - expect( - wslHostsPolicyMovedProjects(parse({ wslHosts: 'allow', movedProjects: 'bring-back' })) - ).toBe('keep') - // A later value must not drop the block it rides on. - const later = parse({ wslHosts: 'block', movedProjects: 'some-later-mode' }) - expect(wslHostsPolicyState(later)).toBe('block') - expect(wslHostsPolicyMovedProjects(later)).toBe('keep') - }) - - it('reads no policy as missing, never as a block', () => { - expect(wslHostsPolicyState(null)).toBe('missing') - expect(wslHostsPolicyState({ version: 1, revision: 1, wslHosts: 'allow' })).toBe('allow') - expect(wslHostsPolicyState({ version: 1, revision: 1, wslHosts: 'block' })).toBe('block') - }) -}) - describe('WSL hosts policy live update', () => { let userDataPath: string beforeEach(() => { @@ -99,28 +46,6 @@ describe('WSL hosts policy live update', () => { writeFileSync(join(userDataPath, wslHostsPolicyCacheFileName(channel)), text) } - it('splits stable from prerelease channels', () => { - expect(wslHostsPolicyChannelForAppVersion(STABLE)).toBe('stable') - expect(wslHostsPolicyChannelForAppVersion(RC)).toBe('next') - expect(wslHostsPolicyDownloadUrl('stable')).toMatch( - /\/releases\/download\/wsl-hosts-policy-stable\/wsl-hosts-policy\.json$/ - ) - }) - - it('caches a downloaded block for the next launch', async () => { - const fetch = respond(policy(1, 'block')) - const live = updater(fetch) - await live.start() - live.stop() - - expect(fetch).toHaveBeenCalledWith(wslHostsPolicyDownloadUrl('stable'), expect.anything()) - expect(readCachedWslHostsPolicy(userDataPath, STABLE)).toEqual({ - version: 1, - revision: 1, - wslHosts: 'block' - }) - }) - // A build that doesn't know a field must not strip it for the newer build sharing the profile. it('caches the downloaded text verbatim, fields this build does not know included', async () => { const text = JSON.stringify({ @@ -143,25 +68,6 @@ describe('WSL hosts policy live update', () => { expect(JSON.parse(cachedText)).toMatchObject({ someLaterField: { keep: true } }) }) - // The newest known block stops new work this run: a fresh one, or one already cached. - it.each([ - ['a newer block', null, policy(2, 'block'), true], - ['an already cached block re-served', policy(2, 'block'), policy(2, 'block'), true], - ['a stale allow behind a cached block', policy(3, 'block'), policy(2, 'allow'), true], - ['a newer allow', policy(1, 'block'), policy(2, 'allow'), false], - ['an allow', null, policy(1, 'allow'), false] - ])('reports %s to this run', async (_label, cachedText, downloaded, blocks) => { - if (cachedText) { - seedCache(cachedText) - } - const onBlock = vi.fn() - const live = updater(respond(downloaded), { onBlock }) - await live.start() - live.stop() - - expect(onBlock).toHaveBeenCalledTimes(blocks ? 1 : 0) - }) - it('never lets a lower or equal revision replace the cache', async () => { seedCache(policy(5, 'block')) const live = updater(respond(policy(5, 'allow'))) @@ -180,46 +86,10 @@ describe('WSL hosts policy live update', () => { expect(readCachedWslHostsPolicy(userDataPath, STABLE)?.wslHosts).toBe('allow') }) - it.each([ - ['an unpublished policy', respond('', 404)], - ['a server error', respond('', 503)], - ['a malformed download', respond('{"version":1')], - [ - 'a network failure', - vi.fn(async () => { - throw new Error('offline') - }) - ] - ])('keeps the last good cache after %s', async (_label, fetch) => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - seedCache(policy(2, 'block')) - const live = updater(fetch) - await live.start() - live.stop() - - expect(readCachedWslHostsPolicy(userDataPath, STABLE)?.revision).toBe(2) - expect(readdirSync(userDataPath)).toEqual([wslHostsPolicyCacheFileName('stable')]) - }) - - it('never downloads in an unpackaged run', async () => { - const fetch = respond(policy(1, 'block')) - await updater(fetch, { isPackaged: false }).start() - - expect(fetch).not.toHaveBeenCalled() - expect(readCachedWslHostsPolicy(userDataPath, STABLE)).toBeNull() - }) - it('keeps a prerelease switch out of a stable build sharing the profile', () => { seedCache(policy(1, 'block'), RC) expect(readCachedWslHostsPolicy(userDataPath, RC)?.wslHosts).toBe('block') expect(readCachedWslHostsPolicy(userDataPath, STABLE)).toBeNull() }) - - it('reads an unreadable cache as no policy', () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - mkdirSync(join(userDataPath, wslHostsPolicyCacheFileName('stable'))) - - expect(readCachedWslHostsPolicy(userDataPath, STABLE)).toBeNull() - }) }) diff --git a/src/main/wsl/orcad/wsl-orcad-account-env.test.ts b/src/main/wsl/orcad/wsl-orcad-account-env.test.ts deleted file mode 100644 index 3c2e0dadc98..00000000000 --- a/src/main/wsl/orcad/wsl-orcad-account-env.test.ts +++ /dev/null @@ -1,215 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { ClaudeRuntimeAuthPreparation } from '../../claude-accounts/runtime-auth/runtime-auth-types' -import { - guestCodexHomePath, - prepareWslOrcadAccountEnv, - withWslOrcadAccountEnv, - type WslOrcadAccountEnvDependencies -} from './wsl-orcad-account-env' -import type { WslOrcadHostCapabilityVerdict } from './wsl-orcad-host-environments' -import { AGENT_SESSION_ACCOUNT_ENV_RUNTIME_CAPABILITY } from '../../../shared/agent-session/agent-session-create-capabilities' - -const POINTER = '~/.orca-claude-profile-pointer-test' -const CLAUDE_HOME = '/home/u/.orca/claude-accounts/acct-a/config' - -function claudeLaunch( - overrides: Partial = {} -): ClaudeRuntimeAuthPreparation { - return { - configDir: '\\\\wsl.localhost\\Ubuntu\\home\\u\\.orca\\claude-accounts\\acct-a\\config', - runtime: 'wsl', - wslDistro: 'Ubuntu', - wslLinuxConfigDir: CLAUDE_HOME, - envPatch: { - ORCA_CLAUDE_PROFILE_POINTER: POINTER, - CLAUDE_CONFIG_DIR: CLAUDE_HOME, - ORCA_CLAUDE_INJECTED_CONFIG_DIR: CLAUDE_HOME - }, - provenance: 'profile:acct-a:wsl:Ubuntu', - ...overrides - } -} - -function dependencies( - overrides: Partial = {} -): WslOrcadAccountEnvDependencies { - return { - prepareClaudeLaunch: vi.fn(async () => claudeLaunch()), - claudeTerminalEnv: vi.fn(() => ({ ORCA_CLAUDE_PROFILE_POINTER: POINTER })), - prepareCodexHome: vi.fn(async () => '\\\\wsl.localhost\\Ubuntu\\home\\u\\.orca\\codex-b'), - managedAccountSelected: vi.fn(() => true), - accountNotApplied: vi.fn(), - ...overrides - } -} - -describe('prepareWslOrcadAccountEnv', () => { - it('gives every other process only the Claude pointer, never waiting on Claude setup', async () => { - const deps = dependencies() - await expect(prepareWslOrcadAccountEnv('Ubuntu', 'codex', deps)).resolves.toEqual({ - ORCA_CLAUDE_PROFILE_POINTER: POINTER, - CODEX_HOME: '/home/u/.orca/codex-b' - }) - expect(deps.prepareClaudeLaunch).not.toHaveBeenCalled() - }) - - it("drops a preparation for another runtime or distro rather than send a host's path", async () => { - const deps = dependencies({ - prepareClaudeLaunch: async () => - claudeLaunch({ runtime: 'host', envPatch: { CLAUDE_CONFIG_DIR: '/Users/u/.claude-a' } }), - prepareCodexHome: async () => '\\\\wsl.localhost\\Debian\\home\\u\\.codex-b' - }) - await expect(prepareWslOrcadAccountEnv('Ubuntu', 'claude', deps)).resolves.toEqual({}) - }) - - it('refuses a home it cannot send', async () => { - const deps = dependencies({ claudeTerminalEnv: () => ({ ORCA_CLAUDE_PROFILE_POINTER: 'x' }) }) - await expect(prepareWslOrcadAccountEnv('Ubuntu', null, deps)).rejects.toThrow( - 'not a usable path' - ) - }) -}) - -describe('guestCodexHomePath', () => { - it('reads UNC and guest paths, case-insensitive on the distro', () => { - expect(guestCodexHomePath('\\\\wsl$\\ubuntu\\home\\u\\.codex', 'Ubuntu')).toBe('/home/u/.codex') - expect(guestCodexHomePath('/home/u//.codex', 'Ubuntu')).toBe('/home/u/.codex') - expect(guestCodexHomePath('C:\\Users\\u\\.codex', 'Ubuntu')).toBeNull() - }) -}) - -describe('withWslOrcadAccountEnv', () => { - const wsl = (id: string) => (id === 'wsl:ubuntu' ? 'Ubuntu' : null) - const run = ( - method: string, - params: unknown, - deps = dependencies(), - id = 'wsl:ubuntu', - hostSupports: (capability: string) => Promise = async () => - 'supported' - ) => withWslOrcadAccountEnv({ environmentId: id, method, params, hostSupports }, deps, wsl) - - it('adds the env to a plain shell and over a caller-built agent launch', async () => { - await expect(run('terminal.create', { worktree: 'id:wt' })).resolves.toMatchObject({ - params: { env: { ORCA_CLAUDE_PROFILE_POINTER: POINTER, CODEX_HOME: '/home/u/.orca/codex-b' } } - }) - const created = await run('session.tabs.createTerminal', { - worktree: 'id:wt', - command: 'claude', - launchAgent: 'claude', - env: { CLAUDE_CONFIG_DIR: '/stale', KEEP: '1' } - }) - expect(created).toMatchObject({ - params: { env: { KEEP: '1', CLAUDE_CONFIG_DIR: CLAUDE_HOME } } - }) - }) - - it('never turns a bare command or agent preset into a caller-built launch', async () => { - const bare = { worktree: 'id:wt', command: 'claude' } - await expect(run('terminal.create', bare)).resolves.toEqual({ ok: true, params: bare }) - const preset = { worktree: 'id:wt', agent: 'codex' } - await expect(run('session.tabs.createTerminal', preset)).resolves.toEqual({ - ok: true, - params: preset - }) - }) - - it('sets agent.launch accountEnv, except for a reused terminal', async () => { - const launch = { agent: 'claude', target: { kind: 'existing', worktree: 'id:wt' } } - await expect(run('agent.launch', launch)).resolves.toMatchObject({ - params: { accountEnv: { CLAUDE_CONFIG_DIR: CLAUDE_HOME } } - }) - const reused = { ...launch, reuseTerminal: { handle: 'term_1' } } - await expect(run('agent.launchReplay', reused)).resolves.toEqual({ ok: true, params: reused }) - }) - - it('refuses the call when the account cannot be prepared', async () => { - const deps = dependencies({ - prepareClaudeLaunch: async () => { - throw new Error('The selected Claude account could not be set up.') - } - }) - await expect( - run('agent.launch', { agent: 'claude', target: { kind: 'existing', worktree: 'x' } }, deps) - ).resolves.toEqual({ ok: false, message: 'The selected Claude account could not be set up.' }) - }) - - describe('agent-session creates (strict schemas, capability-gated)', () => { - const create = { clientOperationId: 'op', worktree: 'id:wt', agent: 'claude' } - const resume = { - kind: 'explicit', - worktree: 'id:wt', - agent: 'codex', - providerSession: { key: 'session_id', id: 's-1' } - } - - it('sets accountEnv on createAgentSession and an explicit ensure for an advertising host', async () => { - const hostSupports = vi.fn(async () => 'supported' as const) - const deps = dependencies() - await expect( - run('terminal.createAgentSession', create, deps, 'wsl:ubuntu', hostSupports) - ).resolves.toEqual({ - ok: true, - params: { - ...create, - accountEnv: { - ORCA_CLAUDE_PROFILE_POINTER: POINTER, - CLAUDE_CONFIG_DIR: CLAUDE_HOME, - ORCA_CLAUDE_INJECTED_CONFIG_DIR: CLAUDE_HOME, - CODEX_HOME: '/home/u/.orca/codex-b' - } - } - }) - expect(hostSupports).toHaveBeenCalledWith(AGENT_SESSION_ACCOUNT_ENV_RUNTIME_CAPABILITY) - await expect( - run('terminal.ensureAgentSession', resume, deps, 'wsl:ubuntu', hostSupports) - ).resolves.toMatchObject({ params: { accountEnv: { CODEX_HOME: '/home/u/.orca/codex-b' } } }) - expect(deps.accountNotApplied).not.toHaveBeenCalled() - }) - - it('leaves the call as is and tells the user once the host is older', async () => { - const deps = dependencies() - const older = async () => 'unsupported' as const - await expect( - run('terminal.createAgentSession', create, deps, 'wsl:ubuntu', older) - ).resolves.toEqual({ ok: true, params: create }) - await expect( - run('terminal.ensureAgentSession', resume, deps, 'wsl:ubuntu', older) - ).resolves.toEqual({ ok: true, params: resume }) - expect(deps.prepareCodexHome).not.toHaveBeenCalled() - expect(deps.accountNotApplied).toHaveBeenCalledWith('Ubuntu') - }) - - it('stays silent on an older host when no managed account is selected', async () => { - const deps = dependencies({ managedAccountSelected: vi.fn(() => false) }) - await run( - 'terminal.createAgentSession', - create, - deps, - 'wsl:ubuntu', - async () => 'unsupported' - ) - expect(deps.accountNotApplied).not.toHaveBeenCalled() - }) - - it('treats an unanswered capability probe as unknown: no field, no notice', async () => { - const deps = dependencies() - await expect( - run('terminal.createAgentSession', create, deps, 'wsl:ubuntu', async () => 'unknown') - ).resolves.toEqual({ ok: true, params: create }) - expect(deps.accountNotApplied).not.toHaveBeenCalled() - }) - - it('never probes or patches an automatic ensure or another environment', async () => { - const hostSupports = vi.fn(async () => 'supported' as const) - const automatic = { kind: 'automatic', sleepingCheckpointId: 'x'.repeat(32) } - await expect( - run('terminal.ensureAgentSession', automatic, dependencies(), 'wsl:ubuntu', hostSupports) - ).resolves.toEqual({ ok: true, params: automatic }) - await expect( - run('terminal.createAgentSession', create, dependencies(), 'ssh-1', hostSupports) - ).resolves.toEqual({ ok: true, params: create }) - expect(hostSupports).not.toHaveBeenCalled() - }) - }) -}) diff --git a/src/main/wsl/orcad/wsl-orcad-held-context.test.ts b/src/main/wsl/orcad/wsl-orcad-held-context.test.ts index 026a3d503a3..e56fa323e75 100644 --- a/src/main/wsl/orcad/wsl-orcad-held-context.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-held-context.test.ts @@ -1,7 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' -import type { WslOrcadHostTarget } from './wsl-orcad-host-target' const mocks = vi.hoisted(() => { const state: { @@ -61,28 +59,7 @@ vi.mock('../../managed-server/install/orcad-remote-context', async () => { }) import { runProcess } from '@orca/process-host' -import { - holdWslDistroWithContext, - readWslHostFacts, - WSL_HOST_FACTS_COMMAND -} from './wsl-orcad-held-context' - -const target: WslOrcadHostTarget = { kind: 'wsl', id: 'wsl:u', distro: 'U', label: 'U' } -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: every host call is mocked at its module. -const conn = {} as OrcadHostTransport - -function holderRejectingOn(gate: Promise): WslDistroHolder { - return { - ensureHeld: vi.fn(async () => { - await gate - throw new Error('holder exited before the distro started') - }), - adoptHolders: vi.fn(), - release: vi.fn(), - releaseAll: vi.fn(), - holderState: vi.fn() - } -} +import { readWslHostFacts, WSL_HOST_FACTS_COMMAND } from './wsl-orcad-held-context' /** What WSL_HOST_FACTS_COMMAND prints. */ function facts(kernel: string, home: string, uname: string, libc = 'ldd (GNU libc) 2.39'): string { @@ -97,167 +74,6 @@ beforeEach(() => { mocks.contextArgs = [] }) -describe('holdWslDistroWithContext', () => { - it('probes the context while the hold is pending, and resolves only once the distro is held', async () => { - let finishHold: () => void = () => {} - const holdDone = new Promise((resolve) => { - finishHold = resolve - }) - const hold: WslDistroHolder = { - ...holderRejectingOn(holdDone), - ensureHeld: vi.fn(async (distro: string) => { - await holdDone - return { - outcome: 'spawned' as const, - record: { version: 1 as const, distro, pid: 9, creationTimeMs: 1, startedAtMs: 1 } - } - }) - } - let settled = false - const held = holdWslDistroWithContext('U', target, conn, hold, undefined).finally(() => { - settled = true - }) - for (let step = 0; step < 2; step++) { - await vi.waitFor(() => expect(mocks.probeStep).not.toBeNull()) - const next = mocks.probeStep - mocks.probeStep = null - next?.() - } - await vi.waitFor(() => - expect(mocks.spawned).toEqual(['host-facts', 'ldd --version', 'cat orcad-active.json']) - ) - // The deploy awaits this before recovery, which may launch orcad. - expect(settled).toBe(false) - - finishHold() - - await expect(held).resolves.toMatchObject({ - held: { outcome: 'spawned' }, - context: { remoteHome: '/home/u' } - }) - }) - - it('stops the context probes once the hold fails, so nothing can boot the distro again', async () => { - let failHold: () => void = () => {} - const holdFails = new Promise((resolve) => { - failHold = resolve - }) - const held = holdWslDistroWithContext( - 'U', - target, - conn, - holderRejectingOn(holdFails), - undefined - ) - await vi.waitFor(() => expect(mocks.probeStep).not.toBeNull()) - mocks.probeStep?.() - await vi.waitFor(() => expect(mocks.spawned).toEqual(['host-facts', 'ldd --version'])) - - failHold() - await expect(held).rejects.toThrow('holder exited') - mocks.probeStep?.() - await vi.waitFor(() => expect(mocks.refused).toEqual(['cat orcad-active.json'])) - - expect(mocks.spawned).toEqual(['host-facts', 'ldd --version']) - }) -}) - -describe('the folded host facts probe', () => { - function heldNow(): WslDistroHolder { - return { - ...holderRejectingOn(Promise.resolve()), - ensureHeld: vi.fn(async (distro: string) => ({ - outcome: 'adopted' as const, - record: { version: 1 as const, distro, pid: 9, creationTimeMs: 1, startedAtMs: 1 } - })) - } - } - - async function resolveWith(facts: string) { - mocks.facts = facts - const held = holdWslDistroWithContext('U', target, conn, heldNow(), undefined) - for (let step = 0; step < 2; step++) { - await vi.waitFor(() => expect(mocks.probeStep).not.toBeNull()) - const next = mocks.probeStep - mocks.probeStep = null - next?.() - } - return held - } - - it('hands the context the platform and login home it read in the same exec', async () => { - await resolveWith(mocks.facts) - - expect(mocks.spawned.filter((label) => label === 'host-facts')).toHaveLength(1) - expect(mocks.contextArgs).toEqual([ - expect.objectContaining({ os: 'linux', arch: 'x64' }), - { - loginHome: '/home/u', - firstLibcProbeOutput: 'ldd (GNU libc) 2.39\n', - readActivationRecord: expect.any(Function) - } - ]) - }) - - it('leaves the context to probe what the facts did not prove', async () => { - await resolveWith(facts('5.15.167.4-microsoft-standard-WSL2', '', 'Linux sparc')) - - expect(mocks.contextArgs).toEqual([ - undefined, - { loginHome: undefined, readActivationRecord: expect.any(Function) } - ]) - expect(mocks.spawned[0]).toBe('host-facts') - expect(mocks.spawned).not.toContain('uname -r') - }) - - it('falls back to the separate probes for a HOME with a newline, never a truncated path', async () => { - await resolveWith(facts('5.15.167.4-microsoft-standard-WSL2', '/home/a\nb', 'Linux x86_64')) - - expect(mocks.contextArgs).toEqual([ - undefined, - { loginHome: undefined, readActivationRecord: expect.any(Function) } - ]) - expect(mocks.spawned.slice(0, 2)).toEqual(['host-facts', 'uname -r']) - }) - - it('falls back without throwing when stdout noise precedes the facts', async () => { - await resolveWith( - `Welcome to Ubuntu\n${facts('5.15.167.4-microsoft-standard-WSL2', '/home/u', 'Linux x86_64')}` - ) - - expect(mocks.contextArgs).toEqual([ - undefined, - { loginHome: undefined, readActivationRecord: expect.any(Function) } - ]) - expect(mocks.spawned.slice(0, 2)).toEqual(['host-facts', 'uname -r']) - }) - - it('keeps a multi-line libc answer whole, and rejects output missing the libc section', () => { - const musl = 'musl libc (x86_64)\nVersion 1.2.4\nDynamic Program Loader' - expect( - readWslHostFacts(facts('5.15.167.4-microsoft-standard-WSL2', '/home/u', 'Linux x86_64', musl)) - ).toMatchObject({ firstLibcProbeOutput: `${musl}\n` }) - expect( - readWslHostFacts( - '__ORCA_WSL_KERNEL__ 5.15\n__ORCA_WSL_HOME__ /home/u\n\n__ORCA_REMOTE_PLATFORM__ Linux x86_64\n' - ) - ).toBeNull() - }) - - it('refuses WSL 1 from the kernel line before holding or probing', async () => { - mocks.facts = facts('4.4.0-19041-Microsoft', '/home/u', 'Linux x86_64') - const holder = heldNow() - - await expect( - holdWslDistroWithContext('U', target, conn, holder, undefined) - ).rejects.toMatchObject({ - name: 'OrcadHostUnsupportedError' - }) - expect(holder.ensureHeld).not.toHaveBeenCalled() - expect(mocks.spawned).toEqual(['host-facts']) - }) -}) - describe.skipIf(process.platform === 'win32')('WSL_HOST_FACTS_COMMAND under a real sh', () => { it('prints exactly the shape readWslHostFacts accepts', async () => { const result = await runProcess({ diff --git a/src/main/wsl/orcad/wsl-orcad-incumbent.test.ts b/src/main/wsl/orcad/wsl-orcad-incumbent.test.ts deleted file mode 100644 index d91b3d9c6cd..00000000000 --- a/src/main/wsl/orcad/wsl-orcad-incumbent.test.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { - encodePairingOffer, - parsePairingCode -} from '../../../shared/remote-runtime/pairing/pairing' -import { pairedRuntimeConnectionToken } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' -import { DeviceRegistry } from '../../runtime/rpc/server/pairing/device-registry' -import { ORCAD_UPDATE_ADMISSION_FENCE_MS } from '../../../shared/orcad-terminal-census' -import { emptyOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' -import type { OrcadRemoteContext } from '../../managed-server/install/orcad-remote-context' -import type { ServeReadiness } from '../../server/serve-readiness' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import type { StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' -import { readWslOrcadIncumbent, type WslOrcadIncumbentDependencies } from './wsl-orcad-incumbent' -import type { WslOrcadHostTarget } from './wsl-orcad-host-target' -import { unusedOrcadHostTransport } from '../../ssh/unused-host-transport.test-fixture' - -const host = getRemoteHostPlatform('linux-x64') -const KEY = Buffer.alloc(32, 7).toString('base64') -const READINESS: ServeReadiness = { - runtimeId: 'r-old', - boundEndpoint: 'ws://127.0.0.1:6791', - advertisedEndpoint: null, - managedWslCliReconciliation: 'settled' as const, - pairing: { - available: true as const, - url: encodePairingOffer({ - v: 2, - endpoint: 'ws://127.0.0.1:6791', - deviceToken: 'device', - publicKeyB64: KEY - }), - endpoint: 'ws://127.0.0.1:6791', - deviceId: 'device-id', - webClientUrl: null, - scope: 'runtime' as const, - qr: null - } -} -const LIVE = { - liveSessions: 1, - startedSinceActivation: 0, - daemonProtocolVersion: 3 -} -const UNVERIFIABLE = { - liveSessions: null, - startedSinceActivation: null, - daemonProtocolVersion: null -} -const target: WslOrcadHostTarget = { - kind: 'wsl', - id: 'wsl:ubuntu', - distro: 'Ubuntu', - label: 'Ubuntu' -} -const conn = unusedOrcadHostTransport() - -function context(active: string | null = '1.4.0+aa'): OrcadRemoteContext { - return { - activationRecord: { - ...emptyOrcadActivationRecord(), - active, - activatedAt: active ? '2026-10-12T01:00:00.000Z' : null - }, - serverTarget: 'linux-x64-glibc', - connection: conn, - host, - remoteHome: '/home/u', - target, - userDataDir: '/home/u/.orca' - } -} - -const slot = { - conn, - host, - remoteHome: '/home/u', - nodePath: '', - userDataDir: '/home/u/.orca', - bindHost: '127.0.0.1', - port: 6768 -} - -function dependencies(overrides: Partial = {}) { - const close = vi.fn(async () => {}) - const deps: WslOrcadIncumbentDependencies = { - wake: vi.fn(async () => ({ outcome: 'serving' as const })), - probe: vi.fn(async () => READINESS), - readBuildHash: vi.fn(async () => '0123456789abcdef'), - listen: vi.fn(async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only entry.localPort and close are read. - return { - entry: { localPort: 51000 }, - close - } as unknown as StartedPortForward - }), - census: vi.fn(async () => LIVE), - ...overrides - } - return { deps, close } -} - -describe('readWslOrcadIncumbent', () => { - it('asks a serving incumbent over a bridge to its bound port, then closes the bridge', async () => { - const { deps, close } = dependencies() - await expect(readWslOrcadIncumbent({ context: context(), slot }, deps)).resolves.toMatchObject({ - census: LIVE, - readiness: READINESS - }) - expect(deps.probe).toHaveBeenCalledWith( - expect.objectContaining({ - remoteInstallDir: '/home/u/.orca-remote/orcad-1.4.0+aa' - }), - { buildHash: '0123456789abcdef', fullVersion: '1.4.0+aa' } - ) - expect(deps.listen).toHaveBeenCalledWith(conn, 6791, target) - const [connection, activatedAt, , options] = vi.mocked(deps.census).mock.calls[0] - expect(connection.endpoint).toMatch(/^ws:\/\/127\.0\.0\.1:51000\/?$/u) - expect(activatedAt).toBe(Date.parse('2026-10-12T01:00:00.000Z')) - expect(options).toEqual({ releaseFinishedAutomationTerminals: true }) - expect(close).toHaveBeenCalledTimes(1) - }) - - it('recounts over a fresh bridge without waking anything again', async () => { - const { deps, close } = dependencies() - const incumbent = await readWslOrcadIncumbent({ context: context(), slot }, deps) - vi.mocked(deps.census).mockResolvedValueOnce({ ...LIVE, liveSessions: 3 }) - await expect(incumbent.recount()).resolves.toMatchObject({ liveSessions: 3 }) - expect(deps.wake).toHaveBeenCalledTimes(1) - expect(deps.listen).toHaveBeenCalledTimes(2) - expect(close).toHaveBeenCalledTimes(2) - // Only final recount closes admission, preventing terminal creation between census and stop. - expect(vi.mocked(deps.census).mock.calls[1]?.[3]).toEqual({ - releaseFinishedAutomationTerminals: true, - closeAdmissionForMs: ORCAD_UPDATE_ADMISSION_FENCE_MS - }) - await incumbent.releaseAdmission() - expect(vi.mocked(deps.census).mock.calls[2]?.[3]).toEqual({ closeAdmissionForMs: 0 }) - }) - - it('is unverifiable, without a bridge, when the incumbent cannot be proven running', async () => { - const { deps } = dependencies({ - wake: vi.fn(async () => ({ outcome: 'unverifiable' as const })) - }) - const incumbent = await readWslOrcadIncumbent({ context: context(), slot }, deps) - expect(incumbent).toMatchObject({ census: UNVERIFIABLE, readiness: null }) - // The recount before the stop must refuse too, never read as zero. - await expect(incumbent.recount()).resolves.toEqual(UNVERIFIABLE) - expect(deps.listen).not.toHaveBeenCalled() - }) - - it('keeps the readiness but never reads zero when the census fails', async () => { - const { deps, close } = dependencies({ - census: vi.fn(async () => { - throw new Error('socket closed') - }) - }) - await expect(readWslOrcadIncumbent({ context: context(), slot }, deps)).resolves.toMatchObject({ - census: UNVERIFIABLE, - readiness: READINESS - }) - expect(close).toHaveBeenCalledTimes(1) - }) -}) - -describe('the incumbent terminal count across restarts', () => { - it('authenticates with the enrolled pairing, so restarts do not grow the device registry', async () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-incumbent-registry-')) - try { - const registry = new DeviceRegistry(dir) - const enrolled = registry.getOrCreatePendingDevice('CLI', 'runtime') - registry.updateLastSeen(enrolled.deviceId) - const paired = parsePairingCode( - encodePairingOffer({ - v: 2, - endpoint: 'ws://127.0.0.1:41000', - deviceToken: enrolled.token, - publicKeyB64: KEY, - pairedDeviceId: enrolled.deviceId - }) - ) - for (let start = 0; start < 3; start += 1) { - // Each orcad start publishes whatever pending device its registry holds. - const pending = registry.getOrCreatePendingDevice('CLI', 'runtime') - const readiness: ServeReadiness = { - ...READINESS, - pairing: { - available: true, - url: encodePairingOffer({ - v: 2, - endpoint: 'ws://127.0.0.1:6791', - deviceToken: pending.token, - publicKeyB64: KEY - }), - endpoint: 'ws://127.0.0.1:6791', - deviceId: pending.deviceId, - webClientUrl: null, - scope: 'runtime', - qr: null - } - } - const { deps } = dependencies({ - probe: vi.fn(async () => readiness), - // The host marks whichever device authenticated as seen. - census: vi.fn(async (connection) => { - const token = pairedRuntimeConnectionToken(connection) - const device = registry.listDevices().find((entry) => entry.token === token) - if (device) { - registry.updateLastSeen(device.deviceId) - } - return LIVE - }) - }) - await readWslOrcadIncumbent({ context: context(), slot, paired }, deps) - } - expect(registry.listDevices()).toHaveLength(2) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/wsl/orcad/wsl-orcad-stdio-bridge-e9.test.ts b/src/main/wsl/orcad/wsl-orcad-stdio-bridge-e9.test.ts index b962fda48e7..486f8acd6d3 100644 --- a/src/main/wsl/orcad/wsl-orcad-stdio-bridge-e9.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-stdio-bridge-e9.test.ts @@ -41,7 +41,7 @@ import { import { WslOrcadBridgeActivity, wslHostBridgeEvents } from './wsl-orcad-bridge-activity' import { createWslOrcadHostTransport } from './wsl-orcad-host-transport' import { listenWslOrcadStdioBridge } from './wsl-orcad-stdio-bridge' -import { startOrcadStdioBridge } from '../../managed-server/lifecycle/orcad-stdio-bridge-provider' +import '../../managed-server/lifecycle/orcad-stdio-bridge-provider' /** Echoes, and lets a test end every connection from the guest side. */ function startGuestServer(): Promise<{ @@ -154,44 +154,6 @@ const closed = (socket: Socket): Promise => new Promise((resolve) => (socket.destroyed ? resolve() : socket.once('close', () => resolve()))) describe('WSL bridge dials never start a stopped distro (E9)', () => { - it('refuses a dial into a stopped distro without spawning wsl.exe', async () => { - const { forward, children } = await startBridge() - const spawnedBefore = children.commands.length - const socket = await dial(forward.entry.localPort) - await closed(socket) - expect(children.commands).toHaveLength(spawnedBefore) - }) - - it('bridges a running distro, and many dials share one running read', async () => { - probe.running = ['Ubuntu'] - const { forward } = await startBridge() - const sockets = await Promise.all([1, 2, 3].map(() => dial(forward.entry.localPort))) - expect(await Promise.all(sockets.map((socket, i) => echoOf(socket, `m${i}`)))).toEqual([ - 'm0', - 'm1', - 'm2' - ]) - expect(probe.calls).toBe(1) - }) - - it('after the guest ends a bridge, the next dial re-reads and is refused once stopped', async () => { - probe.running = ['Ubuntu'] - const { forward, children, guest } = await startBridge() - const first = await dial(forward.entry.localPort) - expect(await echoOf(first, 'up')).toBe('up') - const readsWhileUp = probe.calls - - // The distro stops: its side of every bridge ends first. - probe.running = [] - guest.endAll() - await closed(first) - const spawnedBefore = children.commands.length - const redial = await dial(forward.entry.localPort) - await closed(redial) - expect(probe.calls).toBeGreaterThan(readsWhileUp) - expect(children.commands).toHaveLength(spawnedBefore) - }) - it('a normal one-shot close while the control socket stays open costs the next dial nothing', async () => { probe.running = ['Ubuntu'] const { forward, guest } = await startBridge() @@ -211,51 +173,4 @@ describe('WSL bridge dials never start a stopped distro (E9)', () => { expect(probe.calls).toBe(readsBefore) expect(await echoOf(control, 'still')).toBe('still') }) - - it('a user act that starts the distro is not refused by the read taken before it', async () => { - const { forward, children, transport } = await startBridge() - // A background dial reads it stopped, and that read is cached. - await closed(await dial(forward.entry.localPort)) - - // The user's connect starts it (any wsl.exe launch does) before its clients dial. - probe.running = ['Ubuntu'] - const launch = await transport.exec('true') - launch.close() - const socket = await dial(forward.entry.localPort) - expect(await echoOf(socket, 'mine')).toBe('mine') - expect(children.commands.length).toBeGreaterThan(2) - }) - - it('leaves the shared SSH bridge path ungated: it never reads WSL running state', async () => { - const guest = await startGuestServer() - servers.push(guest.server) - const children = fakeWslBridgeChildren() - const transport = createWslOrcadHostTransport({ - target: { kind: 'wsl', id: 'wsl:ubuntu', distro: 'Ubuntu', label: 'Ubuntu' }, - spawn: children.spawn, - commandLoops: false - }) - // The provider SSH uses, fed the same transport: no gate sits in the shared listener. - const forward = await startOrcadStdioBridge( - transport, - { - id: 'ssh:host', - connectionId: 'ssh-1', - localHost: '127.0.0.1', - localPort: 0, - remoteHost: '127.0.0.1', - remotePort: guest.port, - label: 'ssh' - }, - { - resolveBridge: async (_conn, port) => posixOrcadStdioBridge(port), - checkBridge: checkOrcadStdioBridge, - openChannel: openOrcadStdioBridgeChannel - } - ) - started.push(forward) - const socket = await dial(forward.entry.localPort) - expect(await echoOf(socket, 'ssh')).toBe('ssh') - expect(probe.calls).toBe(0) - }) }) diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-selection-quote-draft.test.ts b/src/renderer/src/components/native-chat/drafts/native-chat-selection-quote-draft.test.ts index e65e7f7265f..bb853d7204a 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-selection-quote-draft.test.ts +++ b/src/renderer/src/components/native-chat/drafts/native-chat-selection-quote-draft.test.ts @@ -31,18 +31,6 @@ afterEach(() => { // Add to chat is typed input: a lone command stays and a second identical quote is a second quote. describe('appendQuoteToChatDraft', () => { - it('adds the quote after the draft every time, and saves it', async () => { - const { store, quotes, persistence } = await renderer(true) - store.updateNativeChatComposerDraft('agent-session:s1', { text: '/compact' }, 'immediate') - quotes.appendQuoteToChatDraft('agent-session:s1', '> a\n\n') - quotes.appendQuoteToChatDraft('agent-session:s1', '> a\n\n') - await persistence.nativeChatComposerDraftWritesSettled() - expect(store.readNativeChatComposerDraft('agent-session:s1').text).toBe( - '/compact\n\n> a\n\n> a\n\n' - ) - expect(storage.drafts.get('agent-session:s1')?.text).toBe('/compact\n\n> a\n\n> a\n\n') - }) - it('adds after a saved draft that had not loaded yet', async () => { storage.drafts.set('agent-session:s2', { text: 'typed earlier', images: [], savedAt: 1 }) const { store, quotes, load, persistence } = await renderer(false) diff --git a/src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.test.ts b/src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.test.ts deleted file mode 100644 index 2e3200598c8..00000000000 --- a/src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { Tab } from '../../../../../shared/tab-types' -import { workspaceChatTargetFor } from './native-chat-workspace-selection' - -const sendMessageToAgent = vi.hoisted(() => vi.fn()) -vi.mock('@/lib/agent-message-send', () => ({ sendMessageToAgent })) - -const CHAT_LEAF = '6f1c2a4e-8b3d-4c5a-9e7f-1a2b3c4d5e6f' - -function tab(partial: Partial & Pick): Tab { - return { - entityId: partial.id, - groupId: 'group-1', - worktreeId: 'wt-1', - label: partial.id, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0, - ...partial - } -} - -const SHELL_LEAF = '7a2d3b5f-9c4e-4d6b-8f80-2b3c4d5e6f70' - -const structured = tab({ - id: 'tab-structured', - entityId: 'session-1', - contentType: 'agent-session', - agentSessionAgent: 'claude' -}) -const terminalChat = tab({ - id: 'tab-term', - entityId: 'term-chat', - contentType: 'terminal', - viewMode: 'chat' -}) -const plainTerminal = tab({ id: 'tab-plain', entityId: 'term-plain', contentType: 'terminal' }) -const state = { - unifiedTabsByWorktree: { 'wt-1': [structured, terminalChat, plainTerminal] }, - terminalLayoutsByTabId: { - 'term-chat': { root: null, activeLeafId: null, expandedLeafId: null, chatLeafId: CHAT_LEAF }, - 'term-plain': { root: null, activeLeafId: null, expandedLeafId: null } - } -} - -describe('workspaceChatTargetFor', () => { - it('maps a picked agent to the composer that holds its unsent text', () => { - expect( - workspaceChatTargetFor(state, 'wt-1', { kind: 'structured-session', sessionId: 'session-1' }) - ).toEqual({ tab: structured, scopeKey: 'agent-session:session-1' }) - expect( - workspaceChatTargetFor(state, 'wt-1', { - kind: 'terminal', - tabId: 'term-chat', - leafId: CHAT_LEAF - }) - ).toEqual({ tab: terminalChat, scopeKey: `term-chat:${CHAT_LEAF}`, chatLeafId: CHAT_LEAF }) - }) - - // Only the chat's own pane has a composer; a plain terminal agent or a split shell beside the chat has none. - it('finds no composer for a plain terminal agent or another pane of a chat tab', () => { - expect( - workspaceChatTargetFor(state, 'wt-1', { - kind: 'terminal', - tabId: 'term-plain', - leafId: CHAT_LEAF - }) - ).toBeNull() - expect( - workspaceChatTargetFor(state, 'wt-1', { - kind: 'terminal', - tabId: 'term-chat', - leafId: SHELL_LEAF - }) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/components/native-chat/viewport/history/use-native-chat-history-retention.test.ts b/src/renderer/src/components/native-chat/viewport/history/use-native-chat-history-retention.test.ts deleted file mode 100644 index de54b3a8d6f..00000000000 --- a/src/renderer/src/components/native-chat/viewport/history/use-native-chat-history-retention.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { expect, it, vi } from 'vitest' -import { useNativeChatHistoryRetention } from './use-native-chat-history-retention' - -it.each([false, true])( - 'preserves a mounted selection until it clears (shared source: %s)', - (shared) => { - const element = document.createElement('div') - element.textContent = 'Selected folded tool lead' - document.body.append(element) - const root = { current: element } - const selected = document.getSelection()! - const range = document.createRange() - range.selectNodeContents(element) - selected.removeAllRanges() - selected.addRange(range) - const release = vi.fn() - const retainHistory = shared ? vi.fn(() => release) : undefined - const trimHistory = vi.fn() - const view = renderHook( - (isVisible) => - useNativeChatHistoryRetention({ - root, - sourceKey: 'source', - retainHistory, - trimHistory, - isVisible - }), - { initialProps: true } - ) - act(() => view.result.current.returnToEnd()) - expect(trimHistory).toHaveBeenCalledTimes(shared ? 1 : 0) - trimHistory.mockClear() - expect(release).not.toHaveBeenCalled() - act(() => view.result.current.leaveEnd()) - view.rerender(false) - act(() => { - selected.removeAllRanges() - document.dispatchEvent(new Event('selectionchange')) - }) - expect(trimHistory).not.toHaveBeenCalled() - act(() => view.result.current.returnToEnd()) - expect(trimHistory).toHaveBeenCalledOnce() - expect(release).toHaveBeenCalledTimes(shared ? 2 : 0) - view.unmount() - element.remove() - } -) - -it.each([false, true])( - 'reads a departure immediately when a send returns before the next render (shared: %s)', - (shared) => { - const release = vi.fn() - const retainHistory = shared ? () => release : undefined - const trimHistory = vi.fn() - const view = renderHook(() => - useNativeChatHistoryRetention({ - root: { current: null }, - sourceKey: 'same-turn', - retainHistory, - trimHistory - }) - ) - act(() => { - view.result.current.leaveEnd() - view.result.current.returnToEnd('send') - }) - expect(trimHistory).toHaveBeenCalledOnce() - expect(release).toHaveBeenCalledTimes(shared ? 1 : 0) - view.unmount() - } -) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts deleted file mode 100644 index 223d2080c50..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - createMockTransport, - createPane, - createManager, - type MockTransport -} from '../test-fixtures/pty-connection-test-pane-fixtures' -import { - buildPaneConnectionDeps, - type PtyConnectionAgentTitleMocks, - bindPaneAgentTitleMocks -} from '../test-fixtures/pty-connection-test-deps' -import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures' -import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' -import { - installTerminalTestGlobals, - restoreTerminalTestGlobals -} from '../test-fixtures/pty-connection-test-environment' - -export function registerPtyConnectionSshHookStatusAuthorityTests(): void { - let mockStoreState: StoreState - let transportFactoryQueue: MockTransport[] = [] - let createdTransportOptions: Record[] = [] - let storeSubscribers: ((state: StoreState) => void)[] = [] - - function createDeps(overrides: Record = {}) { - return buildPaneConnectionDeps(() => mockStoreState, overrides) - } - describe('connectPanePty', () => { - beforeEach(async () => { - vi.resetModules() - vi.clearAllMocks() - transportFactoryQueue = [] - createdTransportOptions = [] - storeSubscribers = [] - mockStoreState = createInitialStoreState(() => mockStoreState) - bindPtyConnectionTestMocks({ - getState: () => mockStoreState, - getTransportQueue: () => transportFactoryQueue, - getTransportOptions: () => createdTransportOptions, - getStoreSubscribers: () => storeSubscribers, - setStoreSubscribers: (subscribers) => { - storeSubscribers = subscribers - } - }) - await installTerminalTestGlobals() - }) - - afterEach(async () => { - await restoreTerminalTestGlobals() - }) - - it('leaves SSH IPC OSC 9999 status ownership in the main runtime', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-ssh') - transportFactoryQueue.push(transport) - mockStoreState = { - ...mockStoreState, - repos: [{ id: 'repo1', connectionId: 'conn-1' }], - sshConnectionStates: new Map([['conn-1', { status: 'connected' }]]) - } as StoreState - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks) - ) - - expect(createdTransportOptions[0]?.onAgentStatus).toBeUndefined() - }) - }) -} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts deleted file mode 100644 index 9a379fd1ec3..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { isPaneResumingInPlace } from '@/lib/pane-spawn-deferral-registry' -import type { ColdRestoreAgentResumeStartup } from './fresh-spawn-types' -import { holdInPlaceResumeUntilSettled } from './in-place-resume-hold' - -function startupFor(paneKey: string): ColdRestoreAgentResumeStartup { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hold reads only sleepingRecordEntry.paneKey. - return { sleepingRecordEntry: { paneKey } } as ColdRestoreAgentResumeStartup -} - -function isLiveUnless(disposed: boolean): () => boolean { - return () => !disposed -} - -function deferred(): { promise: Promise; resolve: () => void; reject: () => void } { - let resolve = (): void => {} - let reject = (): void => {} - const promise = new Promise((res, rej) => { - resolve = () => res(null) - reject = () => rej(new Error('spawn failed')) - }) - return { promise, resolve, reject } -} - -describe('holdInPlaceResumeUntilSettled', () => { - it('owns the record while the start runs, through a nested start, and releases on settle', async () => { - const outer = deferred() - const inner = deferred() - holdInPlaceResumeUntilSettled(isLiveUnless(false), startupFor('tab:a'), outer.promise) - holdInPlaceResumeUntilSettled(isLiveUnless(false), startupFor('tab:a'), inner.promise) - expect(isPaneResumingInPlace('tab:a')).toBe(true) - inner.reject() - await inner.promise.catch(() => undefined) - expect(isPaneResumingInPlace('tab:a')).toBe(true) - outer.resolve() - await outer.promise - expect(isPaneResumingInPlace('tab:a')).toBe(false) - }) - - it('holds nothing for a start not resuming a record, or once the pane is disposed', () => { - const pending = deferred() - holdInPlaceResumeUntilSettled(isLiveUnless(false), null, pending.promise) - holdInPlaceResumeUntilSettled(isLiveUnless(true), startupFor('tab:b'), pending.promise) - expect(isPaneResumingInPlace('tab:b')).toBe(false) - pending.resolve() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts index dba5dcb37c2..2021a634238 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts @@ -1,7 +1,6 @@ import { describe } from 'vitest' import { registerPtyConnectionCommandFinishedCleanupTests } from '../agent-identity/pty-connection-command-finished-cleanup.spec' import { registerPtyConnectionCommandFinishedInterruptArbitrationTests } from '../input/pty-connection-command-finished-interrupt-arbitration.spec' -import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec' import { registerPtyConnectionHookCompletionBellArbitrationTests } from '../notifications/pty-connection-hook-completion-bell-arbitration.spec' import { registerPtyConnectionBellQueryReplyAndStaleInputTests } from '../input/pty-connection-bell-query-reply-and-stale-input.spec' import { registerPtyConnectionHookCompletionSideEffectsTests } from '../notifications/pty-connection-hook-completion-side-effects.spec' @@ -14,7 +13,6 @@ describe('pty-connection-command-finished-cleanup', () => { registerPtyConnectionCommandFinishedInterruptArbitrationTests() }) describe('pty-connection-hook-completion-bell-arbitration', () => { - registerPtyConnectionSshHookStatusAuthorityTests() registerPtyConnectionHookCompletionBellArbitrationTests() registerPtyConnectionBellQueryReplyAndStaleInputTests() }) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-pre-handler-buffer-warn-eviction.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-pre-handler-buffer-warn-eviction.test.ts deleted file mode 100644 index 7f8aa055372..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-pre-handler-buffer-warn-eviction.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -/** Evicting buffered bytes must also evict their warn-once ID, or repeated loss under the reused ID stays silent and the warning set leaks. */ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { bufferPreHandlerPtyData, clearPreHandlerPtyState } from './pty-pre-handler-buffer' - -const PRE_HANDLER_PTY_DATA_MAX_PTYS = 64 -const WARN_BYTES = 64 * 1024 -const EVICTED_PTY_ID = 'pty-warn-evicted' -/** One more than the cap, so the first id admitted is evicted. */ -const FILLER_PTY_IDS = Array.from( - { length: PRE_HANDLER_PTY_DATA_MAX_PTYS }, - (_, index) => `pty-warn-filler-${index}` -) - -function bufferPastWarnThreshold(ptyId: string): void { - bufferPreHandlerPtyData(ptyId, 'x'.repeat(WARN_BYTES + 1)) -} - -function lostHandlerWarnings(warn: ReturnType): string[] { - return warn.mock.calls - .map((call) => String(call[0])) - .filter((message) => message.includes('with no registered data handler')) -} - -afterEach(() => { - vi.restoreAllMocks() - clearPreHandlerPtyState(EVICTED_PTY_ID) - for (const ptyId of FILLER_PTY_IDS) { - clearPreHandlerPtyState(ptyId) - } -}) - -describe('pre-handler lost-handler warning after LRU eviction', () => { - it('warns again once the evicted PTY re-accumulates past the threshold', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - bufferPastWarnThreshold(EVICTED_PTY_ID) - expect(lostHandlerWarnings(warn)).toHaveLength(1) - - // Push the warned id out of the data map through the LRU cap. - for (const ptyId of FILLER_PTY_IDS) { - bufferPreHandlerPtyData(ptyId, 'y') - } - - // Its buffered bytes are gone, so this is a brand-new accumulation episode. - bufferPastWarnThreshold(EVICTED_PTY_ID) - - const messages = lostHandlerWarnings(warn) - expect(messages).toHaveLength(2) - expect(messages[1]).toContain(EVICTED_PTY_ID) - }) - - it('still warns only once while the buffered data is retained', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - bufferPastWarnThreshold(EVICTED_PTY_ID) - bufferPastWarnThreshold(EVICTED_PTY_ID) - bufferPastWarnThreshold(EVICTED_PTY_ID) - - expect(lostHandlerWarnings(warn)).toHaveLength(1) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-renderer-delivery-claims.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-renderer-delivery-claims.test.ts deleted file mode 100644 index 5da2177f1b2..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-renderer-delivery-claims.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - _resetPtyRendererDeliveryClaimsForTest, - acquireHiddenRendererPtyDeliveryClaim, - declareRendererPtyDeliveryVisible, - releaseRendererPtyVisibilityClaim, - setRendererPtyVisibilityClaim -} from './pty-renderer-delivery-claims' - -const PTY_ID = 'workspace@@pty-1' - -describe('renderer PTY delivery claims', () => { - const setHiddenRendererPty = vi.fn() - const setRendererPtyVisible = vi.fn() - - beforeEach(() => { - _resetPtyRendererDeliveryClaimsForTest() - setHiddenRendererPty.mockReset() - setRendererPtyVisible.mockReset() - ;(globalThis as { window: Window }).window = { - api: { pty: { setHiddenRendererPty, setRendererPtyVisible } } - } as unknown as Window - }) - - it('keeps a PTY hidden across an overlapping pane-to-watcher handoff', () => { - const releasePane = acquireHiddenRendererPtyDeliveryClaim(PTY_ID) - const releaseWatcher = acquireHiddenRendererPtyDeliveryClaim(PTY_ID) - - expect(setHiddenRendererPty).toHaveBeenCalledTimes(1) - expect(setHiddenRendererPty).toHaveBeenLastCalledWith(PTY_ID, true) - - releasePane() - expect(setHiddenRendererPty).toHaveBeenCalledTimes(1) - - declareRendererPtyDeliveryVisible(PTY_ID) - expect(setHiddenRendererPty).toHaveBeenCalledTimes(1) - - releaseWatcher() - expect(setHiddenRendererPty).toHaveBeenLastCalledWith(PTY_ID, false) - expect(setHiddenRendererPty).toHaveBeenCalledTimes(2) - }) - - it('does not let a retiring visible pane hide its replacement', () => { - const oldPane = {} - const newPane = {} - setRendererPtyVisibilityClaim(oldPane, PTY_ID, true) - setRendererPtyVisibilityClaim(newPane, PTY_ID, true) - - expect(setRendererPtyVisible).toHaveBeenCalledTimes(1) - releaseRendererPtyVisibilityClaim(oldPane) - expect(setRendererPtyVisible).toHaveBeenCalledTimes(1) - - releaseRendererPtyVisibilityClaim(newPane) - expect(setRendererPtyVisible).toHaveBeenLastCalledWith(PTY_ID, false) - expect(setRendererPtyVisible).toHaveBeenCalledTimes(2) - }) - - it('reports a never-visible mounted pane as known hidden', () => { - setRendererPtyVisibilityClaim({}, PTY_ID, false) - expect(setRendererPtyVisible).toHaveBeenCalledWith(PTY_ID, false) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/host-ownership/ssh-session-gone-verdict.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/host-ownership/ssh-session-gone-verdict.test.ts deleted file mode 100644 index ce421e072fa..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/host-ownership/ssh-session-gone-verdict.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { isSshSessionGoneError } from './ssh-session-gone-verdict' - -// Only host-proven absence authorizes retirement/cold resume; accepting unverifiable errors duplicates live transcripts (docs/reference/ssh-execution-boundary.md). -describe('the renderer verdict that licenses replacing a pane PTY', () => { - it('accepts the relay answering that this pane PTY is gone', () => { - expect(isSshSessionGoneError(new Error('SSH_SESSION_EXPIRED: ssh:conn-1@@pty-1'))).toBe(true) - }) - - // Owner mismatch proves another pane’s PTY is live, not this pane’s absence; renderer must agree with main’s isPtyAlreadyGoneError refusal. - it('refuses an identity mismatch, which names a live PTY owned by another pane', () => { - expect( - isSshSessionGoneError( - new Error('SSH_SESSION_EXPIRED: ssh:conn-1@@pty-1 SSH_PTY_IDENTITY_MISMATCH') - ) - ).toBe(false) - }) - - it('refuses an identity mismatch wrapped by the IPC boundary', () => { - expect( - isSshSessionGoneError( - "Error invoking remote method 'pty:spawn': Error: SSH_SESSION_EXPIRED: ssh:conn-1@@pty-1 SSH_PTY_IDENTITY_MISMATCH" - ) - ).toBe(false) - }) - - // Delivery loss for a live PTY stays unverifiable even if future wording accidentally includes the expiry token. - it('refuses a source-restore verdict for a PTY the relay just proved alive', () => { - expect( - isSshSessionGoneError( - new Error('SSH_PTY_SOURCE_RESTORE_REQUIRED: ssh:conn-1@@pty-1 checkpointUnavailable') - ) - ).toBe(false) - }) - - it.each([ - ['a lost link', 'SSH connection lost, reconnecting...'], - ['a request timeout', 'Request "pty.attach" timed out after 10000ms'], - ['a disposed multiplexer', 'Multiplexer disposed'] - ])('refuses %s', (_label, message) => { - expect(isSshSessionGoneError(new Error(message))).toBe(false) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-retention.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-retention.test.ts index cdc57785280..3a233d64f20 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-retention.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-retention.test.ts @@ -4,32 +4,6 @@ import { createPtyPreconnectInputBuffer } from './pty-preconnect-input-buffer' import { createDeferred } from '../../pty-connection/test-fixtures/pty-connection-test-async' describe('preconnect input lifetime', () => { - it('releases abort listeners after repeated successful flushes', async () => { - const controller = new AbortController() - const delivered: string[] = [] - for (let index = 0; index < 50; index += 1) { - const buffer = createPtyPreconnectInputBuffer() - const text = `paste-${index}` - const accepted = buffer.enqueueAccepted(text, 'driving', undefined, { - signal: controller.signal - }) - await buffer.flush({ - isCurrent: () => true, - sendInput: () => true, - sendInputImmediate: () => true, - sendInputAccepted: async (data) => { - delivered.push(data) - return true - } - }) - await expect(accepted).resolves.toBe(true) - expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0) - } - expect(delivered).toHaveLength(50) - controller.abort() - expect(delivered).toHaveLength(50) - }) - it('releases queued and active paste listeners on clear while a write is stalled', async () => { const controller = new AbortController() const buffer = createPtyPreconnectInputBuffer() diff --git a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts deleted file mode 100644 index f31379e63b9..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installIpcPtyWindow, restorePtySpecWindow } from './pty-transport-test-harness' - -const prompt = vi.hoisted(() => ({ answer: vi.fn() })) - -vi.mock('../../../agent-workspace-trust/agent-workspace-trust-decision-prompt', () => ({ - awaitAgentWorkspaceTrustDecision: prompt.answer -})) - -const CLAUDE_LAUNCH = { - worktreeId: 'repo-1::/repos/app', - launchAgent: 'claude', - command: 'claude' -} as const - -describe('createIpcPtyTransport: first-launch agent trust answer', () => { - const originalWindow: typeof window | undefined = globalThis.window - - beforeEach(() => { - vi.resetModules() - prompt.answer.mockReset() - installIpcPtyWindow(originalWindow, {}) - }) - - afterEach(() => { - restorePtySpecWindow(originalWindow) - }) - - async function connectClaude(): Promise { - const { createIpcPtyTransport } = await import('./pty-transport') - return createIpcPtyTransport(CLAUDE_LAUNCH).connect({ url: '', callbacks: {} }) - } - - it('spawns only after the answer, carrying "let agents ask" to main for this launch', async () => { - let answer: (value: 'agent-asks' | 'pre-trust' | null) => void = () => {} - prompt.answer.mockReturnValueOnce(new Promise((resolve) => (answer = resolve))) - - const { createIpcPtyTransport } = await import('./pty-transport') - const connecting = createIpcPtyTransport(CLAUDE_LAUNCH).connect({ url: '', callbacks: {} }) - await vi.waitFor(() => expect(prompt.answer).toHaveBeenCalled()) - expect(window.api.pty.spawn).not.toHaveBeenCalled() - answer('agent-asks') - await connecting - - expect(vi.mocked(window.api.pty.spawn).mock.calls[0]?.[0]).toMatchObject({ - skipAgentWorkspaceTrust: true - }) - }) - - it('reattaches a section terminal without asking or changing trust', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - await createIpcPtyTransport({ - ...CLAUDE_LAUNCH, - worktreeId: 'folder:placement', - trustWorktreeId: CLAUDE_LAUNCH.worktreeId - }).connect({ url: '', callbacks: {}, sessionId: 'existing-pty' }) - - expect(prompt.answer).not.toHaveBeenCalled() - expect(vi.mocked(window.api.pty.spawn).mock.calls[0]?.[0]).toMatchObject({ - sessionId: 'existing-pty', - worktreeId: 'folder:placement', - trustWorktreeId: CLAUDE_LAUNCH.worktreeId - }) - expect(vi.mocked(window.api.pty.spawn).mock.calls[0]?.[0]).not.toHaveProperty( - 'skipAgentWorkspaceTrust' - ) - }) - - it("spawns with today's default when the prompt is released without an answer", async () => { - prompt.answer.mockResolvedValueOnce(null) - - await connectClaude() - - expect(vi.mocked(window.api.pty.spawn).mock.calls[0]?.[0]).not.toHaveProperty( - 'skipAgentWorkspaceTrust' - ) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts deleted file mode 100644 index ee0d636ef7e..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installIpcPtyWindow, restorePtySpecWindow } from './pty-transport-test-harness' - -const RESUME = { key: 'session_id', id: 'provider-session-1' } as const - -describe('createIpcPtyTransport: restore spawn intent', () => { - const originalWindow: typeof window | undefined = globalThis.window - - beforeEach(() => { - vi.resetModules() - installIpcPtyWindow(originalWindow, {}) - }) - - afterEach(() => { - restorePtySpecWindow(originalWindow) - }) - - it('declares the intent only when the spawn resumes an agent', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - await createIpcPtyTransport().connect({ - url: '', - resumeProviderSession: RESUME, - resumeSpawnIntent: 'automatic-restore', - callbacks: {} - }) - await createIpcPtyTransport().connect({ - url: '', - resumeSpawnIntent: 'automatic-restore', - callbacks: {} - }) - const [resumed, plain] = vi.mocked(window.api.pty.spawn).mock.calls.map(([args]) => args) - expect(resumed).toMatchObject({ spawnIntent: 'automatic-restore' }) - expect(plain).not.toHaveProperty('spawnIntent') - }) - - it('reports a deferral to the pane instead of an error toast', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - vi.mocked(window.api.pty.spawn).mockRejectedValueOnce( - new Error("Error invoking remote method 'pty:spawn': Error: terminal_spawn_deferred:live_cap") - ) - const onError = vi.fn() - const onSpawnDeferred = vi.fn() - - const result = await createIpcPtyTransport().connect({ - url: '', - resumeProviderSession: RESUME, - resumeSpawnIntent: 'automatic-restore', - callbacks: { onError, onSpawnDeferred } - }) - - expect(result).toBeUndefined() - expect(onSpawnDeferred).toHaveBeenCalledWith('live_cap') - expect(onError).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/ipc/scan22-ssh-new-tab-disposed-spawn-kill.repro.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/ipc/scan22-ssh-new-tab-disposed-spawn-kill.repro.test.ts deleted file mode 100644 index b177ea4e5fb..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/ipc/scan22-ssh-new-tab-disposed-spawn-kill.repro.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installIpcPtyWindow, restorePtySpecWindow } from './pty-transport-test-harness' - -// Main reserves the same PTY for a remounted pane; killing a late predecessor spawn would close or disable the successor’s tab. -describe('scan22: disposed mid-spawn SSH transport vs successor on the same PTY', () => { - const originalWindow = (globalThis as { window?: typeof window }).window - beforeEach(() => { - vi.resetModules() - installIpcPtyWindow(originalWindow, {}) - }) - afterEach(() => restorePtySpecWindow(originalWindow)) - - it('does not kill the PTY the remounted successor is bound to', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - let resolveFirst: (value: { id: string }) => void = () => {} - const spawn = vi.mocked(window.api.pty.spawn) - spawn.mockImplementationOnce( - () => - new Promise((resolve) => { - resolveFirst = resolve - }) - ) - // Successor is handed the same id by main's (worktree, connection, paneKey) reservation. - spawn.mockResolvedValueOnce({ id: 'ssh-conn@@pty-7' }) - // As installPtyInputRecovery wires it: the tab and its leaf still exist in the store. - const paneOptions = { - connectionId: 'ssh-conn', - worktreeId: 'wt', - tabId: 'tab-2', - leafId: 'leaf-a', - retainDisposedSpawn: () => true - } - - const first = createIpcPtyTransport(paneOptions) - const firstConnect = first.connect({ url: '', callbacks: {} }) - // Pane remount (generation bump / recovery / park flip) while spawn is in flight. - first.destroy?.() - - const successor = createIpcPtyTransport(paneOptions) - await successor.connect({ url: '', callbacks: {} }) - expect(successor.getPtyId()).toBe('ssh-conn@@pty-7') - - resolveFirst({ id: 'ssh-conn@@pty-7' }) - await firstConnect - - expect(window.api.pty.kill).not.toHaveBeenCalledWith('ssh-conn@@pty-7') - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/output/terminal-output-visibility.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/output/terminal-output-visibility.test.ts deleted file mode 100644 index 8f2610d65ab..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/output/terminal-output-visibility.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - hasTerminalDisplayContent, - trimIncompleteTerminalControlTail -} from './terminal-output-visibility' - -describe('hasTerminalDisplayContent', () => { - it('treats title and agent-status OSC frames as metadata-only', () => { - expect(hasTerminalDisplayContent('\x1b]0;Restored title\x07')).toBe(false) - expect(hasTerminalDisplayContent('\x1b]9999;{"state":"working","agentType":"codex"}\x07')).toBe( - false - ) - }) - - it('treats unterminated metadata/control frames as metadata-only', () => { - expect(hasTerminalDisplayContent('\x1b]0;partial title')).toBe(false) - expect(hasTerminalDisplayContent('\x1b]9999;{"state":"working"')).toBe(false) - expect(hasTerminalDisplayContent('\x1b[31')).toBe(false) - }) - - it('treats styling-only control sequences as metadata-only', () => { - expect(hasTerminalDisplayContent('\x1b[31m\x1b[0m')).toBe(false) - expect(hasTerminalDisplayContent('\x1b[0 q\x1b[?25h')).toBe(false) - }) - - it('treats erase and alternate-screen sequences as display-affecting', () => { - expect(hasTerminalDisplayContent('\x1b[2J\x1b[H')).toBe(true) - expect(hasTerminalDisplayContent('\x1b[?1049h')).toBe(true) - expect(hasTerminalDisplayContent('\x1b#8')).toBe(true) - }) -}) - -describe('trimIncompleteTerminalControlTail', () => { - it('drops trailing partial control frames before replay', () => { - expect(trimIncompleteTerminalControlTail('\x1b]0;partial title')).toBe('') - expect(trimIncompleteTerminalControlTail('visible\x1b]0;partial title')).toBe('visible') - expect(trimIncompleteTerminalControlTail('visible\x1b[31')).toBe('visible') - }) - - it('keeps complete metadata and display frames intact', () => { - expect(trimIncompleteTerminalControlTail('\x1b]0;Restored title\x07')).toBe( - '\x1b]0;Restored title\x07' - ) - expect(trimIncompleteTerminalControlTail('\x1b[31mvisible')).toBe('\x1b[31mvisible') - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/recovery/server-outage/remote-server-notice-claims.test.tsx b/src/renderer/src/components/terminal-pane/pty-transport/recovery/server-outage/remote-server-notice-claims.test.tsx deleted file mode 100644 index 932ecdd3da7..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/recovery/server-outage/remote-server-notice-claims.test.tsx +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - resetRemoteServerNoticeClaimsForTests, - useRemoteServerNoticeClaim, - type RemoteServerNoticeClaim -} from './remote-server-notice-claims' - -const seen = new Map() - -function Surface({ - name, - environmentId, - visible = true -}: { - name: string - environmentId: string | null - visible?: boolean -}) { - seen.set(name, useRemoteServerNoticeClaim(environmentId, environmentId !== null, visible)) - return null -} - -afterEach(() => { - cleanup() - resetRemoteServerNoticeClaimsForTests() - seen.clear() - vi.useRealTimers() -}) - -describe('useRemoteServerNoticeClaim', () => { - it('lets one visible surface speak for a dropped server while the rest stay quiet', () => { - render( - <> - - - - - - ) - - expect(seen.get('hidden')).toMatchObject({ speaks: false, quiet: true }) - expect(seen.get('left')).toMatchObject({ speaks: true, quiet: true }) - expect(seen.get('right')).toMatchObject({ speaks: false, quiet: true }) - expect(seen.get('local')).toMatchObject({ speaks: false, quiet: false }) - }) - - it('keeps the outage start from a hidden tab when another tab becomes the speaker', () => { - vi.useFakeTimers() - vi.setSystemTime(1_000) - const view = render( - <> - - - - ) - expect(seen.get('front')).toMatchObject({ quiet: false, since: 1_000 }) - vi.setSystemTime(9_000) - - act(() => - view.rerender( - <> - - - - ) - ) - - expect(seen.get('front')).toMatchObject({ speaks: true, since: 1_000 }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-error-surface-dismissal.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-error-surface-dismissal.test.ts deleted file mode 100644 index 3809be2c912..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-error-surface-dismissal.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const appStore = vi.hoisted(() => ({ - getState: vi.fn(() => { - throw new Error('These transport fixtures must not read app-store ownership') - }) -})) - -vi.mock('@/store/index', () => ({ useAppStore: { getState: appStore.getState } })) - -afterEach(() => { - expect(appStore.getState).not.toHaveBeenCalled() -}) - -import { stubRuntimeEnvironmentBridge } from '../../../../runtime/rpc/testing/runtime-environment-bridge-fixture' - -// Dismissal re-arms identical errors; otherwise a later fatal recurrence in the same outage can leave a dead pane without a visible surface. -describe('remote runtime error surface dismissal', () => { - const runtimeCall = vi.fn() - const runtimeSubscribe = vi.fn() - const subscriptionSendBinary = vi.fn() - const FATAL_ERROR = 'Remote terminal rejected the write: permission denied.' - - beforeEach(() => { - vi.resetModules() - vi.clearAllMocks() - subscriptionSendBinary.mockReset() - runtimeCall.mockImplementation(async () => ({ ok: true, result: {} })) - runtimeSubscribe.mockImplementation( - async (_args: unknown, callbacks: { onResponse: (response: unknown) => void }) => { - queueMicrotask(() => callbacks.onResponse({ ok: true, result: { type: 'ready' } })) - return { unsubscribe: vi.fn(), sendBinary: subscriptionSendBinary } - } - ) - stubRuntimeEnvironmentBridge({ call: runtimeCall, subscribe: runtimeSubscribe }) - }) - - async function attachTransportWithFatalSends(onError: (message: string) => void) { - const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') - const transport = createRemoteRuntimePtyTransport('env-1', { worktreeId: 'wt-1' }) - transport.attach({ existingPtyId: 'remote:terminal-1', callbacks: { onError } }) - await vi.waitFor(() => expect(subscriptionSendBinary).toHaveBeenCalled()) - runtimeCall.mockImplementation(async (request: { method: string }) => { - if (request.method === 'terminal.send') { - throw new Error(FATAL_ERROR) - } - return { ok: true, result: {} } - }) - return transport - } - - it('re-surfaces an identical fatal error after the user dismisses the error surface', async () => { - const onError = vi.fn() - const transport = await attachTransportWithFatalSends(onError) - - expect(await transport.sendInputAccepted?.('a', 'driving')).toBe(false) - expect(await transport.sendInputAccepted?.('b', 'driving')).toBe(false) - // Contract preserved: one continuous outage still surfaces the repeated error once. - expect(onError.mock.calls).toEqual([[FATAL_ERROR]]) - - transport.notifyErrorSurfaceDismissed?.() - - expect(await transport.sendInputAccepted?.('c', 'driving')).toBe(false) - expect(onError.mock.calls).toEqual([[FATAL_ERROR], [FATAL_ERROR]]) - - // The memory re-arms: repeats after the re-surfaced error are suppressed again until the next dismissal. - expect(await transport.sendInputAccepted?.('d', 'driving')).toBe(false) - expect(onError).toHaveBeenCalledTimes(2) - transport.destroy?.() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-absence-evidence.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-absence-evidence.test.ts deleted file mode 100644 index 00c658e8713..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-absence-evidence.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createRemoteRuntimeTransportMocks } from '../remote/remote-runtime-pty-transport-test-harness' -import type { MultiplexSubscriptionCallbacks } from '../remote/remote-runtime-pty-transport-stream-fixtures' - -const appStore = vi.hoisted(() => ({ - getState: vi.fn(() => { - throw new Error('These transport fixtures must not read app-store ownership') - }) -})) - -vi.mock('@/store/index', () => ({ useAppStore: { getState: appStore.getState } })) - -afterEach(() => { - expect(appStore.getState).not.toHaveBeenCalled() -}) - -let subscriptionCallbacks: MultiplexSubscriptionCallbacks = null -let resolvedPaneHandle = 'terminal-1' - -const { runtimeCall, resetRemoteRuntimeTransport } = createRemoteRuntimeTransportMocks({ - getCallbacks: () => subscriptionCallbacks, - setCallbacks: (callbacks) => { - subscriptionCallbacks = callbacks - }, - getResolvedPaneHandle: () => resolvedPaneHandle, - setResolvedPaneHandle: (handle) => { - resolvedPaneHandle = handle - } -}) - -function readySnapshot(snapshotVersion: number): unknown { - return { - worktree: 'id:wt-1', - publicationEpoch: 'epoch-1', - snapshotVersion, - activeGroupId: 'group-1', - activeTabId: 'host-tab-1::leaf-1', - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: 'host-tab-1::leaf-1', - parentTabId: 'host-tab-1', - leafId: 'leaf-1', - title: 'Terminal 1', - isActive: true, - status: 'ready', - terminal: 'terminal-1' - } - ] - } -} - -describe('remote runtime pty transport host absence evidence', () => { - beforeEach(() => { - resetRemoteRuntimeTransport() - }) - - it('does not report a live host terminal as closed when activation answers tab_not_found', async () => { - runtimeCall.mockImplementation(async (args: { method: string }) => { - if (args.method === 'session.tabs.activate') { - // Why: a host still hydrating its worktree snapshot rejects with this before it republishes. - return { ok: false, error: { code: 'runtime_error', message: 'tab_not_found' } } - } - if (args.method === 'session.tabs.list') { - return { ok: true, result: readySnapshot(2) } - } - return { ok: true, result: {} } - }) - const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport') - const transport = createRemoteRuntimePtyTransport('env-1', { - worktreeId: 'wt-1', - tabId: 'web-terminal-host-tab-1', - leafId: 'leaf-1' - }) - - const onError = vi.fn() - const result = await transport.connect({ url: '', callbacks: { onError } }) - - expect(onError).not.toHaveBeenCalledWith('Remote terminal was closed.') - expect(result).toEqual({ - id: 'remote:env-1@@terminal-1', - replay: '', - isReattach: true - }) - expect(runtimeCall).not.toHaveBeenCalledWith( - expect.objectContaining({ method: 'terminal.create' }) - ) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/shutdown/pty-shutdown-output-queue.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/shutdown/pty-shutdown-output-queue.test.ts deleted file mode 100644 index bda38161202..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/shutdown/pty-shutdown-output-queue.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { PtyShutdownOutputQueue } from './pty-shutdown-output-queue' - -const BYTE_LIMIT = 524_288 - -describe('PTY shutdown output queue', () => { - it('keeps exact UTF-8 boundaries, Unicode tails, and metadata identity', () => { - const boundaryQueue = new PtyShutdownOutputQueue() - const emptyMeta = { rawLength: 9, transformed: true, droppedOutput: true } - boundaryQueue.enqueue({ kind: 'replay', data: 'a'.repeat(BYTE_LIMIT) }) - boundaryQueue.enqueue({ kind: 'data', data: '', meta: emptyMeta }) - boundaryQueue.enqueue({ kind: 'replay', data: 'b' }) - - const boundary = boundaryQueue.takeAll() - expect(boundary).toEqual([ - { kind: 'data', data: '', meta: emptyMeta }, - { kind: 'replay', data: 'b' } - ]) - expect(boundary[0]?.kind === 'data' ? boundary[0].meta : undefined).toBe(emptyMeta) - - const unicodeQueue = new PtyShutdownOutputQueue() - const emojiTail = '😀'.repeat(BYTE_LIMIT / 4) - const unicodeMeta = { seq: 7, rawLength: emojiTail.length + 1, background: true } - unicodeQueue.enqueue({ kind: 'data', data: `P${emojiTail}`, meta: unicodeMeta }) - const [unicode] = unicodeQueue.takeAll() - expect(unicode?.data).toBe(emojiTail) - expect(unicode?.kind === 'data' ? unicode.meta : undefined).toBe(unicodeMeta) - - const loneSurrogateQueue = new PtyShutdownOutputQueue() - const loneSurrogateTail = `\ud800${'z'.repeat(BYTE_LIMIT - 3)}` - loneSurrogateQueue.enqueue({ kind: 'replay', data: `P${loneSurrogateTail}` }) - expect(loneSurrogateQueue.takeAll()[0]?.data).toBe(loneSurrogateTail) - }) - - it('evicts whole oldest events without merging replay and live boundaries', () => { - const queue = new PtyShutdownOutputQueue() - const meta = { seq: 42, rawLength: BYTE_LIMIT - 3, transformed: true } - queue.enqueue({ kind: 'replay', data: 'old' }) - queue.enqueue({ kind: 'data', data: 'x'.repeat(BYTE_LIMIT - 3), meta }) - queue.enqueue({ kind: 'replay', data: 'new' }) - - const retained = queue.takeAll() - expect(retained).toEqual([ - { kind: 'data', data: 'x'.repeat(BYTE_LIMIT - 3), meta }, - { kind: 'replay', data: 'new' } - ]) - expect(retained[0]?.kind === 'data' ? retained[0].meta : undefined).toBe(meta) - }) - - it('retains zero-byte event boundaries without imposing a count cap', () => { - const queue = new PtyShutdownOutputQueue() - for (let index = 0; index < 4_097; index += 1) { - queue.enqueue({ kind: 'data', data: '', meta: { seq: index, transformed: true } }) - } - const retained = queue.takeAll() - expect(retained).toHaveLength(4_097) - expect(retained[0]).toEqual({ kind: 'data', data: '', meta: { seq: 0, transformed: true } }) - expect(retained.at(-1)).toEqual({ - kind: 'data', - data: '', - meta: { seq: 4_096, transformed: true } - }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/snapshots/merge-captured-leaf-state.test.ts b/src/renderer/src/components/terminal-pane/snapshots/merge-captured-leaf-state.test.ts deleted file mode 100644 index 3e0e941cc82..00000000000 --- a/src/renderer/src/components/terminal-pane/snapshots/merge-captured-leaf-state.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { mergeCapturedLeafState } from './merge-captured-leaf-state' - -describe('mergeCapturedLeafState', () => { - it('returns prior entries unchanged when fresh is empty (the wipe-protection case)', () => { - const result = mergeCapturedLeafState({ - prior: { 'pane:1': 'old-buf-1', 'pane:2': 'old-buf-2' }, - fresh: {}, - currentLeafIds: new Set(['pane:1', 'pane:2']) - }) - expect(result).toEqual({ 'pane:1': 'old-buf-1', 'pane:2': 'old-buf-2' }) - }) - - it('overlays fresh entries on top of prior entries', () => { - const result = mergeCapturedLeafState({ - prior: { 'pane:1': 'old-buf-1', 'pane:2': 'old-buf-2' }, - fresh: { 'pane:1': 'new-buf-1' }, - currentLeafIds: new Set(['pane:1', 'pane:2']) - }) - expect(result).toEqual({ 'pane:1': 'new-buf-1', 'pane:2': 'old-buf-2' }) - }) - - it('drops prior entries for leaves no longer present', () => { - const result = mergeCapturedLeafState({ - prior: { 'pane:1': 'old-buf-1', 'pane:removed': 'gone' }, - fresh: { 'pane:1': 'new-buf-1' }, - currentLeafIds: new Set(['pane:1']) - }) - expect(result).toEqual({ 'pane:1': 'new-buf-1' }) - expect(result).not.toHaveProperty('pane:removed') - }) - - it('returns empty when prior is undefined and fresh is empty', () => { - const result = mergeCapturedLeafState({ - prior: undefined, - fresh: {}, - currentLeafIds: new Set(['pane:1']) - }) - expect(result).toEqual({}) - }) - - it('returns fresh entries when prior is undefined', () => { - const result = mergeCapturedLeafState({ - prior: undefined, - fresh: { 'pane:1': 'fresh' }, - currentLeafIds: new Set(['pane:1']) - }) - expect(result).toEqual({ 'pane:1': 'fresh' }) - }) - - it('drops fresh entries for leaves outside currentLeafIds (defense in depth)', () => { - const result = mergeCapturedLeafState({ - prior: {}, - fresh: { 'pane:1': 'fresh', 'pane:rogue': 'should-be-dropped' }, - currentLeafIds: new Set(['pane:1']) - }) - expect(result).toEqual({ 'pane:1': 'fresh' }) - expect(result).not.toHaveProperty('pane:rogue') - }) -}) diff --git a/src/renderer/src/components/terminal-pane/snapshots/use-host-terminal-scrollback-hold.test.ts b/src/renderer/src/components/terminal-pane/snapshots/use-host-terminal-scrollback-hold.test.ts deleted file mode 100644 index 13d01ff393e..00000000000 --- a/src/renderer/src/components/terminal-pane/snapshots/use-host-terminal-scrollback-hold.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - HOST_TERMINAL_SCROLLBACK_HOLD_MS, - startHostTerminalScrollbackHydration -} from '@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration' -import { useHostTerminalScrollbackHold } from './use-host-terminal-scrollback-hold' - -vi.mock('@/runtime/hosted-terminals/hydration/host-terminal-scrollback-hydration', () => ({ - HOST_TERMINAL_SCROLLBACK_HOLD_MS: 3_000, - startHostTerminalScrollbackHydration: vi.fn() -})) -const start = vi.mocked(startHostTerminalScrollbackHydration) - -afterEach(() => { - cleanup() - start.mockReset() - vi.useRealTimers() -}) - -describe('useHostTerminalScrollbackHold', () => { - it('mounts at once when there is nothing to read from a host', () => { - start.mockReturnValue(null) - const { result } = renderHook(() => useHostTerminalScrollbackHold('tab-1', 'wt-1')) - expect(result.current).toBe(false) - }) - - it('holds the mount until the host read settles', async () => { - let settle = (): void => {} - start.mockReturnValue( - new Promise((resolve) => { - settle = resolve - }) - ) - const { result } = renderHook(() => useHostTerminalScrollbackHold('tab-1', 'wt-1')) - expect(result.current).toBe(true) - await act(async () => settle()) - expect(result.current).toBe(false) - expect(start).toHaveBeenCalledWith('tab-1', 'wt-1') - }) - - it('stops holding after the bound even if the host never answers', () => { - vi.useFakeTimers() - start.mockReturnValue(new Promise(() => {})) - const { result } = renderHook(() => useHostTerminalScrollbackHold('tab-1', 'wt-1')) - expect(result.current).toBe(true) - act(() => { - vi.advanceTimersByTime(HOST_TERMINAL_SCROLLBACK_HOLD_MS) - }) - expect(result.current).toBe(false) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/viewport/remote-desktop-viewport-claim.test.ts b/src/renderer/src/components/terminal-pane/viewport/remote-desktop-viewport-claim.test.ts deleted file mode 100644 index a135ca247e1..00000000000 --- a/src/renderer/src/components/terminal-pane/viewport/remote-desktop-viewport-claim.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { shouldClaimRemoteDesktopViewport } from './remote-desktop-viewport-claim' - -describe('shouldClaimRemoteDesktopViewport', () => { - it('requires a second, changed measurement from a focused visible pane', () => { - const current = { cols: 100, rows: 30 } - expect( - shouldClaimRemoteDesktopViewport({ - holdMode: 'remote-desktop-fit', - prior: null, - current, - paneGeometryChanged: false, - paneVisible: true, - documentVisible: true, - documentFocused: true - }) - ).toBe(false) - expect( - shouldClaimRemoteDesktopViewport({ - holdMode: 'remote-desktop-fit', - prior: { cols: 90, rows: 30 }, - current, - paneGeometryChanged: false, - paneVisible: true, - documentVisible: true, - documentFocused: true - }) - ).toBe(true) - }) - - it.each([ - { paneVisible: false, documentVisible: true, documentFocused: true }, - { paneVisible: true, documentVisible: false, documentFocused: true }, - { paneVisible: true, documentVisible: true, documentFocused: false } - ])('rejects passive background geometry: %o', (visibility) => { - expect( - shouldClaimRemoteDesktopViewport({ - holdMode: 'remote-desktop-fit', - prior: { cols: 90, rows: 30 }, - current: { cols: 100, rows: 30 }, - paneGeometryChanged: false, - ...visibility - }) - ).toBe(false) - }) - - it('accepts the first focused measurement after the observed pane box changed', () => { - expect( - shouldClaimRemoteDesktopViewport({ - holdMode: 'remote-desktop-fit', - prior: null, - current: { cols: 70, rows: 30 }, - paneGeometryChanged: true, - paneVisible: true, - documentVisible: true, - documentFocused: true - }) - ).toBe(true) - }) -}) diff --git a/src/renderer/src/components/terminal/pty-running-work-probe-child-evidence.test.ts b/src/renderer/src/components/terminal/pty-running-work-probe-child-evidence.test.ts deleted file mode 100644 index 0b5fc5d0640..00000000000 --- a/src/renderer/src/components/terminal/pty-running-work-probe-child-evidence.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -// hasChildProcesses=false can mean missing host evidence, especially legacy Windows relays; it must not alone prove idle. -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { inspectRuntimeTerminalProcessMock } = vi.hoisted(() => ({ - inspectRuntimeTerminalProcessMock: vi.fn() -})) - -vi.mock('@/runtime/hosted-terminals/inspection/runtime-terminal-process-inspection', () => ({ - inspectRuntimeTerminalProcess: inspectRuntimeTerminalProcessMock -})) - -import { probePtyRunningWork } from './pty-running-work-probe' - -describe('probePtyRunningWork child-process evidence', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('asks the host to pay for a scan, because these probes back destructive decisions', async () => { - inspectRuntimeTerminalProcessMock.mockResolvedValue({ - foregroundProcess: 'cmd.exe', - hasChildProcesses: false, - childProcessEvidence: 'no-children' - }) - - await probePtyRunningWork(['pty-a'], { timeoutMs: 1000 }) - - expect(inspectRuntimeTerminalProcessMock).toHaveBeenCalledWith('pty-a', { - scanChildProcesses: true - }) - }) - - it('reports a host that could not observe the pane as unverifiable, not exited', async () => { - inspectRuntimeTerminalProcessMock.mockResolvedValue({ - foregroundProcess: 'cmd.exe', - hasChildProcesses: false, - childProcessEvidence: 'unverifiable' - }) - - const [probe] = await probePtyRunningWork(['pty-a'], { timeoutMs: 1000 }) - - expect(probe).toMatchObject({ - verdict: 'unverifiable', - reason: 'host_child_processes_unobserved', - timedOut: false - }) - }) - - it('reports an observed-empty pane as exited', async () => { - inspectRuntimeTerminalProcessMock.mockResolvedValue({ - foregroundProcess: 'cmd.exe', - hasChildProcesses: false, - childProcessEvidence: 'no-children' - }) - - const [probe] = await probePtyRunningWork(['pty-a'], { timeoutMs: 1000 }) - - expect(probe?.verdict).toBe('exited') - }) - - it('reports an observed child as live', async () => { - inspectRuntimeTerminalProcessMock.mockResolvedValue({ - foregroundProcess: 'PING.EXE', - hasChildProcesses: true, - childProcessEvidence: 'children' - }) - - const [probe] = await probePtyRunningWork(['pty-a'], { timeoutMs: 1000 }) - - expect(probe?.verdict).toBe('live') - }) - - it('keeps the boolean meaning for a host that never published the verdict', async () => { - inspectRuntimeTerminalProcessMock.mockResolvedValueOnce({ - foregroundProcess: 'node', - hasChildProcesses: true - }) - inspectRuntimeTerminalProcessMock.mockResolvedValueOnce({ - foregroundProcess: 'bash', - hasChildProcesses: false - }) - - const [live] = await probePtyRunningWork(['pty-a'], { timeoutMs: 1000 }) - const [idle] = await probePtyRunningWork(['pty-b'], { timeoutMs: 1000 }) - - expect(live?.verdict).toBe('live') - expect(idle?.verdict).toBe('exited') - }) -}) diff --git a/src/renderer/src/components/use-terminal-browser-retention.test.tsx b/src/renderer/src/components/use-terminal-browser-retention.test.tsx deleted file mode 100644 index c6d5f062132..00000000000 --- a/src/renderer/src/components/use-terminal-browser-retention.test.tsx +++ /dev/null @@ -1,83 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { useRef, useState } from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const ACTIVE = 'wt-active' -const AGENT = 'wt-agent' -const RECENT_HIDDEN = ['wt-d', 'wt-c', 'wt-b', 'wt-a'] -const SURFACES = [ACTIVE, ...RECENT_HIDDEN, AGENT] -const SURFACE_ID_SET = new Set(SURFACES) - -const mocks = vi.hoisted(() => ({ destroyWorktreeBrowserGuests: vi.fn() })) - -vi.mock('../store', () => ({ - useAppStore: { - getState: () => ({ - browserTabsByWorktree: Object.fromEntries( - SURFACES.map((worktreeId) => [ - worktreeId, - [{ id: `tab-${worktreeId}`, pageIds: [`page-${worktreeId}`] }] - ]) - ), - browserPagesByWorkspace: {} - }) - } -})) -vi.mock('../store/slices/browser/cleanup/browser-webview-cleanup', () => ({ - destroyWorktreeBrowserGuests: (_tabs: unknown, _pages: unknown, worktreeId: string) => - mocks.destroyWorktreeBrowserGuests(worktreeId) -})) -vi.mock('./browser-pane/host-guest/webview-registry', () => ({ - hasLiveBrowserGuest: () => true -})) -vi.mock('./browser-pane/navigate/browser-page-download-activity', () => ({ - installBrowserPageDownloadActivityTracking: () => () => {}, - hasActiveBrowserPageDownload: () => false -})) - -const { acquireBrowserAutomationVisibility, releaseBrowserAutomationVisibility } = - await import('./browser-pane/host-guest/browser-automation-visibility') -const { useTerminalBrowserRetention } = await import('./use-terminal-browser-retention') - -function renderRetention(): void { - renderHook(() => { - const [revision, setRevision] = useState(0) - const recencyRef = useRef([...RECENT_HIDDEN]) - const mountedRef = useRef(new Set(SURFACES)) - useTerminalBrowserRetention({ - browserGuestRetentionBudgetEnabled: true, - browserGuestRetentionRevision: revision, - browserGuestWorktreeRecencyRef: recencyRef, - mountedWorktreeIdsRef: mountedRef, - renderedActiveWorktreeId: ACTIVE, - setBrowserGuestRetentionRevision: setRevision, - workspaceSurfaceIds: SURFACES, - workspaceSurfaceIdSet: SURFACE_ID_SET - }) - }) -} - -afterEach(() => { - cleanup() - mocks.destroyWorktreeBrowserGuests.mockReset() -}) - -describe('useTerminalBrowserRetention', () => { - it('keeps a hidden worktree an agent just drove when its automation lease lapses', () => { - renderRetention() - mocks.destroyWorktreeBrowserGuests.mockReset() - - let token = '' - act(() => { - token = acquireBrowserAutomationVisibility(`page-${AGENT}`) - }) - act(() => { - releaseBrowserAutomationVisibility(token) - }) - - const evicted = mocks.destroyWorktreeBrowserGuests.mock.calls.map(([worktreeId]) => worktreeId) - expect(evicted).not.toContain(AGENT) - expect(evicted).toContain('wt-a') - }) -}) diff --git a/src/renderer/src/hooks/installed-agent-skill-runtime-eviction.test.ts b/src/renderer/src/hooks/installed-agent-skill-runtime-eviction.test.ts deleted file mode 100644 index 17b1285ff8e..00000000000 --- a/src/renderer/src/hooks/installed-agent-skill-runtime-eviction.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import type { SkillDiscoveryResult } from '../../../shared/skills' - -const discover = vi.hoisted(() => vi.fn<() => Promise>()) -vi.mock('@/runtime/skills/configuration/runtime-skills-client', () => ({ - discoverSkillsForRuntimeTarget: discover -})) - -import { - discoverInstalledAgentSkills, - evictInstalledAgentSkillDiscoveryForRuntimeEnvironments, - getCachedSkillDiscovery, - getRuntimeScopedSkillDiscoveryKey, - resetSkillDiscoveryCacheForTests -} from './installed-agent-skill-discovery' - -const result = (scannedAt: number): SkillDiscoveryResult => ({ skills: [], sources: [], scannedAt }) -const runtime = (environmentId: string) => ({ kind: 'environment' as const, environmentId }) - -afterEach(() => { - resetSkillDiscoveryCacheForTests() - discover.mockReset() -}) - -it.each(['env', 'env"[,]'])( - 'evicts every filtered scan for %s without evicting other owners', - async (id) => { - const owner = runtime(id) - const other = runtime(`${id}-other`) - discover.mockResolvedValue(result(1)) - for (const names of [['alpha'], ['beta'], undefined]) { - await discoverInstalledAgentSkills(false, undefined, owner, names, ['home']) - } - await discoverInstalledAgentSkills(false, undefined, other, ['alpha'], ['home']) - await discoverInstalledAgentSkills(false, undefined, { kind: 'local' }, ['alpha'], ['home']) - - evictInstalledAgentSkillDiscoveryForRuntimeEnvironments([id]) - discover.mockResolvedValue(result(2)) - for (const names of [['alpha'], ['beta'], undefined]) { - const key = getRuntimeScopedSkillDiscoveryKey(owner, undefined, names, ['home']) - expect(getCachedSkillDiscovery(key)).toBeNull() - await expect( - discoverInstalledAgentSkills(false, undefined, owner, names, ['home']) - ).resolves.toEqual(result(2)) - } - await expect( - discoverInstalledAgentSkills(false, undefined, other, ['alpha'], ['home']) - ).resolves.toEqual(result(1)) - await expect( - discoverInstalledAgentSkills(false, undefined, { kind: 'local' }, ['alpha'], ['home']) - ).resolves.toEqual(result(1)) - expect(discover).toHaveBeenCalledTimes(8) - } -) - -it('keeps a retired filtered response from replacing the new peer cache', async () => { - let finishOld!: (value: SkillDiscoveryResult) => void - discover.mockReturnValueOnce( - new Promise((resolve) => { - finishOld = resolve - }) - ) - const owner = runtime('env') - const old = discoverInstalledAgentSkills(false, undefined, owner, ['alpha'], ['home']) - evictInstalledAgentSkillDiscoveryForRuntimeEnvironments(['env']) - discover.mockResolvedValue(result(2)) - await expect( - discoverInstalledAgentSkills(false, undefined, owner, ['alpha'], ['home']) - ).resolves.toEqual(result(2)) - finishOld(result(1)) - await old - await expect( - discoverInstalledAgentSkills(false, undefined, owner, ['alpha'], ['home']) - ).resolves.toEqual(result(2)) - expect(discover).toHaveBeenCalledTimes(2) -}) diff --git a/src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.profile-switch.test.ts b/src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.profile-switch.test.ts deleted file mode 100644 index 95da15b20a3..00000000000 --- a/src/renderer/src/hooks/ipc-events/browser-request-ipc-bridge.profile-switch.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -// @vitest-environment happy-dom -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - destroyPersistentWebview: vi.fn(), - getState: vi.fn(), - profileListener: null as - | ((data: { - requestId: string - browserPageId: string - profileId: string | null - sessionPartition: string | null - }) => void) - | null, - replyTabSetProfile: vi.fn(), - switchBrowserTabProfile: vi.fn() -})) - -vi.mock('@/components/browser-pane/host-guest/webview-registry', () => ({ - destroyPersistentWebview: mocks.destroyPersistentWebview -})) -vi.mock('../../store', () => ({ - useAppStore: { getState: mocks.getState } -})) -vi.mock('./browser-automation-bootstrap-lease', () => ({ - acquireBrowserAutomationBootstrapLease: vi.fn() -})) -vi.mock('../../store/slices/tabs/closing/pinned-tab-close-guard', () => ({ - guardPinnedTabClose: vi.fn(), - isUnifiedTabPinned: vi.fn(), - resolvePinnedTabLabel: vi.fn() -})) - -import { registerBrowserRequestIpcBridge } from './browser-request-ipc-bridge' - -describe('browser profile request teardown', () => { - beforeEach(() => { - mocks.destroyPersistentWebview.mockReset() - mocks.replyTabSetProfile.mockReset() - mocks.switchBrowserTabProfile.mockReset() - mocks.profileListener = null - mocks.getState.mockReturnValue({ - browserTabsByWorktree: { 'wt-1': [{ id: 'workspace-1' }] }, - browserPagesByWorkspace: { - 'workspace-1': [ - { id: 'page-url', docLocation: null }, - { - id: 'page-doc', - docLocation: { - kind: 'workspace-doc', - worktreeId: 'wt-1', - filePath: '/workspace/report.html' - } - } - ] - }, - switchBrowserTabProfile: mocks.switchBrowserTabProfile - }) - Object.defineProperty(window, 'api', { - configurable: true, - value: { - ui: { - onRequestTabCreate: () => () => {}, - onRequestRemoteCliBrowserScope: () => () => {}, - replyTabCreate: vi.fn(), - onRequestTabSetProfile: (listener: typeof mocks.profileListener) => { - mocks.profileListener = listener - return () => {} - }, - replyTabSetProfile: mocks.replyTabSetProfile, - onRequestTabClose: () => () => {}, - replyTabClose: vi.fn() - } - } - }) - }) - - it('keeps document-preview guests while rebuilding URL siblings for a profile change', () => { - registerBrowserRequestIpcBridge([]) - - mocks.profileListener?.({ - requestId: 'request-1', - browserPageId: 'page-url', - profileId: 'profile-2', - sessionPartition: 'persist:profile-2' - }) - - expect(mocks.destroyPersistentWebview).toHaveBeenCalledExactlyOnceWith('page-url') - expect(mocks.switchBrowserTabProfile).toHaveBeenCalledWith( - 'workspace-1', - 'profile-2', - 'persist:profile-2' - ) - expect(mocks.replyTabSetProfile).toHaveBeenCalledWith({ requestId: 'request-1' }) - }) -}) diff --git a/src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts b/src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts deleted file mode 100644 index 1d4b9b643ec..00000000000 --- a/src/renderer/src/hooks/legacy-worker-terminal-recovery-event.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { rollbackLegacyWorkerTerminalSurfaceInStore } from './legacy-worker-terminal-recovery-event' - -const LEAF_ID = '11111111-1111-4111-8111-111111111111' - -describe('legacy worker terminal recovery events', () => { - it('removes an unmounted split surface only when its PTY identity still matches', () => { - const setTabLayout = vi.fn() - const clearTabPtyId = vi.fn() - const closeTab = vi.fn() - const retireAgentPaneAuthority = vi.fn() - const siblingLeafId = '22222222-2222-4222-8222-222222222222' - const store = { - tabsByWorktree: { - worktree: [{ id: 'legacy-worker' }] - }, - terminalLayoutsByTabId: { - 'legacy-worker': { - root: { - type: 'split' as const, - direction: 'horizontal' as const, - ratio: 0.5, - first: { type: 'leaf' as const, leafId: LEAF_ID }, - second: { type: 'leaf' as const, leafId: siblingLeafId } - }, - activeLeafId: LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_ID]: 'pty-legacy', - [siblingLeafId]: 'pty-sibling' - } - } - }, - setTabLayout, - clearTabPtyId, - closeTab, - retireAgentPaneAuthority - } - - expect( - rollbackLegacyWorkerTerminalSurfaceInStore(store as never, { - lastPaneCloseReason: 'cleanup', - tabId: 'legacy-worker', - leafId: LEAF_ID, - preservePty: true, - expectedPtyId: 'pty-legacy' - }) - ).toBe('removed') - expect(setTabLayout).toHaveBeenCalledWith( - 'legacy-worker', - expect.objectContaining({ - root: { type: 'leaf', leafId: siblingLeafId }, - ptyIdsByLeafId: { [siblingLeafId]: 'pty-sibling' } - }) - ) - expect(clearTabPtyId).toHaveBeenCalledWith('legacy-worker', 'pty-legacy') - expect(retireAgentPaneAuthority).toHaveBeenCalledWith(`legacy-worker:${LEAF_ID}`, { - preserveSleepingAgentSession: true - }) - expect(closeTab).not.toHaveBeenCalled() - }) - - it('does not remove a replacement surface that reused the same pane', () => { - const setTabLayout = vi.fn() - const clearTabPtyId = vi.fn() - const closeTab = vi.fn() - const store = { - tabsByWorktree: { - worktree: [{ id: 'legacy-worker' }] - }, - terminalLayoutsByTabId: { - 'legacy-worker': { - root: { type: 'leaf' as const, leafId: LEAF_ID }, - activeLeafId: LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_ID]: 'pty-replacement' } - } - }, - setTabLayout, - clearTabPtyId, - closeTab - } - - expect( - rollbackLegacyWorkerTerminalSurfaceInStore(store as never, { - lastPaneCloseReason: 'cleanup', - tabId: 'legacy-worker', - leafId: LEAF_ID, - preservePty: true, - expectedPtyId: 'pty-legacy' - }) - ).toBe('identity-mismatch') - expect(setTabLayout).not.toHaveBeenCalled() - expect(clearTabPtyId).not.toHaveBeenCalled() - expect(closeTab).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/hooks/theme/use-system-prefers-dark.test.ts b/src/renderer/src/hooks/theme/use-system-prefers-dark.test.ts deleted file mode 100644 index 9b2099caad6..00000000000 --- a/src/renderer/src/hooks/theme/use-system-prefers-dark.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - getSystemPrefersDarkSnapshot, - resetSystemPrefersDarkSubscriptionForTests, - subscribeToSystemPrefersDarkChange -} from './use-system-prefers-dark' - -type MediaChangeListener = (event: MediaQueryListEvent) => void - -function installMatchMedia(initialMatches: boolean): { - media: { - addEventListener: ReturnType - removeEventListener: ReturnType - emit: (matches: boolean) => void - } - matchMedia: ReturnType -} { - let matches = initialMatches - const listeners = new Set() - const media = { - get matches() { - return matches - }, - addEventListener: vi.fn((type: string, listener: MediaChangeListener) => { - if (type === 'change') { - listeners.add(listener) - } - }), - removeEventListener: vi.fn((type: string, listener: MediaChangeListener) => { - if (type === 'change') { - listeners.delete(listener) - } - }), - emit(nextMatches: boolean): void { - matches = nextMatches - for (const listener of listeners) { - listener({ matches: nextMatches } as MediaQueryListEvent) - } - } - } - const matchMedia = vi.fn(() => media as unknown as MediaQueryList) - vi.stubGlobal('window', { matchMedia }) - return { media, matchMedia } -} - -afterEach(() => { - resetSystemPrefersDarkSubscriptionForTests() - vi.unstubAllGlobals() -}) - -describe('useSystemPrefersDark subscription store', () => { - it('caches the initial media query snapshot', () => { - const { matchMedia } = installMatchMedia(false) - - expect(getSystemPrefersDarkSnapshot()).toBe(false) - expect(getSystemPrefersDarkSnapshot()).toBe(false) - expect(matchMedia).toHaveBeenCalledTimes(1) - }) - - it('shares one media query listener across subscribers', () => { - const { media, matchMedia } = installMatchMedia(true) - const firstSubscriber = vi.fn() - const secondSubscriber = vi.fn() - - const unsubscribeFirst = subscribeToSystemPrefersDarkChange(firstSubscriber) - const unsubscribeSecond = subscribeToSystemPrefersDarkChange(secondSubscriber) - - expect(matchMedia).toHaveBeenCalledTimes(1) - expect(media.addEventListener).toHaveBeenCalledTimes(1) - - media.emit(false) - - expect(getSystemPrefersDarkSnapshot()).toBe(false) - expect(firstSubscriber).toHaveBeenCalledTimes(1) - expect(secondSubscriber).toHaveBeenCalledTimes(1) - - unsubscribeFirst() - expect(media.removeEventListener).not.toHaveBeenCalled() - - media.emit(true) - - expect(getSystemPrefersDarkSnapshot()).toBe(true) - expect(firstSubscriber).toHaveBeenCalledTimes(1) - expect(secondSubscriber).toHaveBeenCalledTimes(2) - - unsubscribeSecond() - expect(media.removeEventListener).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/hooks/use-window-stream-visibility.test.ts b/src/renderer/src/hooks/use-window-stream-visibility.test.ts index 538378a2d6b..4c177d2b0bb 100644 --- a/src/renderer/src/hooks/use-window-stream-visibility.test.ts +++ b/src/renderer/src/hooks/use-window-stream-visibility.test.ts @@ -27,18 +27,6 @@ describe('useWindowStreamVisible', () => { vi.restoreAllMocks() }) - it('parks only after the grace period elapses', async () => { - const hook = renderHook(() => useWindowStreamVisible()) - expect(hook.result.current).toBe(true) - - await act(async () => setDocumentVisibility('hidden')) - await act(async () => vi.advanceTimersByTime(WINDOW_STREAM_PARK_DELAY_MS - 1)) - expect(hook.result.current).toBe(true) - - await act(async () => vi.advanceTimersByTime(1)) - expect(hook.result.current).toBe(false) - }) - // Stale-visibility evidence must reopen streams when macOS occlusion updates stop. it('treats a wedged hidden document as visible once user input disproves it', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -54,13 +42,4 @@ describe('useWindowStreamVisible', () => { expect(document.visibilityState).toBe('hidden') expect(hook.result.current).toBe(true) }) - - it('does not report visible while mounted into a hidden window', async () => { - setDocumentVisibility('hidden') - const hook = renderHook(() => useWindowStreamVisible()) - expect(hook.result.current).toBe(false) - - await act(async () => setDocumentVisibility('visible')) - expect(hook.result.current).toBe(true) - }) }) diff --git a/src/renderer/src/lib/agent-session/hibernation/agent-hibernation-twin-host.test.ts b/src/renderer/src/lib/agent-session/hibernation/agent-hibernation-twin-host.test.ts deleted file mode 100644 index c0591e6cf33..00000000000 --- a/src/renderer/src/lib/agent-session/hibernation/agent-hibernation-twin-host.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { runAgentHibernationTick } from './agent-hibernation-coordinator' -import { - entry, - installEligibleState, - installRuntimeListResponses, - LEAF, - mockRuntimeEnvironmentCall, - resetAgentHibernationCoordinatorFixture, - runtimeListResult, - tab -} from './agent-hibernation-coordinator-test-fixture' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' - -afterEach(resetAgentHibernationCoordinatorFixture) - -// One repo id + path published by both an SSH host and a managed runtime (mid-migration). -const twinRows = { - 'fixture-repo': [ - makeWorktree({ id: 'wt-bg', repoId: 'fixture-repo', hostId: 'ssh:ssh-1' }), - makeWorktree({ - id: 'wt-bg', - repoId: 'fixture-repo', - hostId: 'local', - runtimeOwnerEnvironmentId: 'runtime-1' - }) - ] -} - -function installTwin(ptyId: string) { - return installEligibleState(vi.fn().mockResolvedValue(undefined), { - worktreesByRepo: twinRows, - tabsByWorktree: { 'wt-bg': [tab()] }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { type: 'leaf', leafId: LEAF }, - activeLeafId: LEAF, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF]: ptyId } - } - }, - ptyIdsByTabId: { 'tab-1': [ptyId] }, - agentStatusByPaneKey: { [entry().paneKey]: entry() } - }) -} - -function listSelectors(): string[] { - return mockRuntimeEnvironmentCall.mock.calls - .map(([args]) => args) - .filter((args) => args.method === 'terminal.list') - .map((args) => ('selector' in args ? String(args.selector) : '')) -} - -describe('agent sleep coordinator with a twin-published worktree', () => { - it('asks the runtime the PTY names for liveness and hands the pane its exact stop', async () => { - installRuntimeListResponses(runtimeListResult(['pty-1']), runtimeListResult(['pty-1'])) - const shutdown = installTwin('remote:runtime-1@@pty-1') - - await runAgentHibernationTick() - await runAgentHibernationTick() - - expect(new Set(listSelectors())).toEqual(new Set(['runtime-1'])) - expect(shutdown).toHaveBeenCalledWith('wt-bg', { - paneKey: `tab-1:${LEAF}`, - tabId: 'tab-1', - leafId: LEAF, - ptyId: 'remote:runtime-1@@pty-1', - expectedRuntimePtyId: 'pty-1' - }) - }) - - it('never hibernates a remote PTY whose runtime it cannot name', async () => { - installRuntimeListResponses() - const shutdown = installTwin('remote:pty-1') - - await runAgentHibernationTick() - await runAgentHibernationTick() - - expect(listSelectors()).toEqual([]) - expect(shutdown).not.toHaveBeenCalled() - }) - - it('hibernates an SSH-host PTY locally, without a runtime stop', async () => { - installRuntimeListResponses() - const shutdown = installTwin('ssh:ssh-1@@pty-1') - - await runAgentHibernationTick() - await runAgentHibernationTick() - - expect(listSelectors()).toEqual([]) - expect(shutdown).toHaveBeenCalledWith('wt-bg', { - paneKey: `tab-1:${LEAF}`, - tabId: 'tab-1', - leafId: LEAF, - ptyId: 'ssh:ssh-1@@pty-1' - }) - }) -}) diff --git a/src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts b/src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts deleted file mode 100644 index a581e2b6725..00000000000 --- a/src/renderer/src/lib/agent-session/hibernation/agent-hibernation-visibility.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - startAgentHibernationCoordinator, - stopAgentHibernationCoordinator -} from './agent-hibernation-coordinator' -import { resetStaleDocumentVisibilityForTesting } from '@/components/terminal-pane/viewport/visibility/stale-document-visibility' - -function setVisibility(state: 'visible' | 'hidden'): void { - Object.defineProperty(document, 'visibilityState', { value: state, configurable: true }) - document.dispatchEvent(new Event('visibilitychange')) -} - -describe('agent hibernation coordinator visibility wiring', () => { - beforeEach(() => { - setVisibility('visible') - resetStaleDocumentVisibilityForTesting() - }) - afterEach(async () => { - const { resetAgentHibernationCoordinatorFixture } = - await import('./agent-hibernation-coordinator-test-fixture') - resetAgentHibernationCoordinatorFixture() - resetStaleDocumentVisibilityForTesting() - setVisibility('visible') - vi.unstubAllGlobals() - vi.restoreAllMocks() - }) - - it('subscribes to the becoming-visible pass on start and unsubscribes on stop', async () => { - // Keep happy-dom's event target when the state fixture stubs window. - const browserWindow = window - const { installEligibleState, NOW, LEAF } = - await import('./agent-hibernation-coordinator-test-fixture') - vi.stubGlobal('window', browserWindow) - vi.useFakeTimers() - const shutdown = installEligibleState(vi.fn().mockResolvedValue(undefined)) - - startAgentHibernationCoordinator({ intervalMs: 1_000, now: () => NOW }) - await vi.advanceTimersByTimeAsync(1_000) - expect(shutdown).not.toHaveBeenCalled() - - setVisibility('hidden') - await vi.advanceTimersByTimeAsync(3_000) - expect(shutdown).not.toHaveBeenCalled() - - setVisibility('visible') - await vi.advanceTimersByTimeAsync(0) - expect(shutdown).toHaveBeenCalledExactlyOnceWith('wt-bg', { - paneKey: `tab-1:${LEAF}`, - tabId: 'tab-1', - leafId: LEAF, - ptyId: 'pty-1' - }) - - shutdown.mockClear() - stopAgentHibernationCoordinator() - setVisibility('hidden') - setVisibility('visible') - await vi.advanceTimersByTimeAsync(0) - setVisibility('hidden') - setVisibility('visible') - await vi.advanceTimersByTimeAsync(3_000) - expect(shutdown).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts b/src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts deleted file mode 100644 index a3cabcf222c..00000000000 --- a/src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' -import { cleanupFailedEphemeralVmWorkspace } from './ephemeral-vm-failed-create-cleanup' - -function request(): WorktreeCreationRequest { - return { - repoId: 'repo-1', - name: 'feature', - setupDecision: 'inherit', - agent: null, - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null, - ephemeralVmRuntimeId: 'runtime-1', - ephemeralVmCheckoutMode: 'provisioned-root', - workspaceRunContext: { - kind: 'workspace-run', - projectId: 'project-1', - hostId: 'ssh:runtime-ssh-1', - projectHostSetupId: 'setup-1', - repoId: 'repo-1', - path: '/workspace/repo' - } - } -} - -describe('cleanupFailedEphemeralVmWorkspace', () => { - it('removes the imported project setup before destroying its VM', async () => { - const order: string[] = [] - await cleanupFailedEphemeralVmWorkspace(request(), { - deleteProjectHostSetup: vi.fn(async () => { - order.push('setup') - return { id: 'setup-1' } - }), - cleanupRuntime: vi.fn(async () => { - order.push('runtime') - }), - reportSetupError: vi.fn(), - reportRuntimeError: vi.fn() - }) - - expect(order).toEqual(['setup', 'runtime']) - }) - - it('retains the VM when setup deletion throws', async () => { - const cleanupRuntime = vi.fn().mockResolvedValue(undefined) - const reportSetupError = vi.fn() - await cleanupFailedEphemeralVmWorkspace(request(), { - deleteProjectHostSetup: vi.fn().mockRejectedValue(new Error('setup delete failed')), - cleanupRuntime, - reportSetupError, - reportRuntimeError: vi.fn() - }) - - expect(reportSetupError).toHaveBeenCalledOnce() - expect(cleanupRuntime).not.toHaveBeenCalled() - }) - - it('retains the VM when setup deletion reports no result', async () => { - const cleanupRuntime = vi.fn().mockResolvedValue(undefined) - const reportSetupError = vi.fn() - await cleanupFailedEphemeralVmWorkspace(request(), { - deleteProjectHostSetup: vi.fn().mockResolvedValue(null), - cleanupRuntime, - reportSetupError, - reportRuntimeError: vi.fn() - }) - - expect(reportSetupError).toHaveBeenCalledOnce() - expect(cleanupRuntime).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/monaco-languages/markdown-textmate-tokens.test.ts b/src/renderer/src/lib/monaco-languages/markdown-textmate-tokens.test.ts deleted file mode 100644 index 6d3265b2a42..00000000000 --- a/src/renderer/src/lib/monaco-languages/markdown-textmate-tokens.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import type * as Monaco from 'monaco-editor' -import { describe, expect, it, vi } from 'vitest' -import { loadNodeOniguruma } from '../syntax-highlighting/oniguruma-test-harness' -import { createMarkdownTokensProvider } from './markdown-textmate-tokens' - -vi.mock('../syntax-highlighting/oniguruma', () => ({ loadOniguruma: loadNodeOniguruma })) - -function tokenizeLines(provider: Monaco.languages.TokensProvider, lines: string[]): string[][] { - let state = provider.getInitialState() - return lines.map((line) => { - const result = provider.tokenize(line, state) - state = result.endState - return result.tokens.map((token) => token.scopes) - }) -} - -describe('createMarkdownTokensProvider', () => { - it('styles markdown with Dark+ rules and highlights a fence once its grammar loads', async () => { - const defineTheme = vi.fn() - let replacement: Monaco.languages.TokensProvider | undefined - const provider = await createMarkdownTokensProvider({ - editor: { defineTheme }, - languages: { - setTokensProvider: (_language, next) => { - if ('tokenize' in next && 'getInitialState' in next && !('tokenizeEncoded' in next)) { - replacement = next - } - return { dispose: () => {} } - } - } - }) - - expect(defineTheme).toHaveBeenCalledWith( - 'vs-dark', - expect.objectContaining({ - rules: expect.arrayContaining([ - { token: 'md.markup.heading', foreground: '#569cd6', fontStyle: 'bold' } - ]) - }) - ) - const [heading, list] = tokenizeLines(provider, ['## Quick', '- **State:** open']) - expect(new Set(heading)).toEqual( - new Set([ - 'md.punctuation.definition.heading.markdown', - 'md.markup.heading.markdown', - 'md.entity.name.section.markdown' - ]) - ) - expect(list).toEqual([ - 'md.punctuation.definition.list.begin.markdown', - 'md.text.html.markdown', - 'md.markup.bold.markdown', - 'md.markup.bold.markdown', - 'md.markup.bold.markdown', - 'md.text.html.markdown' - ]) - - const fence = ['```ts', 'const x = 1', '```'] - tokenizeLines(provider, fence) - const refreshed = await vi.waitFor(() => { - if (!replacement) { - throw new Error('fence grammar has not loaded') - } - return replacement - }) - expect(tokenizeLines(refreshed, ['```ts title="a.ts"', 'const x = 1', '```'])[1]).toContain( - 'md.storage.type.ts' - ) - }) -}) diff --git a/src/renderer/src/lib/pending-worktree-creation.test.ts b/src/renderer/src/lib/pending-worktree-creation.test.ts deleted file mode 100644 index c43bc740715..00000000000 --- a/src/renderer/src/lib/pending-worktree-creation.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - findPendingLinkedWorkItemCreationId, - findPendingWorktreeCreationId, - type PendingWorktreeCreation, - type WorktreeCreationRequest -} from './workspace/creation/pending-worktree-creation' - -function request(overrides: Partial = {}): WorktreeCreationRequest { - return { - repoId: 'repo-1', - name: 'workspace', - setupDecision: 'inherit', - agent: null, - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null, - ...overrides - } -} - -function pending( - creationId: string, - creationRequest: WorktreeCreationRequest -): PendingWorktreeCreation { - return { - creationId, - phase: 'preparing', - status: 'creating', - startedAt: 1, - indeterminate: false, - loaderVisible: true, - request: creationRequest - } -} - -describe('findPendingWorktreeCreationId', () => { - it('matches Windows path spelling while keeping repositories distinct', () => { - const entry = { - ...pending('create-1', request()), - worktreeId: 'repo-1::C:\\workspaces\\feature' - } - expect(findPendingWorktreeCreationId({ entry }, 'repo-1::c:/workspaces/feature/')).toBe( - 'create-1' - ) - expect(findPendingWorktreeCreationId({ entry }, 'repo-2::c:/workspaces/feature/')).toBeNull() - }) -}) - -describe('findPendingLinkedWorkItemCreationId', () => { - it('deduplicates the same linked item on the same execution host', () => { - const existing = request({ - linkedIssue: 42, - workspaceRunContext: { - kind: 'workspace-run', - projectId: 'project-1', - hostId: 'ssh:server', - projectHostSetupId: 'setup-1', - repoId: 'repo-1', - path: '/repo' - } - }) - - expect( - findPendingLinkedWorkItemCreationId( - { existing: pending('existing', existing) }, - request({ - linkedIssue: 42, - workspaceRunContext: { - ...existing.workspaceRunContext!, - path: '/renamed-repo' - } - }) - ) - ).toBe('existing') - }) - - it('keeps the same linked item on different execution hosts distinct', () => { - const existing = request({ - linkedPR: 77, - workspaceRunContext: { - kind: 'workspace-run', - projectId: 'project-1', - hostId: 'ssh:server-a', - projectHostSetupId: 'setup-a', - repoId: 'repo-1', - path: '/repo' - } - }) - - expect( - findPendingLinkedWorkItemCreationId( - { existing: pending('existing', existing) }, - request({ - linkedPR: 77, - workspaceRunContext: { - ...existing.workspaceRunContext!, - hostId: 'ssh:server-b', - projectHostSetupId: 'setup-b' - } - }) - ) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/lib/settled-worker-wake-policy.test.ts b/src/renderer/src/lib/settled-worker-wake-policy.test.ts deleted file mode 100644 index 05b63f44d45..00000000000 --- a/src/renderer/src/lib/settled-worker-wake-policy.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { resumeSleepingAgentSessionsForWorktree } from './agent-session/resume/resume-sleeping-agent-session' - -// Main's answer to the window's layout commands, as a switch-on build sends them. -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) - -const initialState = useAppStore.getState() - -afterEach(() => { - vi.unstubAllGlobals() - useAppStore.setState(initialState, true) -}) - -it('resumes a settled worker and an ordinary agent once each in the same wake sweep', () => { - const records = ['settled-worker', 'ordinary-agent'].map((id) => ({ - paneKey: `${id}:leaf`, - tabId: id, - worktreeId: 'wt-1', - agent: 'claude' as const, - providerSession: { key: 'session_id' as const, id }, - prompt: 'continue the session', - state: 'working' as const, - capturedAt: Date.now(), - updatedAt: Date.now(), - origin: 'quit' as const, - // Old clients can still publish the withdrawn policy field. - ...(id === 'settled-worker' ? { automaticResumeBlockedBy: 'legacy-orchestration-worker' } : {}) - })) - useAppStore.setState({ - tabsByWorktree: { 'wt-1': [] }, - sleepingAgentSessionsByPaneKey: Object.fromEntries(records.map((r) => [r.paneKey, r])) - }) - - expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(2) - expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(0) - const state = useAppStore.getState() - const tabs = state.tabsByWorktree['wt-1'] - expect(tabs).toHaveLength(2) - const commands = tabs.map((tab) => state.pendingStartupByTabId[tab.id]?.command ?? '') - for (const record of records) { - expect(commands.filter((command) => command.includes(record.providerSession.id))).toHaveLength( - 1 - ) - } - for (const command of commands) { - expect(command.match(/--resume/g)).toHaveLength(1) - } - expect(state.sleepingAgentSessionsByPaneKey).toEqual({}) -}) diff --git a/src/renderer/src/lib/typing-latency/input-events.test.ts b/src/renderer/src/lib/typing-latency/input-events.test.ts deleted file mode 100644 index 6979e9f3c04..00000000000 --- a/src/renderer/src/lib/typing-latency/input-events.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// @vitest-environment happy-dom -import { XTERM_COMPOSITION_SESSION_END_EVENT } from '@/components/terminal-pane/input/ime/terminal-ime-composition-route' -import { afterEach, describe, expect, it } from 'vitest' -import { installTypingLatencyInputEvents, type TypingInputSignal } from './input-events' - -function keydown(init: KeyboardEventInit): void { - window.dispatchEvent(new KeyboardEvent('keydown', init)) -} - -function sessionEnd(data: string, dataPendingReconciliation = false): void { - window.dispatchEvent( - new CustomEvent(XTERM_COMPOSITION_SESSION_END_EVENT, { - detail: { id: 1, data, dataPendingReconciliation } - }) - ) -} - -describe('installTypingLatencyInputEvents', () => { - let detach: (() => void) | null = null - - afterEach(() => { - detach?.() - detach = null - document.body.replaceChildren() - }) - - it('classifies direct keys and ignores IME-owned preedit keydowns', () => { - const signals: TypingInputSignal[] = [] - detach = installTypingLatencyInputEvents(window, (signal) => { - signals.push(signal) - }) - - keydown({ key: 'Process', code: 'KeyG', isComposing: true }) - keydown({ key: 'a', code: 'KeyA', isComposing: true }) - keydown({ key: '@', code: 'Digit2', keyCode: 229 }) - keydown({ key: 'Shift', code: 'ShiftLeft' }) - keydown({ key: 'a', code: 'KeyA' }) - keydown({ key: 'Enter', code: 'Enter' }) - - expect(signals.map(({ source, text }) => ({ source, text }))).toEqual([ - { source: 'direct', text: 'a' }, - { source: 'direct', text: 'Enter' } - ]) - }) - - it('uses reconciled xterm session data instead of raw compositionend data', () => { - const signals: TypingInputSignal[] = [] - detach = installTypingLatencyInputEvents(window, (signal) => { - signals.push(signal) - }) - - window.dispatchEvent(new CompositionEvent('compositionend', { data: '', bubbles: true })) - sessionEnd('') - sessionEnd('stale', true) - sessionEnd('한') - - expect(signals.map(({ source, text }) => ({ source, text }))).toEqual([ - { source: 'ime', text: '한' } - ]) - }) - - it('settles prevented and unprevented commits once after propagation', () => { - const terminalElement = document.createElement('div') - document.body.appendChild(terminalElement) - const settlements: boolean[] = [] - detach = installTypingLatencyInputEvents(window, (signal) => - signal.source === 'ime' - ? { settleAfterPropagation: (defaultPrevented) => settlements.push(defaultPrevented) } - : undefined - ) - - const dispatchSessionEnd = (): void => { - terminalElement.dispatchEvent( - new CustomEvent(XTERM_COMPOSITION_SESSION_END_EVENT, { - bubbles: true, - cancelable: true, - detail: { id: 1, data: '한' } - }) - ) - } - dispatchSessionEnd() - - terminalElement.addEventListener(XTERM_COMPOSITION_SESSION_END_EVENT, (event) => - event.preventDefault() - ) - dispatchSessionEnd() - - expect(settlements).toEqual([false, true]) - }) -}) diff --git a/src/renderer/src/lib/worker-auto-close.test.ts b/src/renderer/src/lib/worker-auto-close.test.ts deleted file mode 100644 index edd50c7e192..00000000000 --- a/src/renderer/src/lib/worker-auto-close.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// @vitest-environment happy-dom - -import { act, createElement } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { WorkerAutoCloseState } from '../../../shared/worker-auto-close' - -const mocks = vi.hoisted(() => ({ - worker: Boolean(true) -})) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: vi.fn(async () => ({ - autoClose: { kept: false, closesAt: '2026-10-27T12:02:00Z' } - })) -})) -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ - runtimeEnvironmentSupportsCapability: vi.fn(async () => true) -})) -vi.mock('@/runtime/hosts/capabilities/local-runtime-capabilities', () => ({ - ensureLocalRuntimeCapabilities: vi.fn(async () => {}), - readLocalRuntimeCapabilitiesOrUnknown: () => ['orchestration.worker-keep-open.v1'] -})) -vi.mock('@/runtime/visible-agent-orchestration', () => ({ - selectVisibleAgentOrchestration: () => - mocks.worker - ? { 'tab:leaf': { taskId: 't', dispatchId: 'd', dispatchStatus: 'completed' } } - : {} -})) -vi.mock('@/store', () => ({ - useAppStore: (select: (state: unknown) => unknown) => select({ agentStatusByPaneKey: {} }) -})) - -import { useWorkerAutoClose } from './worker-auto-close' - -const TARGET = { kind: 'local' as const } -const SUBJECT = { paneKey: 'tab:leaf' } -let latest: WorkerAutoCloseState | null = null - -function Probe(): null { - latest = useWorkerAutoClose(TARGET, SUBJECT, 'tab:leaf', true).state - return null -} - -describe('useWorkerAutoClose', () => { - let root: Root | undefined - afterEach(() => { - act(() => root?.unmount()) - vi.useRealTimers() - }) - - it('stops its countdown clock and forgets the state once the pane is no longer a worker', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] }) - root = createRoot(document.createElement('div')) - await act(async () => root!.render(createElement(Probe))) - await act(async () => vi.advanceTimersByTimeAsync(0)) - expect(latest).toEqual({ kept: false, closesAt: '2026-10-27T12:02:00Z' }) - - mocks.worker = false - await act(async () => root!.render(createElement(Probe))) - - expect(latest).toBeNull() - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation-leave-visit.test.ts b/src/renderer/src/lib/workspace/activation/worktree-activation-leave-visit.test.ts deleted file mode 100644 index dbe6c4e3e7b..00000000000 --- a/src/renderer/src/lib/workspace/activation/worktree-activation-leave-visit.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../../../shared/worktree/types' -import { useAppStore } from '@/store/index' -import { activateAndRevealWorktree } from './worktree-activation' -import { getWorktreeVisitKey } from '../../worktree-visit-recency' - -vi.mock('../../../../../shared/sidebar-inputs-switch', () => ({ - ORCA_SIDEBAR_INPUTS_IS_MAIN: true -})) - -const initialAppStoreState = useAppStore.getState() - -afterEach(() => { - useAppStore.setState(initialAppStoreState, true) - vi.useRealTimers() -}) - -function worktree(name: string): Worktree { - return { - id: `repo-1::/workspace/${name}`, - repoId: 'repo-1', - path: `/workspace/${name}`, - head: 'abc123', - branch: `refs/heads/${name}`, - isBare: false, - isMainWorktree: false, - displayName: name, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 - } -} - -describe('switching workspaces with the sidebar-inputs switch on', () => { - it('marks the workspace you leave as used up to now, just before the one you open', () => { - vi.useFakeTimers({ now: 50_000, toFake: ['Date'] }) - const shells = worktree('shells') - const next = worktree('next') - useAppStore.setState({ - repos: [ - { id: 'repo-1', path: '/workspace/repo', displayName: 'repo', badgeColor: '', addedAt: 0 } - ], - worktreesByRepo: { 'repo-1': [shells, next] }, - activeRepoId: 'repo-1', - activeView: 'terminal', - activeWorktreeId: shells.id, - activeWorkspaceExecutionHostId: 'local', - tabsByWorktree: { [shells.id]: [], [next.id]: [] }, - ptyIdsByTabId: {}, - everActivatedWorktreeIds: new Set([shells.id, next.id]), - lastVisitedAtByWorktreeId: {}, - refreshGitHubForWorktreeIfStale: vi.fn() - }) - - activateAndRevealWorktree(next.id) - - expect(useAppStore.getState().lastVisitedAtByWorktreeId).toEqual({ - [getWorktreeVisitKey(shells.id, 'local')]: 49_999, - [next.id]: 50_000 - }) - }) -}) diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation-shown-tab-focus.test.ts b/src/renderer/src/lib/workspace/activation/worktree-activation-shown-tab-focus.test.ts deleted file mode 100644 index bcde95dce7d..00000000000 --- a/src/renderer/src/lib/workspace/activation/worktree-activation-shown-tab-focus.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import { activateAndRevealFolderWorkspace, activateAndRevealWorktree } from './worktree-activation' -import { folderWorkspaceKey } from '../../../../../shared/workspace-scope' -import { - makeCreatedAgentWorktree, - seedEmptyActivatableWorktree -} from './worktree-activation-created-agent.test-fixture' - -const initialAppStoreState = useAppStore.getState() -const RUN_TAB_ID = '11111111-2222-4333-8444-555555555555' - -afterEach(() => { - useAppStore.setState(initialAppStoreState, true) - vi.useRealTimers() -}) - -/** A tab main created for a run in a background workspace, as the window adopts it. */ -function adoptRunTab(workspaceKey: string): void { - useAppStore.getState().createTab(workspaceKey, undefined, undefined, { - id: RUN_TAB_ID, - initialPtyId: 'pty-run' - }) - expect(useAppStore.getState().getTab(RUN_TAB_ID)?.lastFocusedAt).toBeUndefined() -} - -describe('opening a workspace focuses the tab it shows', () => { - it('stamps the run tab a worktree visit shows without a tab click', () => { - vi.useFakeTimers({ now: 50_000, toFake: ['Date'] }) - const worktree = makeCreatedAgentWorktree() - seedEmptyActivatableWorktree(worktree) - adoptRunTab(worktree.id) - - activateAndRevealWorktree(worktree.id, { notifyHostRuntime: false }) - - expect(useAppStore.getState().getTab(RUN_TAB_ID)?.lastFocusedAt).toBe(50_000) - }) - - it('stamps the run tab a folder visit shows without a tab click', () => { - vi.useFakeTimers({ now: 60_000, toFake: ['Date'] }) - const folderKey = folderWorkspaceKey('folder-1') - useAppStore.setState({ - folderWorkspaces: [ - { - id: 'folder-1', - projectGroupId: 'group-1', - name: 'notes', - folderPath: '/local/notes', - executionHostId: 'local', - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } - ], - activeView: 'terminal', - getFreshFolderWorkspacePathStatus: () => ({ path: '/local/notes', exists: true }), - markWorktreeVisited: vi.fn(), - recordWorktreeVisit: vi.fn(), - revealWorktreeInSidebar: vi.fn() - }) - adoptRunTab(folderKey) - - activateAndRevealFolderWorkspace('folder-1') - - expect(useAppStore.getState().getTab(RUN_TAB_ID)?.lastFocusedAt).toBe(60_000) - }) -}) diff --git a/src/renderer/src/lib/workspace/ownership/worktree-host-connection-phase.recipe.test.ts b/src/renderer/src/lib/workspace/ownership/worktree-host-connection-phase.recipe.test.ts deleted file mode 100644 index 82a90bd9f0d..00000000000 --- a/src/renderer/src/lib/workspace/ownership/worktree-host-connection-phase.recipe.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AppState } from '@/store/types' -import type { RuntimeEnvironmentStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status' -import { resolveBrowserRouteHostConnection } from './worktree-host-connection-phase' - -const RECIPE_TARGET = 'runtime-ssh-vm-1' - -function stateWith(entry: RuntimeEnvironmentStatus | undefined): AppState { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resolver reads only these fields. - return { - runtimeEnvironments: [ - { - id: 'env-recipe', - orcadDeployment: { sshTargetId: RECIPE_TARGET, sshTargetGeneration: 1 } - } - ], - runtimeStatusByEnvironmentId: new Map(entry ? [['env-recipe', entry]] : []), - sshConnectionStates: new Map() - } as unknown as AppState -} - -describe('browser route host connection for a recipe VM', () => { - it('waits only while the recipe server is being dialed', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: an awaiting handshake needs no other fields here. - const dialing = { - status: null, - remoteControl: { state: 'awaiting_ready' }, - checkedAt: 1 - } as RuntimeEnvironmentStatus - expect(resolveBrowserRouteHostConnection(stateWith(dialing), 'wt', RECIPE_TARGET)).toEqual( - expect.objectContaining({ - phase: 'connecting', - targetId: RECIPE_TARGET, - connectedEpoch: null - }) - ) - }) - - it('settles when the recipe server was never reached, so the route offers recovery', () => { - expect(resolveBrowserRouteHostConnection(stateWith(undefined), 'wt', RECIPE_TARGET).phase).toBe( - 'unavailable' - ) - }) - - it('names a new connected epoch when the recipe server is reached again', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a ready status needs no other fields here. - const status = { graphStatus: 'ready' } as RuntimeEnvironmentStatus['status'] - const first = resolveBrowserRouteHostConnection( - stateWith({ status, checkedAt: 1, connectionGeneration: 3, hostContactEpoch: 1 }), - 'wt', - RECIPE_TARGET - ) - const second = resolveBrowserRouteHostConnection( - stateWith({ status, checkedAt: 2, connectionGeneration: 3, hostContactEpoch: 2 }), - 'wt', - RECIPE_TARGET - ) - - expect(first.phase).toBe('connected') - expect(first.connectedEpoch).not.toBeNull() - expect(second.connectedEpoch).not.toBe(first.connectedEpoch) - }) -}) diff --git a/src/renderer/src/lib/wsl-host-availability.test.ts b/src/renderer/src/lib/wsl-host-availability.test.ts deleted file mode 100644 index c061ab435e9..00000000000 --- a/src/renderer/src/lib/wsl-host-availability.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDefaultSettings } from '../../../shared/constants' -import type { AppState } from '@/store/types' -import { selectWslHostUnavailableReason } from './wsl-host-availability' -import { selectWslHostsServing } from '../components/sidebar/use-wsl-hosts-enabled' - -const WSL_ENV = 'wsl:ubuntu' -const WORKTREE = 'wsl-repo::/home/me/app' - -function state(experimentalWslHosts: boolean, withHost = true): AppState { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the selectors read only these fields. - return { - settings: { ...getDefaultSettings('/tmp'), experimentalWslHosts }, - wslHostServerFiles: 'present', - folderWorkspaces: [], - projectGroups: [], - repos: [ - { - id: 'wsl-repo', - path: '/home/me/app', - displayName: 'app', - badgeColor: '', - addedAt: 0, - executionHostId: `runtime:${WSL_ENV}` - } - ], - runtimeEnvironments: withHost - ? [ - { - id: WSL_ENV, - name: 'Ubuntu (WSL)', - createdAt: 0, - updatedAt: 0, - lastUsedAt: null, - runtimeId: null, - preferredEndpointId: 'ws', - endpoints: [], - orcadDeployment: { kind: 'wsl', distro: 'Ubuntu', localPort: 42000, remotePort: 6768 } - } - ] - : [] - } as unknown as AppState -} - -// Stage 1: the setting governs new work only; a moved project on a saved host stays reachable. -describe('a WSL host project with the WSL hosts setting off', () => { - it('stays reachable: its panes and explorer show no "turned off" state', () => { - expect(selectWslHostUnavailableReason(state(false), WORKTREE)).toBeNull() - expect(selectWslHostsServing(state(false))).toBe(true) - }) - - it('serves nothing when there is no saved host and the setting is off', () => { - expect(selectWslHostsServing(state(false, false))).toBe(false) - expect(selectWslHostsServing(state(true, false))).toBe(true) - }) -}) diff --git a/src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts b/src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts deleted file mode 100644 index 8751d1a6c44..00000000000 --- a/src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { subscribeRuntimeFileChanges } from './runtime-file-watch-client' -import { - runtimeEnvironmentCall, - runtimeEnvironmentSubscribe, - installRuntimeFileClientEnvironment -} from '../runtime-file-client-test-harness' - -installRuntimeFileClientEnvironment() - -describe('runtime file client', () => { - it('delivers remote file changes to listeners for the same worktree', async () => { - const firstPayload = vi.fn() - const secondPayload = vi.fn() - const unsubscribe = vi.fn() - let onResponse: ((response: unknown) => void) | undefined - runtimeEnvironmentCall.mockResolvedValue({ - id: 'unwatch', - ok: true, - result: { unsubscribed: true }, - _meta: { runtimeId: 'remote-runtime' } - }) - runtimeEnvironmentSubscribe.mockImplementation((_args, callbacks) => { - onResponse = callbacks.onResponse - return Promise.resolve({ unsubscribe, sendBinary: vi.fn() }) - }) - - const firstStop = await subscribeRuntimeFileChanges( - { - target: { kind: 'environment' as const, environmentId: 'env-1' }, - worktreeId: 'wt-1', - worktreePath: '/remote/repo' - }, - firstPayload - ) - const secondStop = await subscribeRuntimeFileChanges( - { - target: { kind: 'environment' as const, environmentId: 'env-1' }, - worktreeId: 'wt-1', - worktreePath: '/remote/repo' - }, - secondPayload - ) - - onResponse?.({ - id: 'ready', - ok: true, - result: { type: 'ready', subscriptionId: 'files-watch-1' }, - _meta: { runtimeId: 'remote-runtime' } - }) - onResponse?.({ - id: 'changed', - ok: true, - result: { - type: 'changed', - worktree: 'id:wt-1', - events: [{ kind: 'update', absolutePath: '/remote/repo/readme.md' }] - }, - _meta: { runtimeId: 'remote-runtime' } - }) - - expect(firstPayload).toHaveBeenCalledWith({ - worktreePath: '/remote/repo', - events: [{ kind: 'update', absolutePath: '/remote/repo/readme.md' }] - }) - expect(secondPayload).toHaveBeenCalledWith({ - worktreePath: '/remote/repo', - events: [{ kind: 'update', absolutePath: '/remote/repo/readme.md' }] - }) - - firstStop() - - secondStop() - }) -}) diff --git a/src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-prior-removal.test.ts b/src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-prior-removal.test.ts deleted file mode 100644 index 4e7d567b9ff..00000000000 --- a/src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-orphan-recovery-prior-removal.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { RuntimeMobileSessionTabsResult } from '../../../../../../shared/runtime-session-contracts' -import { mergeAdoptionResponse } from './web-session-terminal-orphan-recovery-adoption' - -describe('post-adoption reconciliation of previously removed surfaces', () => { - it('preserves a newer host-published pending row after the old surface was removed', () => { - const projected: RuntimeMobileSessionTabsResult = { - worktree: 'folder:post-adoption-prior-removal', - publicationEpoch: 'renderer:host:client-navigation', - snapshotVersion: 2, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - retiredTerminalSurfaces: [], - tabs: [ - { - type: 'terminal', - id: 'host-tab::leaf-claim', - parentTabId: 'host-tab', - leafId: 'leaf-claim', - title: 'leaf-claim', - ptyId: 'pty-claim', - isActive: false, - status: 'ready', - terminal: 'term-claim' - }, - { - type: 'terminal', - id: 'host-tab::leaf-old', - parentTabId: 'host-tab', - leafId: 'leaf-old', - title: 'leaf-old', - ptyId: 'pty-new', - isActive: false, - status: 'pending-handle', - terminal: null - } - ] - } - - const merged = mergeAdoptionResponse(projected, [], [], new Set(['host-tab\0leaf-old'])) - - expect(merged.tabs).toEqual([ - { - type: 'terminal', - id: 'host-tab::leaf-claim', - parentTabId: 'host-tab', - leafId: 'leaf-claim', - title: 'leaf-claim', - ptyId: 'pty-claim', - isActive: false, - status: 'ready', - terminal: 'term-claim' - }, - { - type: 'terminal', - id: 'host-tab::leaf-old', - parentTabId: 'host-tab', - leafId: 'leaf-old', - title: 'leaf-old', - ptyId: 'pty-new', - isActive: false, - status: 'pending-handle', - terminal: null - } - ]) - }) -}) diff --git a/src/renderer/src/runtime/rpc/calls/abortable-runtime-environment-call.test.ts b/src/renderer/src/runtime/rpc/calls/abortable-runtime-environment-call.test.ts index fc5a4a3cabc..924f1694007 100644 --- a/src/renderer/src/runtime/rpc/calls/abortable-runtime-environment-call.test.ts +++ b/src/renderer/src/runtime/rpc/calls/abortable-runtime-environment-call.test.ts @@ -40,23 +40,3 @@ it('cancels setup using the preselected id and unsubscribes a late handle', asyn await Promise.resolve() expect(unsubscribe).toHaveBeenCalled() }) - -it('keeps the response deadline while setup is pending', async () => { - vi.useFakeTimers() - const subscribe = vi.fn((_args: { subscriptionId?: string }) => new Promise(() => {})) - const cancelSubscription = vi.fn().mockResolvedValue(undefined) - stubRuntimeEnvironmentBridge({ subscribe, cancelSubscription }) - const pending = callAbortableRuntimeEnvironment( - 'env', - 'files.search', - {}, - 15_000, - new AbortController().signal - ) - const rejection = expect(pending).rejects.toThrow('timed out') - await vi.advanceTimersByTimeAsync(15_000) - await rejection - expect(cancelSubscription).toHaveBeenCalledWith({ - subscriptionId: 'd0b695cc-c36b-4d6d-aa45-e62ce3457d19' - }) -}) diff --git a/src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking.test.ts b/src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking.test.ts deleted file mode 100644 index 05457ee740e..00000000000 --- a/src/renderer/src/runtime/rpc/subscriptions/window-visibility-subscription-parking.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { resetStaleDocumentVisibilityForTesting } from '@/components/terminal-pane/viewport/visibility/stale-document-visibility' -import { installWindowVisibilitySubscriptionParking } from './window-visibility-subscription-parking' -import { WINDOW_HIDE_PARK_GRACE_MS as WINDOW_VISIBILITY_SUBSCRIPTION_PARK_DELAY_MS } from '../../../lib/window-park-visibility' - -type Deferred = { - promise: Promise - resolve: (value: T) => void -} - -function createDeferred(): Deferred { - let resolve!: (value: T) => void - const promise = new Promise((done) => { - resolve = done - }) - return { promise, resolve } -} - -function setDocumentVisibility(state: 'visible' | 'hidden'): void { - Object.defineProperty(document, 'visibilityState', { - configurable: true, - get: () => state - }) - document.dispatchEvent(new Event('visibilitychange')) -} - -async function settle(): Promise { - await Promise.resolve() - await Promise.resolve() -} - -describe('installWindowVisibilitySubscriptionParking', () => { - beforeEach(() => { - vi.useFakeTimers() - setDocumentVisibility('visible') - }) - - afterEach(() => { - setDocumentVisibility('visible') - resetStaleDocumentVisibilityForTesting() - vi.useRealTimers() - vi.restoreAllMocks() - }) - - it('keeps one pending start and replaces it only after stale settlement', async () => { - const first = createDeferred<{ unsubscribe: () => void }>() - const second = createDeferred<{ unsubscribe: () => void }>() - const firstUnsubscribe = vi.fn() - const secondUnsubscribe = vi.fn() - const currents: (() => boolean)[] = [] - const subscribe = vi - .fn((isCurrent: () => boolean) => { - currents.push(isCurrent) - return first.promise - }) - .mockImplementationOnce((isCurrent) => { - currents.push(isCurrent) - return first.promise - }) - .mockImplementationOnce((isCurrent) => { - currents.push(isCurrent) - return second.promise - }) - const dispose = installWindowVisibilitySubscriptionParking([{ subscribe }]) - - setDocumentVisibility('hidden') - vi.advanceTimersByTime(WINDOW_VISIBILITY_SUBSCRIPTION_PARK_DELAY_MS) - expect(currents[0]()).toBe(false) - setDocumentVisibility('visible') - - first.resolve({ unsubscribe: firstUnsubscribe }) - await settle() - expect(firstUnsubscribe).toHaveBeenCalled() - expect(currents[0]()).toBe(false) - expect(currents[1]()).toBe(true) - - second.resolve({ unsubscribe: secondUnsubscribe }) - await settle() - dispose() - expect(secondUnsubscribe).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/runtime/web-session-tabs-late-merged-predecessor-lockout.test.ts b/src/renderer/src/runtime/web-session-tabs-late-merged-predecessor-lockout.test.ts deleted file mode 100644 index 088a123a44f..00000000000 --- a/src/renderer/src/runtime/web-session-tabs-late-merged-predecessor-lockout.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' -import { decideWebSessionTabsSnapshot } from './web-session-tabs-sync/tracking-decisions' -import { - recordReceivedWebSessionTabsSnapshot, - shouldApplyRecoveredWebSessionTabsSnapshot -} from './web-session-tabs-sync/tracking' -import { resetWebSessionTabsSyncTestState } from './web-session-tabs-sync/testing/web-session-tabs-sync.test-fixture' - -// getState: snapshot receipt reads the held paired-tab closes; none here. -vi.mock('../store', () => ({ useAppStore: { setState: vi.fn(), getState: () => ({}) } })) -vi.mock('@/hooks/agent-hook-completion-notifications', () => ({ - observeAgentHookCompletionForNotification: vi.fn() -})) - -/** Fence retired publisher lineages in both recovery and receipt ledger. A late headless-merge predecessor must neither enter nor retire its live successor; testing rejection alone misses successor lockout. */ -const ENV = 'remote-runtime' -const WORKTREE = 'repo::/worktree' -const GEN_1 = 'renderer-generation-1' -const GEN_2 = 'renderer-generation-2' -const MERGED_GEN_1 = `${GEN_1}:headless-merge:abc` - -function frame(publicationEpoch: string, snapshotVersion: number): RuntimeMobileSessionTabsResult { - return { - worktree: WORKTREE, - publicationEpoch, - snapshotVersion, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } -} - -/** The composed gate every production apply path runs. */ -function admits(snapshot: RuntimeMobileSessionTabsResult, receivedFrame: number): boolean { - return ( - shouldApplyRecoveredWebSessionTabsSnapshot(ENV, snapshot, receivedFrame) && - decideWebSessionTabsSnapshot(snapshot, ENV).apply - ) -} - -describe('a late frame from a retired generation must not retire the live successor', () => { - beforeEach(() => { - resetWebSessionTabsSyncTestState() - }) - - for (const [label, epoch] of [ - ['bare', GEN_1], - ['headless-merge', MERGED_GEN_1] - ] as const) { - it(`keeps admitting the successor after a ${label} predecessor frame is rejected`, () => { - const firstReceived = recordReceivedWebSessionTabsSnapshot(ENV, frame(GEN_1, 5)) - expect(admits(frame(GEN_1, 5), firstReceived)).toBe(true) - - const successorReceived = recordReceivedWebSessionTabsSnapshot(ENV, frame(GEN_2, 1)) - expect(admits(frame(GEN_2, 1), successorReceived)).toBe(true) - - // Late enough to win on delivery order; retired by lineage, so it must lose... - const late = frame(epoch, 9) - const lateReceived = recordReceivedWebSessionTabsSnapshot(ENV, late) - expect(admits(late, lateReceived)).toBe(false) - - // ...and losing must cost it nothing more than that frame. The successor is still publishing. - const next = frame(GEN_2, 2) - const nextReceived = recordReceivedWebSessionTabsSnapshot(ENV, next) - expect(admits(next, nextReceived)).toBe(true) - }) - } -}) diff --git a/src/renderer/src/store/github/checks/check-actions-errors.test.ts b/src/renderer/src/store/github/checks/check-actions-errors.test.ts deleted file mode 100644 index a98f502fef8..00000000000 --- a/src/renderer/src/store/github/checks/check-actions-errors.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PRCheckDetail } from '../../../../../shared/github/check-types' -import { createTestStore, mockApi, resetRemoteRuntimeMocks } from '../github-slice-test-harness' - -const pending: PRCheckDetail[] = [{ name: 'Build', status: 'queued', conclusion: null, url: null }] -beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - vi.spyOn(console, 'error').mockImplementation(() => undefined) -}) -afterEach(() => vi.restoreAllMocks()) - -describe('checks provider error policy', () => { - it.each([true, false])( - 'shares one failed read with strict caller first=%s', - async (strictFirst) => { - const store = createTestStore() - const upstream = Promise.withResolvers() - const error = new Error('offline') - mockApi.gh.prChecks.mockReturnValueOnce(upstream.promise) - const fetch = (throwOnError: boolean): Promise => - store.getState().fetchPRChecks('/repo', 1, 'main', 'sha', undefined, { throwOnError }) - const first = fetch(strictFirst) - const second = fetch(!strictFirst) - const settled = Promise.allSettled([first, second]) - upstream.reject(error) - const results = await settled - expect(results[strictFirst ? 0 : 1]).toEqual({ status: 'rejected', reason: error }) - expect(results[strictFirst ? 1 : 0]).toEqual({ status: 'fulfilled', value: [] }) - - expect(store.getState().checksCache).toEqual({}) - } - ) - - it('preserves the good cache for default callers while strict callers observe errors and recover', async () => { - const store = createTestStore() - mockApi.gh.prChecks.mockResolvedValueOnce(pending) - await store.getState().fetchPRChecks('/repo', 1, 'main', 'sha') - const error = new Error('offline') - mockApi.gh.prChecks.mockRejectedValue(error) - await expect( - store.getState().fetchPRChecks('/repo', 1, 'main', 'sha', undefined, { - force: true, - throwOnError: true - }) - ).rejects.toThrow(error) - await expect( - store.getState().fetchPRChecks('/repo', 1, 'main', 'sha', undefined, { - force: true - }) - ).resolves.toEqual(pending) - expect(Object.values(store.getState().checksCache).map((entry) => entry.data)).toEqual([ - pending - ]) - mockApi.gh.prChecks.mockResolvedValueOnce([]) - await expect( - store.getState().fetchPRChecks('/repo', 1, 'main', 'sha', undefined, { - force: true, - throwOnError: true - }) - ).resolves.toEqual([]) - }) -}) diff --git a/src/renderer/src/store/github/repositories/github-pr-refresh-wsl-host-off.test.ts b/src/renderer/src/store/github/repositories/github-pr-refresh-wsl-host-off.test.ts deleted file mode 100644 index e76b5b829c4..00000000000 --- a/src/renderer/src/store/github/repositories/github-pr-refresh-wsl-host-off.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../../shared/constants' -import type { Repo } from '../../../../../shared/repo-types' -import type { AppState } from '../../types' -import { - createTestStore, - makePR, - makePRRefreshWorktree, - resetRemoteRuntimeMocks, - runtimeEnvironmentCall -} from '../github-slice-test-harness' - -const WSL_ENV: AppState['runtimeEnvironments'][number] = { - id: 'env-1', - name: 'Ubuntu (WSL)', - createdAt: 0, - updatedAt: 0, - lastUsedAt: null, - runtimeId: null, - preferredEndpointId: 'ws', - endpoints: [], - orcadDeployment: { kind: 'wsl', distro: 'Ubuntu', localPort: 42000, remotePort: 6768 } -} - -const REPO: Repo = { - id: 'repo-wsl', - path: '/home/me/app', - displayName: 'app', - badgeColor: 'blue', - addedAt: 1, - kind: 'git', - executionHostId: 'runtime:env-1', - gitRemoteIdentity: { - canonicalKey: 'github.com/owner/repo', - remoteName: 'origin', - remoteUrl: 'https://github.com/owner/repo.git' - } -} - -function status(state: 'ready' | 'distro-stopped'): AppState['wslHostStatuses'] { - return { 'env-1': { environmentId: 'env-1', distro: 'Ubuntu', state, detail: null } } -} - -describe('PR refresh for a WSL host that is off (E9)', () => { - beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - }) - - it('keeps the last badge, records host-off, and never asks the host', async () => { - runtimeEnvironmentCall.mockResolvedValueOnce({ - id: 'rpc-1', - ok: true, - result: makePR({ number: 31 }), - _meta: { runtimeId: 'remote-runtime' } - }) - const store = createTestStore() - store.setState({ - settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: null }, - repos: [REPO], - worktreesByRepo: { - 'repo-wsl': [ - makePRRefreshWorktree({ id: 'wt-wsl', repoId: 'repo-wsl', branch: 'feature/x' }) - ] - }, - prCache: {}, - hostedReviewCache: {}, - sshConnectionStates: new Map(), - runtimeEnvironments: [WSL_ENV], - wslHostStatuses: status('ready') - }) - store.getState().enqueueGitHubPRRefresh('wt-wsl', 'manual', 100) - await vi.waitFor(() => - expect( - Object.values(store.getState().prCache).some((entry) => entry.data?.number === 31) - ).toBe(true) - ) - - store.setState({ wslHostStatuses: status('distro-stopped') }) - store.getState().enqueueGitHubPRRefresh('wt-wsl', 'manual', 100) - - await vi.waitFor(() => - expect(Object.values(store.getState().prRefreshStates)).toContainEqual( - expect.objectContaining({ status: 'skipped', skippedReason: 'host-off' }) - ) - ) - - expect(Object.values(store.getState().prCache).map((entry) => entry.data?.number)).toEqual([31]) - }) -}) diff --git a/src/renderer/src/store/project-groups/nested-repository-operations.test.ts b/src/renderer/src/store/project-groups/nested-repository-operations.test.ts deleted file mode 100644 index 817c85c6b0d..00000000000 --- a/src/renderer/src/store/project-groups/nested-repository-operations.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { it, vi, expect, beforeEach, describe } from 'vitest' -import type { NestedRepoScanResult } from '../../../../shared/project-group-types' -import { createTestStore } from '../testing/app-store-test-fixture' - -const LOCAL_OWNER = { runtimeEnvironmentId: null } -const projectGroupsScanNested = vi.fn() -const projectGroupsOnNestedScanProgress = vi.fn() - -beforeEach(() => { - projectGroupsScanNested.mockReset() - projectGroupsOnNestedScanProgress.mockReset() - projectGroupsOnNestedScanProgress.mockReturnValue(vi.fn()) - vi.stubGlobal('window', { - api: { - projectGroups: { - scanNested: projectGroupsScanNested, - onNestedScanProgress: projectGroupsOnNestedScanProgress - } - } - }) -}) - -describe('project group store routing', () => { - it('routes local nested scan progress by scanId and unsubscribes after completion', async () => { - const unsubscribe = vi.fn() - const progressCallback = vi.fn() - const matchingScan = { - selectedPath: '/platform', - selectedPathKind: 'non_git_folder' as const, - repos: [{ path: '/platform/api', displayName: 'api', depth: 1 }], - truncated: false, - timedOut: false, - stopped: false, - durationMs: 10, - maxDepth: 3, - maxRepos: 100, - timeoutMs: null - } - projectGroupsOnNestedScanProgress.mockImplementation( - (listener: (data: { scanId: string; scan: NestedRepoScanResult }) => void) => { - listener({ scanId: 'other-scan', scan: { ...matchingScan, repos: [] } }) - listener({ scanId: 'scan-1', scan: matchingScan }) - return unsubscribe - } - ) - projectGroupsScanNested.mockResolvedValue(matchingScan) - const store = createTestStore() - - await expect( - store.getState().scanNestedRepos('/platform', undefined, { - ...LOCAL_OWNER, - scanId: 'scan-1', - onProgress: progressCallback - }) - ).resolves.toEqual(matchingScan) - - expect(progressCallback).not.toHaveBeenCalledWith({ ...matchingScan, repos: [] }) - expect(progressCallback).toHaveBeenCalledWith(matchingScan) - expect(projectGroupsScanNested).toHaveBeenCalledWith({ - path: '/platform', - connectionId: undefined, - scanId: 'scan-1' - }) - expect(unsubscribe).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/store/repos/sparse-presets-repo-removal-purge-leak.test.ts b/src/renderer/src/store/repos/sparse-presets-repo-removal-purge-leak.test.ts deleted file mode 100644 index b35eba3d84c..00000000000 --- a/src/renderer/src/store/repos/sparse-presets-repo-removal-purge-leak.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -/** Repo UUIDs never recur; removal must evict all four lazily populated sparse-preset maps or session memory grows forever. */ -import { getRepoExecutionHostId } from '../../../../shared/execution-host' -import { describe, it, expect, vi, beforeEach } from 'vitest' -import { createTestStore } from '../testing/app-store-test-fixture' -import { makeWorktree } from '../slices/worktrees/worktree.test-fixture' -import type { Repo } from '../../../../shared/repo-types' -import type { SparsePreset } from '../../../../shared/worktree/create-types' - -const repo1: Repo = { id: 'repo-1', path: '/r1', displayName: 'R1', badgeColor: '#000', addedAt: 1 } -const repo2: Repo = { id: 'repo-2', path: '/r2', displayName: 'R2', badgeColor: '#111', addedAt: 2 } - -const reposRemove = vi.fn().mockResolvedValue(undefined) - -beforeEach(() => { - reposRemove.mockReset().mockResolvedValue(undefined) - vi.stubGlobal('window', { - api: { - repos: { removeForHost: reposRemove }, - pty: { kill: vi.fn() }, - runtimeEnvironments: { call: vi.fn() } - } - }) -}) - -function preset(id: string, repoId: string): SparsePreset { - return { id, repoId, name: id, directories: ['src'], createdAt: 1, updatedAt: 1 } -} - -function seed(store: ReturnType): void { - store.setState({ - repos: [repo1, repo2], - worktreesByRepo: { - [repo1.id]: [makeWorktree({ id: 'repo-1::/r1/wt1', repoId: repo1.id, path: '/r1/wt1' })], - [repo2.id]: [makeWorktree({ id: 'repo-2::/r2/wt1', repoId: repo2.id, path: '/r2/wt1' })] - }, - sparsePresetsByRepo: { - [repo1.id]: [preset('p1', repo1.id)], - [repo2.id]: [preset('p2', repo2.id)] - }, - sparsePresetsLoadingByRepo: { [repo1.id]: false, [repo2.id]: false }, - sparsePresetsLoadStatusByRepo: { [repo1.id]: 'loaded', [repo2.id]: 'loaded' }, - sparsePresetsErrorByRepo: { [repo1.id]: 'stale', [repo2.id]: 'boom' } - }) -} - -describe('removeProject purges the removed repo sparse-preset maps (leak regression)', () => { - it('drops all four sparse-preset maps for the removed repo, keeps the surviving repo', async () => { - const store = createTestStore() - seed(store) - - await store.getState().removeProject(repo1.id, { hostId: getRepoExecutionHostId(repo1) }) - - const s = store.getState() - expect(repo1.id in s.sparsePresetsByRepo).toBe(false) - expect(repo1.id in s.sparsePresetsLoadingByRepo).toBe(false) - expect(repo1.id in s.sparsePresetsLoadStatusByRepo).toBe(false) - expect(repo1.id in s.sparsePresetsErrorByRepo).toBe(false) - expect(s.sparsePresetsByRepo[repo2.id]).toEqual([preset('p2', repo2.id)]) - expect(s.sparsePresetsLoadingByRepo[repo2.id]).toBe(false) - expect(s.sparsePresetsLoadStatusByRepo[repo2.id]).toBe('loaded') - expect(s.sparsePresetsErrorByRepo[repo2.id]).toBe('boom') - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-listing-branch-switch.test.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-listing-branch-switch.test.ts deleted file mode 100644 index dc3a2c00429..00000000000 --- a/src/renderer/src/store/slices/worktrees/listing/worktree-listing-branch-switch.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { Worktree } from '../../../../../../shared/worktree/types' -import { routeListingBranchSwitchesThroughGitIdentity } from './worktree-listing-branch-switch' - -const restoredStub: Worktree = { - id: 'repo-1::/srv/app/feature', - repoId: 'repo-1', - hostId: 'runtime:env-1', - displayName: 'feature', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - linkedGitLabMR: null, - linkedGitLabIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - path: '/srv/app/feature', - head: '', - branch: '', - isBare: false, - isMainWorktree: false -} - -describe('routeListingBranchSwitchesThroughGitIdentity', () => { - it('lets the first listing replace a restored stub that git status filled in meanwhile', () => { - const stubWithGitStatus = { ...restoredStub, head: 'abc123', branch: 'refs/heads/feature' } - const listed: Worktree = { - ...stubWithGitStatus, - runtimeOwnerEnvironmentId: 'env-1', - instanceId: 'instance-1' - } - - const result = routeListingBranchSwitchesThroughGitIdentity({ - requestStarted: [restoredStub], - current: [stubWithGitStatus], - incoming: [listed], - matchesRefreshHost: () => true, - hasBranchScopedReviewContext: () => false, - updateWorktreeGitIdentity: vi.fn() - }) - - expect(result[0]?.instanceId).toBe('instance-1') - }) - - it('keeps a branch switch git status saw over a stale listing of a headless row', () => { - const switched = { ...restoredStub, head: 'new-head', branch: 'refs/heads/new' } - const staleListing: Worktree = { - ...restoredStub, - head: 'old-head', - branch: 'refs/heads/old', - instanceId: 'instance-1' - } - const updateWorktreeGitIdentity = vi.fn() - - const result = routeListingBranchSwitchesThroughGitIdentity({ - requestStarted: [restoredStub], - current: [switched], - incoming: [staleListing], - matchesRefreshHost: () => true, - hasBranchScopedReviewContext: () => true, - updateWorktreeGitIdentity - }) - - expect(result[0]?.branch).toBe('refs/heads/new') - expect(updateWorktreeGitIdentity).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/metadata/foreign-host-status-guard.test.ts b/src/renderer/src/store/slices/worktrees/metadata/foreign-host-status-guard.test.ts index 616bfa7c30c..0fdce853139 100644 --- a/src/renderer/src/store/slices/worktrees/metadata/foreign-host-status-guard.test.ts +++ b/src/renderer/src/store/slices/worktrees/metadata/foreign-host-status-guard.test.ts @@ -7,8 +7,7 @@ import { createTestStore, mockApi, resetRemoteRuntimeMocks, - resetWorktreeSliceModuleMemory, - runtimeEnvironmentCall + resetWorktreeSliceModuleMemory } from '../worktrees-slice-test-harness' const requestWorktreeBaseFallbackNotice = vi.hoisted(() => vi.fn()) @@ -57,41 +56,4 @@ describe('worktree remote runtime mutations', () => { expect.objectContaining({ updates: { manualOrder: 5 } }) ) }) - - it("still moves a paired host's card into that host's own column", async () => { - const store = createTestStore() - const hosted = makeWorktree({ - id: 'repo1::/path/wt1', - repoId: 'repo1', - path: '/path/wt1', - hostId: 'runtime:env-1' - }) - runtimeEnvironmentCall.mockResolvedValue({ - id: 'rpc-set-status', - ok: true, - result: { worktree: { ...hosted, workspaceStatus: 'status-6' } }, - _meta: { runtimeId: 'runtime-remote' } - }) - store.setState({ - worktreesByRepo: { repo1: [hosted] }, - workspaceStatuses: [{ id: 'in-progress', label: 'In progress' }], - hostWorkspaceStatuses: { 'env-1': [{ id: 'status-6', label: 'Today' }] } - }) - - await store.getState().updateWorktreesMeta([ - { - worktreeId: hosted.id, - updates: { workspaceStatus: 'status-6' }, - executionHostId: 'runtime:env-1' - } - ]) - - expect(store.getState().worktreesByRepo.repo1[0]?.workspaceStatus).toBe('status-6') - expect(runtimeEnvironmentCall).toHaveBeenCalledWith( - expect.objectContaining({ - selector: 'env-1', - params: expect.objectContaining({ workspaceStatus: 'status-6' }) - }) - ) - }) }) diff --git a/src/renderer/src/store/terminals/legacy-relay-bridged-tab-close.test.ts b/src/renderer/src/store/terminals/legacy-relay-bridged-tab-close.test.ts deleted file mode 100644 index 672d7e21d3e..00000000000 --- a/src/renderer/src/store/terminals/legacy-relay-bridged-tab-close.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalTabRetirementPlan } from './terminal-tab-retirement' - -const PTY = 'ssh:ssh-box@@pty-1' -const TAB = 'web-terminal-tab-1' - -const api = vi.hoisted(() => { - let release: () => void = () => {} - const listed = new Promise((resolve) => { - release = resolve - }) - return { - close: vi.fn(async () => ({ status: 'requested' })), - // Main answers the first listing late, after the close already started. - listPanes: vi.fn(async () => { - await listed - return [{ ptyId: 'ssh:ssh-box@@pty-1', targetId: 'ssh-box', tabId: 'tab-1', state: 'live' }] - }), - release: () => release() - } -}) - -vi.stubGlobal('window', { - api: { - legacyRelayBridge: { listPanes: api.listPanes, close: api.close, onPanes: () => () => {} } - } -}) - -const { stopLegacyRelayBridgedShellsForTab } = await import('./legacy-relay-bridged-tab-close') - -function plan(overrides: Partial = {}): TerminalTabRetirementPlan { - return { - tabId: TAB, - worktreeId: 'wt-1', - ptyIds: [], - localOrSshPtyIds: [], - runtimeTerminals: [], - cleanupOnlyPtyIds: [], - sharedPtyIds: [], - unroutablePtyIds: [], - ...overrides - } -} - -function state(otherTabPtyId: string | null = null) { - return { - tabsByWorktree: { - 'wt-1': [ - { id: TAB, ptyId: PTY }, - ...(otherTabPtyId ? [{ id: 'moved-to', ptyId: otherTabPtyId }] : []) - ] - }, - unifiedTabsByWorktree: {}, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {}, - lastKnownRelayPtyIdByTabId: {}, - deferredSshSessionIdsByTabId: {}, - pendingReconnectPtyIdByTabId: {} - } -} - -beforeEach(() => { - api.close.mockClear() -}) - -describe('closing a tab whose shell an older relay still runs', () => { - it('stops that shell, waiting for main’s first pane list rather than reading it empty', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the close reads only the tab and pty maps this fixture fills. - const closing = stopLegacyRelayBridgedShellsForTab(state() as never, TAB, plan()) - await new Promise((resolve) => setTimeout(resolve, 5)) - expect(api.close).not.toHaveBeenCalled() - api.release() - await closing - expect(api.close).toHaveBeenCalledWith({ ptyId: PTY }) - }) - - it('never stops a shell another tab now shows, or one the plan says is shared', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above. - await stopLegacyRelayBridgedShellsForTab(state(PTY) as never, TAB, plan()) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above. - await stopLegacyRelayBridgedShellsForTab(state() as never, TAB, plan({ sharedPtyIds: [PTY] })) - expect(api.close).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/store/workspaces/selection/workspace-host-target.test.ts b/src/renderer/src/store/workspaces/selection/workspace-host-target.test.ts deleted file mode 100644 index dd5833c0a3a..00000000000 --- a/src/renderer/src/store/workspaces/selection/workspace-host-target.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { hostWorktreeTarget } from '../../../../../shared/worktree/host-qualified-identity' -import '../../../../../shared/workspace-scope' -import type { AppState } from '../../types' -import { makeFolderWorkspace } from '../../folder-workspaces/folder-workspace.test-fixture' -import { makeWorktree } from '../../slices/worktrees/worktree.test-fixture' -import { selectWorkspaceByHostTarget } from './workspace-host-target' - -const SHARED_ID = 'repo-1::/work/orca' -const localRow = makeWorktree({ id: SHARED_ID, repoId: 'repo-1', hostId: 'local' }) -const sshRow = makeWorktree({ id: SHARED_ID, repoId: 'repo-1', hostId: 'ssh:build-box' }) -const otherRepoRow = makeWorktree({ id: 'repo-2::/work/api', repoId: 'repo-2', hostId: 'local' }) -const folder = makeFolderWorkspace({ id: 'folder-1', executionHostId: 'local' }) - -function makeState( - overrides: Partial> = {} -): Pick { - return { - worktreesByRepo: { 'repo-1': [localRow, sshRow], 'repo-2': [otherRepoRow] }, - folderWorkspaces: [folder], - detectedWorktreesByRepo: {}, - ...overrides - } -} - -describe('selectWorkspaceByHostTarget', () => { - it('resolves the target host only', () => { - const state = makeState() - expect( - selectWorkspaceByHostTarget(state, hostWorktreeTarget({ id: SHARED_ID, hostId: 'local' })) - ).toBe(localRow) - expect( - selectWorkspaceByHostTarget( - state, - hostWorktreeTarget({ id: SHARED_ID, hostId: 'ssh:build-box' }) - ) - ).toBe(sshRow) - }) - - it("answers a paired runtime's logical host alias", () => { - const hubRow = makeWorktree({ - id: 'repo-3::/srv/app', - repoId: 'repo-3', - hostId: 'ssh:hub', - runtimeOwnerEnvironmentId: 'env-1' - }) - const state = makeState({ worktreesByRepo: { 'repo-3': [hubRow] } }) - expect( - selectWorkspaceByHostTarget( - state, - hostWorktreeTarget({ id: hubRow.id, hostId: 'runtime:env-1' }) - ) - ).toBe(hubRow) - }) -})