diff --git a/.github/workflows/ssh-hostile-hosts.yml b/.github/workflows/ssh-hostile-hosts.yml index d129bec5c17..00c23a1b9de 100644 --- a/.github/workflows/ssh-hostile-hosts.yml +++ b/.github/workflows/ssh-hostile-hosts.yml @@ -10,16 +10,19 @@ on: types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] paths: # The managed deploy runs on these remote install and runtime primitives. - - 'src/main/ssh/remote-*' - - 'src/main/ssh/*runtime*' - - 'src/main/ssh/orcad-*' + + - 'src/main/ssh/runtime-access/**' - 'src/main/managed-server/**' + - 'src/main/ssh/migration-source/**' + - 'src/main/persistence/migrating-orcad-catalog/**' - 'src/main/orcad/orcad-artifact-materializer.ts' - 'src/main/orcad/orcad-host-unavailable.ts' - 'src/main/node-runtime/**' - - 'src/main/ssh/ssh-remote-*' + - 'src/main/ssh/remote-exec/**' + - 'src/main/ssh/remote-host/**' + - 'src/main/ssh/filesystem/**' - 'src/main/ssh/hostile-host-test-support/**' - - 'src/main/ssh/sftp-*' + - 'src/main/ssh/file-transfer/sftp/**' - 'src/shared/node-runtime-pin.ts' - 'src/shared/orcad-artifacts.ts' - 'config/scripts/build-orcad-*.mjs' @@ -31,8 +34,15 @@ on: - 'config/patches/node-pty*' # The deploy runs over this SSH transport. - 'src/main/ssh/connection/**' - - 'src/main/ssh/ssh-reconnect-error-classification.ts' - - 'src/main/ssh/ssh-posix-command-wrapper.ts' + - 'src/main/ssh/file-transfer/ssh-connection-file-transfers.ts' + - 'src/main/ssh/targets/ssh-connection-store.ts' + - 'src/main/ssh/targets/testing/ssh-connection-store-test-fixture.ts' + - 'src/main/ssh/targets/ssh-target-runtime-ownership.ts' + - 'src/main/ssh/authentication/ssh2-credential-fallback.ts' + - 'src/main/ssh/authentication/ssh2-handshake.ts' + - 'src/main/ssh/host-keys/ssh2-host-key-verification.ts' + - 'src/main/ssh/connection/reconnect/ssh-reconnect-error-classification.ts' + - 'src/main/ssh/remote-exec/ssh-posix-command-wrapper.ts' - 'src/shared/shell/launch/shell-argument-quoting.ts' - '!src/**/*.test.ts' - 'src/main/ssh/hostile-host-test-support/ssh-hostile-hosts.docker.test.ts' diff --git a/.github/workflows/ssh-windows-hosts.yml b/.github/workflows/ssh-windows-hosts.yml index 93b7ef1f134..4185ad26af4 100644 --- a/.github/workflows/ssh-windows-hosts.yml +++ b/.github/workflows/ssh-windows-hosts.yml @@ -8,16 +8,18 @@ on: pull_request: types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] paths: - - 'src/main/ssh/remote-*' - - 'src/main/ssh/*runtime*' - - 'src/main/ssh/orcad-*' + - 'src/main/ssh/runtime-access/**' - 'src/main/managed-server/**' + - 'src/main/ssh/migration-source/**' + - 'src/main/persistence/migrating-orcad-catalog/**' - 'src/main/orcad/orcad-artifact-materializer.ts' - 'src/main/orcad/orcad-host-unavailable.ts' - 'src/main/node-runtime/**' - - 'src/main/ssh/ssh-remote-*' + - 'src/main/ssh/remote-exec/**' + - 'src/main/ssh/remote-host/**' + - 'src/main/ssh/filesystem/**' - 'src/main/ssh/hostile-host-test-support/**' - - 'src/main/ssh/ssh-windows-host-*' + - 'src/main/ssh/hostile-host-test-support/ssh-windows-host-*' - 'src/wsl-guest/**' - 'src/packages/process-host/**' - 'pnpm-workspace.yaml' @@ -48,8 +50,15 @@ on: - 'src/main/ipc/ssh/ssh-host-server-*.ts' # The deploy runs over this SSH transport. - 'src/main/ssh/connection/**' - - 'src/main/ssh/ssh-reconnect-error-classification.ts' - - 'src/main/ssh/ssh-posix-command-wrapper.ts' + - 'src/main/ssh/file-transfer/ssh-connection-file-transfers.ts' + - 'src/main/ssh/targets/ssh-connection-store.ts' + - 'src/main/ssh/targets/testing/ssh-connection-store-test-fixture.ts' + - 'src/main/ssh/targets/ssh-target-runtime-ownership.ts' + - 'src/main/ssh/authentication/ssh2-credential-fallback.ts' + - 'src/main/ssh/authentication/ssh2-handshake.ts' + - 'src/main/ssh/host-keys/ssh2-host-key-verification.ts' + - 'src/main/ssh/connection/reconnect/ssh-reconnect-error-classification.ts' + - 'src/main/ssh/remote-exec/ssh-posix-command-wrapper.ts' - 'src/shared/shell/launch/shell-argument-quoting.ts' - '!src/**/*.test.ts' - 'src/main/managed-server/host-state/orcad-windows-host-lane.test.ts' @@ -69,7 +78,7 @@ on: workflow_dispatch: inputs: cells: - description: Comma-separated cell ids from src/main/ssh/ssh-windows-host-cells.ts; empty runs the default set (orcad-cli-* cells run only when named). + description: Comma-separated cell ids from src/main/ssh/hostile-host-test-support/ssh-windows-host-cells.ts; empty runs the default set (orcad-cli-* cells run only when named). required: false default: '' preparation_mode: diff --git a/.github/workflows/wsl-orcad-e2e.yml b/.github/workflows/wsl-orcad-e2e.yml index f10f9cfe44c..8c8ef29b65a 100644 --- a/.github/workflows/wsl-orcad-e2e.yml +++ b/.github/workflows/wsl-orcad-e2e.yml @@ -27,7 +27,8 @@ on: - 'config/scripts/*orcad*' - 'package.json' - 'pnpm-lock.yaml' - - 'src/main/ssh/orcad-*' + - 'src/main/ssh/migration-source/**' + - 'src/main/persistence/migrating-orcad-catalog/**' - 'src/main/managed-server/**' - 'src/packages/process-host/**' # Unit tests never run in this lane; only the real distro test below does. diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 058beaf9d7b..808de3a90be 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -23,7 +23,7 @@ 1 test-no-in-test-import-actual:src/main/speech/openai-api-key-store.test.ts 5 test-no-in-test-import-actual:src/main/ssh/config/ssh-config-loader-regression.test.ts 2 test-no-in-test-import-actual:src/main/ssh/connection/ssh-connection-auth-fallback.test.ts -1 test-no-in-test-import-actual:src/main/ssh/orcad-snapshot-room.test.ts +1 test-no-in-test-import-actual:src/main/managed-server/host-state/orcad-snapshot-room.test.ts 1 test-no-in-test-import-actual:src/main/window/dropped-path-preparation.test.ts 2 test-no-in-test-import-actual:src/main/workspace-hooks/hooks-runner.test.ts 1 test-no-in-test-import-actual:src/main/workspaces/removal/local-worktree-removal-recovery.test.ts @@ -31,10 +31,7 @@ 3 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts 1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts 1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-hydration.test.ts -2 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts -3 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts 1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-rate-limit-hydration.test.ts -1 test-no-in-test-import-actual:src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts 1 test-no-in-test-import-actual:src/renderer/src/lib/agent-session/launch/new-tab/agent-launch-caller-routing.test.ts 1 test-no-polling-loop:src/main/browser/cookies/browser-cookie-import-concurrency.test.ts 1 test-no-polling-loop:src/main/claude/claude-stop-ack-race.test.ts @@ -70,7 +67,7 @@ 3 test-no-polling-loop:src/main/skills/install/skill-bundle-process-termination.integration.test.ts 2 test-no-polling-loop:src/main/skills/runtime-upload/skill-upload-process-restart.integration.test.ts 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 +1 test-no-polling-loop:src/main/ssh/legacy-relay/endpoints/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.test.ts 2 test-no-polling-loop:src/main/windows/windows-host-job.win32.test.ts @@ -150,7 +147,6 @@ 1 test-no-polling-loop:tests/e2e/terminal-tui-wheel-reports.spec.ts 1 test-no-polling-loop:tests/e2e/workspace-sleep-in-main.spec.ts 2 test-no-polling-loop:tests/e2e/worktree-card-downward-drag.spec.ts -1 test-no-real-time-wait:mobile/src/tasks/worktree-create-retry.test.ts 1 test-no-real-time-wait:mobile/src/terminal/terminal-webview-tap-routing.test.ts 1 test-no-real-time-wait:src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts 3 test-no-real-time-wait:src/main/agent-hooks/server-copilot-normalization.test.ts @@ -258,11 +254,7 @@ 1 test-no-real-time-wait:src/main/skills/cloud/skill-cloud-direct-upload.test.ts 2 test-no-real-time-wait:src/main/skills/runtime-upload/skill-upload-process-restart.integration.test.ts 4 test-no-real-time-wait:src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts -1 test-no-real-time-wait:src/main/ssh/legacy-relay/legacy-relay-cli-server.test.ts -1 test-no-real-time-wait:src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts -2 test-no-real-time-wait:src/main/ssh/sftp-upload.test.ts -1 test-no-real-time-wait:src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts -2 test-no-real-time-wait:src/main/ssh/ssh-quit-abort-upload.test.ts +1 test-no-real-time-wait:src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts 2 test-no-real-time-wait:src/main/startup/gpu-lifecycle-install-dir-acl-guard.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 @@ -630,12 +622,11 @@ 2 test-no-wall-clock:src/main/skills/transaction-state/skill-transaction-startup-recovery.test.ts 4 test-no-wall-clock:src/main/skills/runtime-upload/skill-upload-process-restart.integration.test.ts 4 test-no-wall-clock:src/main/sqlite/sync-database.test.ts -1 test-no-wall-clock:src/main/ssh/legacy-relay/legacy-relay-bridge-runtime-exit.test.ts -4 test-no-wall-clock:src/main/ssh/orcad-exited-own-fence-mutation-race.test.ts -8 test-no-wall-clock:src/main/ssh/orcad-exited-own-fence.test.ts -6 test-no-wall-clock:src/main/ssh/orcad-exited-own-install-lock.test.ts -2 test-no-wall-clock:src/main/ssh/orcad-exited-own-lock-windows.test.ts -4 test-no-wall-clock:src/main/ssh/ssh-remote-commands.test.ts +4 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts +8 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence.test.ts +4 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts +2 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts +4 test-no-wall-clock:src/main/ssh/remote-exec/ssh-remote-commands.test.ts 2 test-no-wall-clock:src/main/star-nag/service-direct-star.test.ts 3 test-no-wall-clock:src/main/star-nag/service-threshold-prompt.test.ts 1 test-no-wall-clock:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts @@ -676,9 +667,6 @@ 4 test-no-wall-clock:src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts -2 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts -3 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts -1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.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/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 @@ -798,10 +786,9 @@ 1 test-timeout-needs-reason:src/main/skills/install/skill-bundle-process-termination.integration.test.ts 1 test-timeout-needs-reason:src/main/sqlite/sync-database-concurrent-backup.test.ts 2 test-timeout-needs-reason:src/main/ssh/connection/ssh-connection-sftp-wire.test.ts -1 test-timeout-needs-reason:src/main/ssh/orcad-exited-own-fence.test.ts -1 test-timeout-needs-reason:src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts -1 test-timeout-needs-reason:src/main/ssh/ssh-exec-stdin-file-transfer.test.ts -2 test-timeout-needs-reason:src/main/ssh/system-transport/system-ssh-forward-process-real-openssh.test.ts +1 test-timeout-needs-reason:src/main/managed-server/activation/orcad-exited-own-fence.test.ts +1 test-timeout-needs-reason:src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts +2 test-timeout-needs-reason:src/main/ssh/system-transport/forwarding/system-ssh-forward-process-real-openssh.test.ts 2 test-timeout-needs-reason:src/main/startup/single-instance-lock-exit.electron.test.ts 1 test-timeout-needs-reason:src/main/window/renderer-publication-throttle.electron.test.ts 1 test-timeout-needs-reason:src/main/windows/windows-administrator-restart.win32.test.ts diff --git a/config/legacy-relay-compat-tags-baseline.txt b/config/legacy-relay-compat-tags-baseline.txt index 369c460aeea..c168b52ead7 100644 --- a/config/legacy-relay-compat-tags-baseline.txt +++ b/config/legacy-relay-compat-tags-baseline.txt @@ -10,14 +10,13 @@ src/main/ipc/ssh/ssh-session-teardown.ts src/main/ipc/ssh/ssh.ts src/main/runtime/orchestration/terminal-authority/verify-orchestration-compatibility-caller.ts src/main/runtime/orchestration/terminal-authority/orchestration-compatibility-authority.ts -src/main/ssh/orcad-migration-delta-move.test.ts -src/main/ssh/orcad-migration-delta-move.ts -src/main/ssh/orcad-migration-repository-link.test.ts -src/main/ssh/orcad-migration-terminal-gate-host-wide.test.ts -src/main/ssh/orcad-migration-terminal-gate.test.ts -src/main/ssh/orcad-migration-terminal-gate.ts -src/main/ssh/ssh-host-server-on-connect.test.ts -src/main/ssh/ssh-host-server-on-connect.ts +src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts +src/main/managed-server/migration/cutover/orcad-migration-delta-move.ts +src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts +src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts +src/main/ssh/migration-source/orcad-migration-terminal-gate.ts +src/main/ssh/host-server/ssh-host-server-on-connect.test.ts +src/main/ssh/host-server/ssh-host-server-on-connect.ts src/main/ssh/targets/ssh-target-orcad-preflight.ts src/preload/api-types.ts src/preload/api/legacy-relay-bridge-api.ts diff --git a/config/legacy-relay-importers-baseline.txt b/config/legacy-relay-importers-baseline.txt index 9e3a59417b0..ef18c667b27 100644 --- a/config/legacy-relay-importers-baseline.txt +++ b/config/legacy-relay-importers-baseline.txt @@ -9,7 +9,9 @@ src/main/ipc/ssh/ssh-connect-flow.ts src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts src/main/ipc/ssh/ssh-session-teardown.ts src/main/ipc/ssh/ssh.ts -src/main/ssh/orcad-migration-terminal-gate-host-wide.test.ts src/main/managed-server/lifecycle/orcad-runtime-conversion-wiring.ts tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts tests/e2e/helpers/legacy-relay-docker-host.ts +src/main/managed-server/install/remote-install-model.ts +src/main/ssh/system-transport/ssh-system-transport.integration.test.ts +src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index 562fe9cf0e7..639a055288a 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -72,5 +72,5 @@ 3 src/main/runtime/terminal/surface/mobile-session-layout-projection.ts 1 src/main/runtime/workspaces/session-hosts/get-runtime-id.ts 1 src/main/runtime/workspaces/session-hosts/runtime-workspace-session-controller.ts -1 src/main/ssh/orcad-migration-source-retention.ts +1 src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts 1 src/main/ssh/targets/ssh-target-id-migration.ts diff --git a/config/max-lines-baseline.txt b/config/max-lines-baseline.txt index 88d10e41432..3b8aeb2bea9 100644 --- a/config/max-lines-baseline.txt +++ b/config/max-lines-baseline.txt @@ -3,6 +3,6 @@ # split the oversized file instead. # Regenerate/prune: pnpm check:max-lines-ratchet --prune (removes stale entries only) inline src/main/ipc/worktree-remote.ts -inline src/main/ssh/ssh-channel-multiplexer.ts +inline src/main/ssh/protocol/ssh-channel-multiplexer.ts inline src/main/ssh/connection/ssh-connection.ts inline src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport.ts diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index cf707d1b82a..1ef89fe5148 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -90,10 +90,10 @@ src/main/rate-limits/gemini-cli-oauth-extractor.ts src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.ts src/main/runtime/rpc/server/pairing/network/windows-mobile-firewall.ts src/main/ssh/connection/ssh-connection.ts -src/main/ssh/ssh-proxy-command.ts +src/main/ssh/system-transport/ssh-proxy-command.ts src/main/ssh/system-transport/system-ssh-command.ts -src/main/ssh/system-transport/system-ssh-dynamic-forward-process.ts -src/main/ssh/system-transport/system-ssh-file-transfer.ts +src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.ts +src/main/ssh/system-transport/file-transfer/system-ssh-file-transfer.ts src/main/ssh/system-transport/system-ssh-operation-lifecycle.ts src/main/startup/ensure-virtual-display.ts src/main/pty/process-retirement/windows-process-tree-kill.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index e8637632070..46dcb8613d5 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -454,10 +454,10 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime", "mobile-relay"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. 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: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 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): Audit1316 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): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. 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. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. 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. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. 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. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result.", + "coverageNotes": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. 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: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 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): Audit1316 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): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. 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. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. 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. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. 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. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/25761"], "invariant": "A prompt occurrence leaves the input region only when an accepted reply answers it (a current host's provider acknowledgment, or an older host's whole-write acceptance as before) or the user collapses it to a strip above the composer, which writes nothing and keeps the card mounted with its partial answer; status-backed occurrences are told apart by the host wait's start, so view toggles and remounts preserve them while real clear/replacement supersedes them, and a transcript-only one is dropped when the view stops observing it; obsolete results cannot change replacements; selector groups wait for complete writes before pacing; refusal or unknown handoff never causes replay; a card retires an unsubmitted composer send without writing under it or losing its text, and the hidden composer cannot send or interrupt; Collapse or Escape folds a card without writing, never during an in-flight answer, and a new occurrence shows expanded again; the phone blocks only Send while a card is expanded and shows one card per occurrence; cancellation stops unsent groups and active dictation can stop.", - "oracle": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: 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): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it.", + "oracle": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: 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): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-paste-draft.test.ts src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts mobile/src/session/mobile-prompt-controller.test.ts --maxWorkers=2", @@ -606,7 +606,8 @@ "Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. 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.", "Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts.", "Historical assertion references before mobile owner-layout policy; removed references have no replacement claim: [{\"file\":\"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx\",\"assertions\":[\"ignores a raw acknowledgment from a rebound PTY\",\"sends only one cancellation, can cancel an answer, and permits retry after unknown\"]},{\"file\":\"mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts\",\"assertions\":[\"a late answer cannot reshow an answered replacement occurrence\",\"a late answer cannot dismiss a replacement session\"]},{\"file\":\"mobile/src/session/mobile-prompt-controller.test.ts\",\"assertions\":[\"finishes an older-host selector once and dismisses it like an acknowledged answer\",\"dismisses older-host approval choice %i like an acknowledged answer and restores Send\",\"retains permission choices on %s\",\"acknowledges the same pending %s after a view-only toggle\",\"shows a collapsed prompt again as a new wait\",\"keeps an acknowledged Deny hidden after the chat screen remounts on a lingering status\",\"drops an accepted result after real %s replacement\",\"keeps an agent notice answerable and retires only human input through the %s view\",\"retains exact cancelled calls through edits, prefix/ID replay, paging and new equal rows (%s)\",\"keeps structured %s admission separate from captured Cancel and delivered rows\",\"settles the terminal answer for Q1 after Q2 arrives without hiding Q2\",\"fences a late captured structured answer after %s replacement\",\"does not turn real %s host-result conversion into an answered question\",\"keeps later same-ID Cancel after eviction/reentry and old answer settlement\",\"keeps structured answer controls after a thrown send\",\"isolates equal portable IDs on two hosts and rejects the old host callback\"]},{\"file\":\"tests/e2e/native-chat-ssh-delivery.unit.test.ts\",\"assertions\":[\"serializes every chunk of a healthy large SSH answer before Enter and dismissal\",\"cancels remaining paced groups while an already-issued body still settles\",\"paired terminal.send uses provider settlement for accepted and lost acknowledgment\",\"older paired hosts keep their whole-write verdict for answers and ordinary sequences\",\"older paired hosts confirm ordinary chat sends and pasted answers as before\",\"finishes every older-host selector group once and settles the answer as delivered\"]},{\"file\":\"src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx\",\"assertions\":[\"keeps an in-flight message visible and never submits it into the approval\",\"routes no typing to the hidden composer until the card is answered\"]},{\"file\":\"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx\",\"assertions\":[\"keeps an answered approval hidden across a chat view remount and a PTY rebind\"]},{\"file\":\"src/main/runtime/terminal/input/runtime-terminal-writer.test.ts\",\"assertions\":[\"waits for complete body settlement before Enter\",\"does not send the suffix after refusal or unknown settlement\",\"returns unknown after an acknowledged prefix followed by refusal or bookkeeping failure\",\"preserves legacy raw body and Enter writes\"]}]", - "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed." + "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed.", + "Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim." ], "promotionCriteria": [ "Record change-reverted red/green evidence and repeatable remote rendered approval/question/dictation journeys.", @@ -3594,18 +3595,17 @@ "providers": ["local", "ssh"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): 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: Audit1412 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): Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed.", + "coverageNotes": "Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): 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: Audit1412 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): Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7086", "https://github.com/stablyai/orca/issues/16477" ], "invariant": "Index-only Git activity below the common Git directory must not emit worktrees:changed, invalidate worktree caches, or trigger fetchWorktrees fanout; structural add/remove/HEAD/gitdir/locked/config.worktree changes must still refresh worktrees and nudge Source Control. When the authoritative paired host accepts an external structural change for a uniquely identified server-local repo, each live client for that host must receive one existing host-scoped worktreesChanged invalidation and converge to the same repo/worktree identity without reconnect; duplicate watcher events must coalesce, stale cached or in-flight catalogs must not survive invalidation, and event-ignoring clients must remain compatible. Colliding local/SSH repo IDs must not publish the host-blind event until existing semantics can carry owner identity. External head moves (commit, amend, reset) must reach background worktree rows through spawn-free metadata reads, never through structural fanout. A process generation-scope rollover revokes every direct SSH target and old-scope provider request, not only the target whose counter exhausted.", - "oracle": "Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): 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): Classify exact git-common paths as structural, status-only, or ignored; count notifications from debounced watcher events; force the Linux/Windows poll path to emit allowlisted leaf events, detect linked HEAD rewrites independent of entry-directory mtime, and surface in-place index rewrites via the backstop re-stat; diff head identities from metadata-file reads and notify only real head moves. Join the real runtime RPC server to two independently authenticated E2EE clients plus an event-ignoring client, advance the host Git inventory, trigger duplicate structural watcher callbacks, and require one host renderer notification plus one runtime event and a refreshed catalog per subscribed client; require the event-ignoring client to refresh safely on explicit read. Hold a scan after it captures old inventory, join it from a second paired client, publish the watcher invalidation, advance Git independently, and require both overlapping RPCs to retry or join one fresh scan before returning. Disconnect one client, advance inventory again, and require reconnect to read current state without stale event replay. Give a watcher a local repo ID colliding with an SSH owner and require the host renderer refresh while the unqualified runtime event stays absent. Force the real path in isolated Electron apps with git worktree add, a host Git inventory assertion, store-subscription barriers, matching host/client worktree identity, and visible rows in both renderers. For direct SSH, roll one exhausted target into a fresh process generation scope while invalidating sibling target tokens, and fill a partial pushed authority before clearing that target's PTY bindings once. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed.", + "oracle": "Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): 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): Classify exact git-common paths as structural, status-only, or ignored; count notifications from debounced watcher events; force the Linux/Windows poll path to emit allowlisted leaf events, detect linked HEAD rewrites independent of entry-directory mtime, and surface in-place index rewrites via the backstop re-stat; diff head identities from metadata-file reads and notify only real head moves. Join the real runtime RPC server to two independently authenticated E2EE clients plus an event-ignoring client, advance the host Git inventory, trigger duplicate structural watcher callbacks, and require one host renderer notification plus one runtime event and a refreshed catalog per subscribed client; require the event-ignoring client to refresh safely on explicit read. Hold a scan after it captures old inventory, join it from a second paired client, publish the watcher invalidation, advance Git independently, and require both overlapping RPCs to retry or join one fresh scan before returning. Disconnect one client, advance inventory again, and require reconnect to read current state without stale event replay. Give a watcher a local repo ID colliding with an SSH owner and require the host renderer refresh while the unqualified runtime event stays absent. Force the real path in isolated Electron apps with git worktree add, a host Git inventory assertion, store-subscription barriers, matching host/client worktree identity, and visible rows in both renderers. For direct SSH, roll one exhausted target into a fresh process generation scope while invalidating sibling target tokens, and fill a partial pushed authority before clearing that target's PTY bindings once. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts", "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-external-worktree-discovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/ssh-connection-generation.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts --reporter=dot" ], "testFiles": [ @@ -3614,8 +3614,7 @@ "src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts", "src/main/window/attach-main-window-services.test.ts", "tests/e2e/paired-external-worktree-discovery.spec.ts", - "src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts", - "src/main/ssh/connection/ssh-connection-generation.test.ts" + "src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts" ], "assertionRefs": [ { @@ -3654,13 +3653,6 @@ "the headed host and separate paired Electron client render the same new worktree identity", "the paired client's main-process shared-control transport keeps one connection epoch while converging and compares Windows paths case-insensitively" ] - }, - { - "file": "src/main/ssh/connection/ssh-connection-generation.test.ts", - "assertions": [ - "one exhausted target rolls the process generation scope and invalidates every sibling target token", - "old-scope mutation expectations fail while the new-scope authority continues rotating" - ] } ], "evidenceRuns": [ @@ -3723,7 +3715,9 @@ "Audit1412 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/main/ssh/ssh-provider-authority.test.ts\",\n \"assertions\": [\n \"generation-scope rollover invalidates every target authority before abort callbacks run\",\n \"every registered old-scope provider request aborts exactly once\"\n ]\n }\n]", "Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. 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 assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts\",\n \"assertions\": [\n \"duplicate host watcher callbacks coalesce to one local notification and one worktreesChanged event for each of two live paired clients\",\n \"host inventory and both paired catalogs advance to the same worktree identity after runtime cache invalidation\",\n \"an invalidated in-flight host scan and a second client's joined read converge through one fresh retry before either can return stale data\",\n \"a disconnected client reconnects to current catalog state without replaying a stale invalidation\",\n \"an event-ignoring client remains compatible, and colliding local/SSH owners do not publish an owner-blind event\",\n \"the shared runtime publication remains valid without a headed renderer notifier\"\n ]\n }", - "Audit2003 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/watched-worktree-catalog-notification.test.ts src/main/runtime/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 6.19,\n \"summary\": \"Three watcher/runtime/wiring files passed with 38 tests, including two-client publication, reconnect, stale scan fencing, headless parity, owner-collision suppression, failure isolation, and main-window notifier wiring. Historical run: the watched-worktree-catalog-notification suite was later removed as mock forwarding coverage; it is not an active gate or replacement-equivalence claim.\"\n }" + "Audit2003 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/watched-worktree-catalog-notification.test.ts src/main/runtime/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 6.19,\n \"summary\": \"Three watcher/runtime/wiring files passed with 38 tests, including two-client publication, reconnect, stale scan fencing, headless parity, owner-collision suppression, failure isolation, and main-window notifier wiring. Historical run: the watched-worktree-catalog-notification suite was later removed as mock forwarding coverage; it is not an active gate or replacement-equivalence claim.\"\n }", + "Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed.", + "Historical SSH generation selector and assertion metadata before policy retirement, preserved verbatim; not current coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/authority/ssh-connection-generation.test.ts --reporter=dot\"\n\"src/main/ssh/connection/authority/ssh-connection-generation.test.ts\"\n{\n \"file\": \"src/main/ssh/connection/authority/ssh-connection-generation.test.ts\",\n \"assertions\": [\n \"one exhausted target rolls the process generation scope and invalidates every sibling target token\",\n \"old-scope mutation expectations fail while the new-scope authority continues rotating\"\n ]\n }" ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if index-only churn can emit worktrees:changed, or if structural add/remove/HEAD/lock changes fail to converge." }, @@ -4235,10 +4229,10 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): 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: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): 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: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", "motivatingLinks": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -4321,7 +4315,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed." ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, @@ -4439,7 +4434,7 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. 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): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. 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): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 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): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. 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. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. 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. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result.", + "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. 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): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. 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): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 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): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. 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. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. 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. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-5557/remote-html-preview-render-workspace-files-locally-over-the-file", "https://linear.app/stably/issue/STA-3872/unable-to-open-html-files-in-remote-server", @@ -4450,7 +4445,7 @@ "https://github.com/stablyai/orca/pull/13876" ], "invariant": "Opening one HTML preview from a paired client renders the workspace document in exactly one client-local browser tab, located by that document and served over the orca-preview scheme. The client gains exactly that one browser workspace and it is the document one — blank where a URL page carries a URL, named by the document, with the chip naming the file — while the host gains no browser page at all, neither in its own page registry nor in the tab snapshot its clients publish into. The preview occupies its own split without taking focus from the source editor; an explicit click activates it, and closing it removes only the preview. Following a document from a file link is the other half of that switch and does move the reader to it, tab group included, whether the preview is new or already open, because opening a file is a request to look at it. A document tab quit with the client comes back as the same row on a grant the relaunched client mints afresh. A preview is named by the browser page it is open in, not by a namespace of its own, and the page registry has two halves: a workspace-document guest is registered in its own map and is absent from the browsing one entirely. That absence is the fence. Page, session and profile management, agent tab enumeration and command targeting, download routing and certificate attribution all read the browsing map directly, in more places than a per-channel guard could be remembered in, so none of them can name a document page and none of them carries a guard. Browser tools the reader drives (element grab, hover describe, selection capture, the annotation viewport bridge) are the one operation that legitimately spans the halves, and they go through the single authority that reads both, keyed by the page and its hosting renderer. The halves are disjoint in both directions: browsing registration refuses a page the document half already holds, and minting a grant refuses a page the browsing half already holds, so one id can never name a surface in both. The headless backend acts on that refusal by destroying the window it had already opened rather than leaving a policy-less page behind an id nothing can drive, keeping nothing under that id for its own shutdown to hand back. Registration refuses on the same terms when the guest it was asked about is already gone. The exit door is guarded in both its halves: a preview withdraws by revoking its grant and never through the unregister channel, so a page the document half holds arriving there is refused before either the registration teardown or the grab-state disposal beside it, which would otherwise drop the intent an in-flight preview grab compares by identity and leave that grab answering ok without ever arming its guest. A bridge request whose guest does not resolve is refused without tearing down the page it named, so a misaddressed request cannot cancel a healthy page's in-flight downloads and grabs. The annotation viewport bridge resolves its guest when its serialized op actually runs rather than when the request arrived, so a cross-process navigation while it waited cannot leave the bridge installed in a retired guest while the reader looks at a new one. State main keys by a preview's page is disposed when that page's grant is revoked, which is the only signal a preview's surface is gone. A tool asking for a page whose guest has not attached yet waits for that registration and arms when it arrives, rather than answering not-ready at the reader; that wait resolves only the request already naming this page, never the worktree-wide or any-tab waits the CLI and agents use to ask for a browser tab to drive. Handing the previewed document to the reader's own machine routes on the owners its grant was minted against — the file's own connection owner and the worktree's own runtime owner, neither read from the tab's stored fields. Only a document proven to live on this machine reaches the client OS; one with a resolved remote owner is downloaded first; and one whose owner cannot be resolved at all, workspace root included, is refused with a message naming that, because the download route would otherwise read the same absolute path on the client and hand back a same-named local file under the remote document's name. A runtime-owned path that falls outside its worktree root is refused by that route itself and surfaces as a failure toast rather than a download. Nothing the document does writes a file to this machine either: the preview partition denies downloads outright instead of routing them through the browser download flow, which has no page to attribute a preview's bytes to and would otherwise reserve a name in this desktop's Downloads folder and write them there unprompted. That refusal is visible to the reader and invisible to the document: the preview's shell carries a fixed sentence saying downloads are off, published at most once per preview per interval so a document asking in a loop cannot fill Orca's chrome, while the page itself gets back exactly what it got before, which is nothing. The sentence names no file, because the document chooses the name it offers; and a refusal never takes the document away the way an entry document's own failure does, whatever it names. A preview is a browser tab, not an editor tab in a preview mode: it is named the way a browser tab is named — by the document it shows when that document declares a title, and by the file it shows when it does not — while the chip goes on naming the file and the host whatever the document calls itself. A title is refused on the same terms the url is: a document that declares none has Chromium report the grant URL as its title, and that title is stored, mirrored onto the tab and written to disk, so anything carrying the scheme falls back to the file instead. It is created by the preview action as a page located by its document, it carries the workspace-relative path copy the editor's path header owned, and closing it revokes the grant that made the document readable while a URL tab closing beside it revokes nothing. Chrome persisted by builds that made previews editor tabs is dropped on restore rather than coming back naming a surface no restore can produce, and the ordinary editor tab for the same document is left alone. A document tab is held back at the mobile publish boundary — no client holds its grant, and the wire has no tab kind for it — while an ordinary browser tab beside it still publishes. It is held back from the group projection that publishes tab order, recency and group activity as well as from the tab list itself, so no published group names a tab the phone is never sent. A browser page can be located by a workspace document instead of a URL, and the document is the whole of its stored identity. The grant and the orca-preview URL that document is served over are minted when the page mounts and replaced by a hard reload, so neither is ever written to the page's url, mirrored onto its tab, persisted or published: such a page's url is the blank URL from creation through restore, including when a session written elsewhere carries a grant URL in, and what the session carries is the worktree and path a restored page mints afresh against today's owners. Every door onto a page's url holds that line — creation, the title update, and the navigation commit alike — so a report about a document page cannot give it a URL it never had, and the title fallback and the loading affordance follow the url each door actually wrote. The mirror carries the document too, so a tab entry cannot go on naming a document its active page has left. Every guest in the app is policy-attached through one door: a workspace document takes a restricted profile there rather than a separate installer beside it, so the attachment bookkeeping that door owns — what registration refuses, and what teardown frees — covers a preview on the same terms as a browsing page, and a preview takes none of the browsing machinery that door installs. That authority answers from the moment the embedder hands the guest over rather than only after a later navigation: the guest binds to the grant it is already showing, so the tools reach the document the reader opened and not just one they navigated to. A read the host reports as truncated or over-cap is refused rather than served partially, and a document outside the paired worktree is refused with a message naming that boundary instead of a bare read failure. The rendered document reaches nothing off-machine on its own: every served response carries a self-only content security policy, the preview session cancels any request that is not in-document, subframes cannot navigate outside the grant, a guest no document has yet bound to a grant may not navigate at all, the guest gathers no ICE candidates, and an SSH path that canonicalizes outside the grant root is refused before it is read. The one route out is a link the reader presses: a trusted click on an anchor, reported by the preview's own preload from a guest still bound to a live grant, leaves through the configured browser destination and captured source route — and only after the reader confirms the exact destination URL, so a document cannot spend a single stray press exfiltrating what it can read into a link it authored. The preview hands its guest that focus itself whenever it is the surface the reader is in — a browsing page gets it from the chrome around it, and a preview has no chrome to get it from — and it does so only then, so a preview mounted behind a terminal or an editor never takes the keyboard from what the reader is actually in. It offers again when the window itself takes focus back and nothing in the embedder has claimed that focus, because another app coming to the front lands focus on the embedder rather than the guest and the route out would otherwise stay shut until something remounted the pane — while the same window focus also arrives when the reader presses a tab, that being the guest's own blur returning, and taking focus back from there would fight the reader for their own click. Nothing else does. A navigation or popup the document starts by itself is swallowed whatever else is happening, including immediately after a genuine press elsewhere in the document, so a page that can read its grant cannot hand it to a browser tab; a middle click opens nothing; and a fragment link is answered inside the document. A preview attach carries the preview preload and no renderer-supplied one, and no other attach path can acquire it. A subresource the workspace will not send degrades the document to a notice naming that file, never to a failure panel over a page that rendered. A grant outlives neither the tab that owns it nor the renderer document that minted it, and only the trusted renderer can mint or revoke one. For the browser creations this gate still owns, owner-pinned creation returns the canonical host page identity before navigation readiness; delayed navigation cannot turn a created page into an unidentifiable failure or a duplicate retry. Capability rejection before host mutation must preserve the original error, issue no RPC, surface a failure toast, and remove only a caller-declared newly-created empty split. Post-create reconciliation failure requires exact rollback; ambiguous rollback rejects without local fallback.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. 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): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. 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): Audit1709 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: Audit1687 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: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. 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): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: 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): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle.", + "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. 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): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. 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): Audit1709 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: Audit1687 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: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. 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): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: 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): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", @@ -4472,14 +4467,13 @@ "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3", "npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts src/renderer/src/store/slices/browser/browser.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts src/renderer/src/store/slices/browser/browser.test.ts", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" ], "testFiles": [ "src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts", - "src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts", "src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts", "src/renderer/src/store/slices/browser/browser.test.ts", "src/main/browser/document-preview/doc-preview-grant-registry.test.ts", @@ -4509,12 +4503,6 @@ "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts" ], "assertionRefs": [ - { - "file": "src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts", - "assertions": [ - "closing an absent renderer page returns browser_tab_not_found instead of an untyped failure" - ] - }, { "file": "src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts", "assertions": ["explicit cleanup cannot close a page owned by another worktree"] @@ -4957,7 +4945,8 @@ "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", "D01 candidate audit retires this complete dated receipt because a named test source changes in the candidate overlay. It supplies no new execution or equivalent-coverage claim. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 1.27,\n \"summary\": \"Candidate with the sole delta that every failure sets the blocking reason, asset or not, failed 4/14 on the asset-notice assertions — the same mutant the retired 2026-08-26 record measured at 3/10, re-run at the relocated path. A refused subresource must name itself over a document that stays mounted; only the entry document may take the page away.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"\n }", "D01 candidate audit retires this complete dated receipt because a named test source changes in the candidate overlay. It supplies no new execution or equivalent-coverage claim. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\",\n \"result\": \"passed\",\n \"durationSeconds\": 1.54,\n \"summary\": \"14/14 on the reader-facing failure suite at its relocated path. This and the red run below replace the 2026-08-26 pair recorded against the pre-relocation path (10/10 green, 3/10 red), re-measured today so the entry/subresource split keeps a red half rather than only a green one.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"\n }", - "D01 final candidate whole-registration policy removes retired module selectors and obsolete assertion descriptions prospectively. Existing unaffected receipts retain their original scope; reduced selectors have no new execution or equivalent replacement claim. Retired named modules: [\"src/preload/doc-preview-link-interception.test.ts\",\"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"]. Retired compound assertion refs, preserved as historical data: [{\"file\":\"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\"assertions\":[\"an external preview link shows the reader its exact destination and becomes a browser tab only after confirmation\",\"a declined confirmation opens nothing, and a confirmed tab that is refused or fails outright surfaces instead of being dropped\"]}]" + "D01 final candidate whole-registration policy removes retired module selectors and obsolete assertion descriptions prospectively. Existing unaffected receipts retain their original scope; reduced selectors have no new execution or equivalent replacement claim. Retired named modules: [\"src/preload/doc-preview-link-interception.test.ts\",\"src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.failure-message.test.tsx\"]. Retired compound assertion refs, preserved as historical data: [{\"file\":\"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\"assertions\":[\"an external preview link shows the reader its exact destination and becomes a browser tab only after confirmation\",\"a declined confirmation opens nothing, and a confirmed tab that is refused or fails outright surfaces instead of being dropped\"]}]", + "Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed. Retired assertion reference: {\"file\":\"src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts\",\"assertions\":[\"closing an absent renderer page returns browser_tab_not_found instead of an untyped failure\"]}" ], "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." }, @@ -4989,12 +4978,12 @@ "providers": ["local", "remote-runtime", "ssh", "wsl"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. 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): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 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: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1563 retires mock cookie inventories, summary/flag/counter checks, historical replacement/replay narratives and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise owned admission and cleanup, real staged-file lifetime, JSON/SQLite/WAL/schema compatibility, synthetic encryption and native Electron SameSite storage. Session/CDP/credential/write/renderer producers remain injected where recorded. Seven unchanged native definitions are not rerun locally; known stale registry-stub fixtures are not executable proof. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1559 removes mocked host/lease/reconciliation, event/flag/counter, forwarding, inventory and retry-budget alarms without equivalent replacement coverage. Retained cases establish owned promise, registry, rollback, admission and cleanup boundaries with injected Electron/renderer/host inputs; actual local sockets, file staging and Buffer collection are scoped in the PR. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain historical evidence only. No live paired runtime, rendered browser/profile/TLS or device claim. Historical scope before this audit: Audit1401 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): Audit1340 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic protocol, registry, injected-socket, and loopback-listener tests cover strict framing, remote-DNS targets, exact destination-write and source-consumption credit, at most 256 streams per route with pending opens counted inside that cap, 1024 admitted opens per 10-second monotonic window, an 8 MiB per-route application-buffer ledger, shared 32 MiB browser-host and 128 MiB process ledgers across application copies, encrypted client queues, and native WebSocket bufferedAmount, bounded byte/claim/socket-source counts, a four-frame queued-drain quantum, authority epochs, exact host selection, one host per authenticated connection, four hosts per paired device, eight global browser-host polls with four per authenticated paired device, a shared ask/host ceiling that retains one quarter for waits, bounded initial and reconnect runtime_busy recovery, long-poll metering and disconnect abort, monotonic host/page/route generations without page tombstones, two-phase exact page retirement with cancellation, connection-owned cleanup, exact client revocation, stale and replaced fences, retired stream IDs, half-close and close ordering, SOCKS CONNECT, bind/close races, listener wildcard normalization, unsupported commands, unavailable routes, and raw/terminal binary-handler isolation. Page commands use a separately echoed v1 attach negotiation, exact authority/host/page generations, bounded command IDs and sequences, and bounded create/navigate payloads; legacy attaches still receive only the unchanged ready/revoked event shapes. A second optional reconciliation subprotocol gates bounded reclaim, close, and restore payloads behind exact attach/ready echo, complete inventory, command negotiation, reconnect authority, and command-result authority; the production client advertises it only with the matching command and inventory capabilities. Exact guest or app-renderer loss marks one page generation outcome-unknown, coalesces a bounded negotiated inventory reattach, closes or retires the dead generation, and allocates a fresh generation before URL restore; explicit close is not misclassified as a crash. Mixed-version mutation tests project hidden client pages before activate, close, split, reorder, and move-to-group admission, preserve hidden raw order slots, translate visible insertion indices, and project mutation snapshots. A production server orchestrator consumes each immutable inventory once, reserves target generations without exposing placement, emits only negotiated ledger commands, commits after exact completed proof, preserves unrelated and server placements, aborts an attempt when connection authority enters reconnect grace, and requires fresh inventory after failure or abort. The production client dispatcher additionally proves per-page FIFO execution, exact payload-matched duplicate replay, frozen command/result snapshots, a global retired-generation floor, transactional admission, bounded pages/active commands/queues/per-page and global result cache/concurrency, create dependency failure, cancellation, deduplicated retirement joining, and bounded close without late-result overwrite. The server ledger owns issue order and immutable command/result snapshots, bounds outstanding commands, active pages, and per-page/global replay caches, releases active-page capacity after an exact completed close while retaining bounded result replay, validates the shared wire payload before admission, requires live delivery and exact placement, authenticates results to the negotiated connection and paired lease, rejects gaps and conflicting replay, and fences outstanding outcomes at exact retirement. Negotiated command results reuse the authenticated attach socket through bounded nested JSON requests; exact ID routing, reverse-order replies, unknown and duplicate IDs, timeout teardown, serialization failure, aggregate queue accounting, acknowledgement validation, and the unchanged non-v1 path are deterministic. A stable local listener rejects CONNECT while offline or reconnecting, retains its address across replacement, requires a strictly increasing tunnel generation, ignores late superseded callbacks, propagates tunnel protocol failure to the route owner, and recycles exhausted stream IDs only after generation replacement. Reconnect uses the unchanged native v1 attach payload and capability pair; SSH descriptors alone add an execution-host capability and require a runtime-minted grant bound to the exact browser-host lease. Exact SSH provider epoch and connection generation fence ssh2 forwardOut and one non-interactive standalone system-SSH dynamic forward per route. Unit tests preserve domain-form SOCKS requests, sanitize remote errors, bound stderr, cancel startup, release timed-out and synchronously failed sockets, and release routes once. An ephemeral Docker sshd resolves a container-only domain and returns a unique HTTP marker through both ssh2 and the actual system-OpenSSH dynamic-forward adapter without touching the user's SSH files; authority loss fences the ssh2 route. The execution runtime charges route application bytes to the same per-host/process policy; its existing E2EE owner separately caps native outbound buffers process-wide. Production-registered browser-host and paired-runtime methods lease one exact host, prove attach, command delivery, and result settlement share one exact connection identity, then carry SOCKS and HTTP bytes over a dedicated E2EE socket to the fenced execution-host revision and prove route close destroys the destination socket. The production desktop adapter now composes one exact host per environment pairing revision with the page executor, current renderer selector, route Session/WebContents registries, and one reference-counted route per canonical execution-host key. Negotiated same-client control reconnect retains exact authority, placements, grants, dispatcher dedupe, executor guests, and listener addresses; it fences tunnels immediately, blocks route admission, reattaches command delivery only after ready, and replays unsettled commands without repeating completed mutations. Terminal release, replacement, legacy disconnect, and reconnect-grace expiry make only the exact host generation's client placements non-cancellable retirement-pending while retaining capacity until exact cleanup; reconnect grace preserves them. Environment replacement and app shutdown still serialize transport closure before page cleanup and force-close every remaining route. The production placement preparation starts the exact desktop adapter and advertises host/tunnel capabilities only when the paired Electron client is eligible. Node stream-internal high-water bytes, strict cross-route scheduling, and physical cross-platform evidence remain uncovered. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. The removed retry-arithmetic and attach-request inventory suites are not current coverage; retained lease and composition suites exercise admission retry, cleanup, inventory negotiation, and reconnect behavior. Test-value audit1293 removes src/main/browser/network/tunnels/browser-network-tunnel-client-memory-budget.test.ts (4 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1302: src/main/browser/client-pages/lifecycle/browser-client-page-unavailability.test.ts: Every route/guest lifecycle/currentness/navigation/renderer/automation authority is supplied by fake callbacks, then unavailability listener is invoked manually and private inventory/mock calls are checked. No guest destruction, renderer disconnect or actual reconciliation/close consumer. Lose generation fence/reconcile-once/missing-renderer-close branch alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1318: src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts: Retain actual local encrypted WebSocket subscription concurrency routing when host replies out of order, plus an exception thrown by a real ws consumer callback being turned into a subscription error. Server is a test-shaped handshake/response producer using production crypto, not actual runtime host/auth authority or independent cryptographic oracle. Remove happy second-request duplicate, unknown/duplicate-ID branches, fixed32 capacity, serialization/capacity/timeouts and fake memory release/admission call-count scenarios; intentionally lose those alarms. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1340: src/main/runtime/runtime-binary-message-router.test.ts removed. Connection mode conflict exceptions and one terminal/raw callback each. 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. Audit1371 removes the reconciliation protocol/capability echo inventory from browser-client-host-reconciliation.test.ts. The pending command result refusal without exact authority and later accepted acknowledgement callback remains byte-identical. The narrow negotiation echo alarm is intentionally lost; no equivalent browser/authenticated transport proof is claimed. Existing receipts with unchanged selectors retain only their original scope. Audit1401: src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts reduced. Loses deterministic equal-length URL compaction tie-breaking and reversed-input invariance alarm. No equivalent replacement coverage is claimed.", + "coverageNotes": "Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. 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): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 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: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1563 retires mock cookie inventories, summary/flag/counter checks, historical replacement/replay narratives and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise owned admission and cleanup, real staged-file lifetime, JSON/SQLite/WAL/schema compatibility, synthetic encryption and native Electron SameSite storage. Session/CDP/credential/write/renderer producers remain injected where recorded. Seven unchanged native definitions are not rerun locally; known stale registry-stub fixtures are not executable proof. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1559 removes mocked host/lease/reconciliation, event/flag/counter, forwarding, inventory and retry-budget alarms without equivalent replacement coverage. Retained cases establish owned promise, registry, rollback, admission and cleanup boundaries with injected Electron/renderer/host inputs; actual local sockets, file staging and Buffer collection are scoped in the PR. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain historical evidence only. No live paired runtime, rendered browser/profile/TLS or device claim. Historical scope before this audit: Audit1401 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): Audit1340 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic protocol, registry, injected-socket, and loopback-listener tests cover strict framing, remote-DNS targets, exact destination-write and source-consumption credit, at most 256 streams per route with pending opens counted inside that cap, 1024 admitted opens per 10-second monotonic window, an 8 MiB per-route application-buffer ledger, shared 32 MiB browser-host and 128 MiB process ledgers across application copies, encrypted client queues, and native WebSocket bufferedAmount, bounded byte/claim/socket-source counts, a four-frame queued-drain quantum, authority epochs, exact host selection, one host per authenticated connection, four hosts per paired device, eight global browser-host polls with four per authenticated paired device, a shared ask/host ceiling that retains one quarter for waits, bounded initial and reconnect runtime_busy recovery, long-poll metering and disconnect abort, monotonic host/page/route generations without page tombstones, two-phase exact page retirement with cancellation, connection-owned cleanup, exact client revocation, stale and replaced fences, retired stream IDs, half-close and close ordering, SOCKS CONNECT, bind/close races, listener wildcard normalization, unsupported commands, unavailable routes, and raw/terminal binary-handler isolation. Page commands use a separately echoed v1 attach negotiation, exact authority/host/page generations, bounded command IDs and sequences, and bounded create/navigate payloads; legacy attaches still receive only the unchanged ready/revoked event shapes. A second optional reconciliation subprotocol gates bounded reclaim, close, and restore payloads behind exact attach/ready echo, complete inventory, command negotiation, reconnect authority, and command-result authority; the production client advertises it only with the matching command and inventory capabilities. Exact guest or app-renderer loss marks one page generation outcome-unknown, coalesces a bounded negotiated inventory reattach, closes or retires the dead generation, and allocates a fresh generation before URL restore; explicit close is not misclassified as a crash. Mixed-version mutation tests project hidden client pages before activate, close, split, reorder, and move-to-group admission, preserve hidden raw order slots, translate visible insertion indices, and project mutation snapshots. A production server orchestrator consumes each immutable inventory once, reserves target generations without exposing placement, emits only negotiated ledger commands, commits after exact completed proof, preserves unrelated and server placements, aborts an attempt when connection authority enters reconnect grace, and requires fresh inventory after failure or abort. The production client dispatcher additionally proves per-page FIFO execution, exact payload-matched duplicate replay, frozen command/result snapshots, a global retired-generation floor, transactional admission, bounded pages/active commands/queues/per-page and global result cache/concurrency, create dependency failure, cancellation, deduplicated retirement joining, and bounded close without late-result overwrite. The server ledger owns issue order and immutable command/result snapshots, bounds outstanding commands, active pages, and per-page/global replay caches, releases active-page capacity after an exact completed close while retaining bounded result replay, validates the shared wire payload before admission, requires live delivery and exact placement, authenticates results to the negotiated connection and paired lease, rejects gaps and conflicting replay, and fences outstanding outcomes at exact retirement. Negotiated command results reuse the authenticated attach socket through bounded nested JSON requests; exact ID routing, reverse-order replies, unknown and duplicate IDs, timeout teardown, serialization failure, aggregate queue accounting, acknowledgement validation, and the unchanged non-v1 path are deterministic. A stable local listener rejects CONNECT while offline or reconnecting, retains its address across replacement, requires a strictly increasing tunnel generation, ignores late superseded callbacks, propagates tunnel protocol failure to the route owner, and recycles exhausted stream IDs only after generation replacement. Reconnect uses the unchanged native v1 attach payload and capability pair; SSH descriptors alone add an execution-host capability and require a runtime-minted grant bound to the exact browser-host lease. Exact SSH provider epoch and connection generation fence ssh2 forwardOut and one non-interactive standalone system-SSH dynamic forward per route. Unit tests preserve domain-form SOCKS requests, sanitize remote errors, bound stderr, cancel startup, release timed-out and synchronously failed sockets, and release routes once. An ephemeral Docker sshd resolves a container-only domain and returns a unique HTTP marker through both ssh2 and the actual system-OpenSSH dynamic-forward adapter without touching the user's SSH files; authority loss fences the ssh2 route. The execution runtime charges route application bytes to the same per-host/process policy; its existing E2EE owner separately caps native outbound buffers process-wide. Production-registered browser-host and paired-runtime methods lease one exact host, prove attach, command delivery, and result settlement share one exact connection identity, then carry SOCKS and HTTP bytes over a dedicated E2EE socket to the fenced execution-host revision and prove route close destroys the destination socket. The production desktop adapter now composes one exact host per environment pairing revision with the page executor, current renderer selector, route Session/WebContents registries, and one reference-counted route per canonical execution-host key. Negotiated same-client control reconnect retains exact authority, placements, grants, dispatcher dedupe, executor guests, and listener addresses; it fences tunnels immediately, blocks route admission, reattaches command delivery only after ready, and replays unsettled commands without repeating completed mutations. Terminal release, replacement, legacy disconnect, and reconnect-grace expiry make only the exact host generation's client placements non-cancellable retirement-pending while retaining capacity until exact cleanup; reconnect grace preserves them. Environment replacement and app shutdown still serialize transport closure before page cleanup and force-close every remaining route. The production placement preparation starts the exact desktop adapter and advertises host/tunnel capabilities only when the paired Electron client is eligible. Node stream-internal high-water bytes, strict cross-route scheduling, and physical cross-platform evidence remain uncovered. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. The removed retry-arithmetic and attach-request inventory suites are not current coverage; retained lease and composition suites exercise admission retry, cleanup, inventory negotiation, and reconnect behavior. Test-value audit1293 removes src/main/browser/network/tunnels/browser-network-tunnel-client-memory-budget.test.ts (4 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1302: src/main/browser/client-pages/lifecycle/browser-client-page-unavailability.test.ts: Every route/guest lifecycle/currentness/navigation/renderer/automation authority is supplied by fake callbacks, then unavailability listener is invoked manually and private inventory/mock calls are checked. No guest destruction, renderer disconnect or actual reconciliation/close consumer. Lose generation fence/reconcile-once/missing-renderer-close branch alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1318: src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts: Retain actual local encrypted WebSocket subscription concurrency routing when host replies out of order, plus an exception thrown by a real ws consumer callback being turned into a subscription error. Server is a test-shaped handshake/response producer using production crypto, not actual runtime host/auth authority or independent cryptographic oracle. Remove happy second-request duplicate, unknown/duplicate-ID branches, fixed32 capacity, serialization/capacity/timeouts and fake memory release/admission call-count scenarios; intentionally lose those alarms. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1340: src/main/runtime/runtime-binary-message-router.test.ts removed. Connection mode conflict exceptions and one terminal/raw callback each. 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. Audit1371 removes the reconciliation protocol/capability echo inventory from browser-client-host-reconciliation.test.ts. The pending command result refusal without exact authority and later accepted acknowledgement callback remains byte-identical. The narrow negotiation echo alarm is intentionally lost; no equivalent browser/authenticated transport proof is claimed. Existing receipts with unchanged selectors retain only their original scope. Audit1401: src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts reduced. Loses deterministic equal-length URL compaction tie-breaking and reversed-input invariance alarm. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4150/refactor-remote-browser-to-client-hosted-electron-webviews" ], "invariant": "A client-hosted browser network route exists only for an exact live server-owned browser-host lease, authority epoch, host generation, paired identity, execution-host revision or SSH provider authority, and server-owned route generation. A client page is usable only when its runtime ID, authority epoch, host identity and generation, logical page ID, page-host generation, current placement, and still-live lease all match atomically; a retired, retirement-pending, or server-placed page cannot be claimed as live client placement. Live logical placements and their identities are bounded, an occupied logical page cannot change placement until exact two-phase retirement completes, cancellation restores the same authority, and the runtime-wide page generation stays monotonic without tombstones. Server-issued page commands and results remain bounded, FIFO per page, immutable after admission, authenticated to the exact paired lease, attach connection, and live placement, and replayable only when byte-equivalent. Negotiated transient result-transport loss retains exact authority and replays unsettled commands through the preserved client dedupe cache; terminal authority loss makes outstanding outcomes unknown and makes only the exact host generation's placements non-cancellable retirement-pending until exact cleanup or reconciliation proof. Desktop composition installs exact command authority before delivery, keeps result settlements below nested-request capacity, suspends every tunnel without closing guests on negotiated loss, gates handlers through route recovery, and synchronously suspends routes and revokes exact retained navigation grants before asynchronous transport or handler cleanup on terminal loss. Navigation-revocation failure remains observable without preventing guest destruction and route cleanup. One environment pairing revision owns at most one composed desktop host and one reference-counted route per canonical execution-host key; pairing replacement and shutdown close control transport before pages and force-close routes even when guest cleanup remains ambiguous. Non-native descriptors require explicit capability negotiation and an exact runtime-minted lease-bound execution-host grant. Host selection never chooses arbitrarily, stale cleanup or settlement cannot remove a replacement, destination names remain unresolved until the execution host, credit returns only after writes settle, and route loss never falls back to desktop DNS or sockets. A main-owned local listener remains stable across upstream transport loss, rejects CONNECT while offline, accepts only a strictly newer tunnel generation, ignores superseded callbacks, and never reuses a stream ID within one generation. Pending opens, admitted open rate, nested control requests, per-route application bytes, aggregate browser-host/process bytes, claims, and socket sources remain bounded with exact release on settlement and retirement. Queued transport drain yields after a bounded quantum. The local SOCKS endpoint accepts only loopback CONNECT and rejects unsupported commands.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. 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): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 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: Audit1687 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: Audit1686 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: 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): Attach two browser hosts and require unqualified selection to fail ambiguous while exact selection succeeds. Reject a second identity on one connection and a fifth identity for one paired device, release one exact lease, then admit its replacement without starving another device. Admit four hosts from one authenticated device and a host from a second, reject the first device's fifth host, and release only the first device's exact counters while the second remains live. Fill asks and hosts to their shared ceiling, retain a quarter of the total budget for ordinary waits, close both sockets, and prove every global, class, and device counter releases. Reject one initial host attach with the unchanged runtime_busy response, then require bounded client-specific jitter to attach when capacity returns; repeated rejection and explicit close must release every timer and subscription. Replace one same-device connection, require the old subscription and route to fence, then prove late old cleanup leaves the new generation live. Mint an exact execution-host grant, reject a different key, prove late old grant cleanup leaves its replacement, and invalidate every grant with lease replacement. Reject client-to-client, client-to-server, server-to-server, and server-to-client placement overwrite until exact retirement. Begin retirement once idempotently, reject client use and every replacement while pending, cancel the exact token to restore the same placement, and reject delayed cancellation or completion after a newer retirement begins. On explicit release, replacement, legacy disconnect, and reconnect-grace expiry, require only the exact host generation's client placements to become non-cancellable retirement-pending before lease settlement; preserve negotiated grace, other hosts, server placements, replacements, and capacity until exact completion. Complete only the exact pending token, retain capacity until completion, and require a reused client page ID to receive a higher global generation without retaining a tombstone. Require a client page through the exact runtime, epoch, host, and page tuple; reject every mismatch, released or replaced leases, retirement-pending pages, retired pages, server placements, invalid identities, and the 257th live placement. Admit 1024 opens in one monotonic 10-second window and reject the 1025th until the window expires. Fill 8 MiB across destination-to-client queues and separately across unsettled client-to-destination writes, release one exact retired stream, admit one replacement, and require the next byte claim to close the route without stale-callback or reentrant-close underflow. Across multiple routes, charge application copies, encrypted queue entries, and dynamic native socket bytes to one 32 MiB browser-host and 128 MiB process ceiling; reject zero-byte claim/socket-source floods, fence released leases, synchronously release JavaScript queue claims while retaining native claims through exact socket close, and yield a parked queue after four frames without reordering. Route nested responses by exact ID under reordering, reject unknown and duplicate IDs, cap pending requests and queued bytes, and tear down every concurrent waiter once on timeout or close. Drive one real paired attach, command, and result through one exact connection ID; reject missing send support and malformed or wrong-runtime acknowledgements while preserving old non-v1 attaches. Drop an authenticated transport, require the same listener to reject CONNECT before and during reconnect, attach the exact existing native v1 payload and capability pair to a strictly newer generation, ignore late old callbacks, and roll an exhausted stream-ID ledger only by replacing the generation. Require SSH descriptors to add an execution-host capability and exact grant, reject missing grants and stale provider authority before resolver or binary registration, pass exact domains to ssh2 and system-SSH SOCKS without local resolution, sanitize connector diagnostics, and close every stream and standalone route process once on timeout, synchronous failure, or rotation. Drive the accepted lease through real paired E2EE native SOCKS-to-HTTP and ephemeral Docker ssh2 remote-only DNS journeys, then exercise exact frame, credit, half-close, stale-stream, remote-DNS, unsupported-command, offline, and teardown assertions.", + "oracle": "Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. 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): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 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: Audit1687 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: Audit1686 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: 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): Attach two browser hosts and require unqualified selection to fail ambiguous while exact selection succeeds. Reject a second identity on one connection and a fifth identity for one paired device, release one exact lease, then admit its replacement without starving another device. Admit four hosts from one authenticated device and a host from a second, reject the first device's fifth host, and release only the first device's exact counters while the second remains live. Fill asks and hosts to their shared ceiling, retain a quarter of the total budget for ordinary waits, close both sockets, and prove every global, class, and device counter releases. Reject one initial host attach with the unchanged runtime_busy response, then require bounded client-specific jitter to attach when capacity returns; repeated rejection and explicit close must release every timer and subscription. Replace one same-device connection, require the old subscription and route to fence, then prove late old cleanup leaves the new generation live. Mint an exact execution-host grant, reject a different key, prove late old grant cleanup leaves its replacement, and invalidate every grant with lease replacement. Reject client-to-client, client-to-server, server-to-server, and server-to-client placement overwrite until exact retirement. Begin retirement once idempotently, reject client use and every replacement while pending, cancel the exact token to restore the same placement, and reject delayed cancellation or completion after a newer retirement begins. On explicit release, replacement, legacy disconnect, and reconnect-grace expiry, require only the exact host generation's client placements to become non-cancellable retirement-pending before lease settlement; preserve negotiated grace, other hosts, server placements, replacements, and capacity until exact completion. Complete only the exact pending token, retain capacity until completion, and require a reused client page ID to receive a higher global generation without retaining a tombstone. Require a client page through the exact runtime, epoch, host, and page tuple; reject every mismatch, released or replaced leases, retirement-pending pages, retired pages, server placements, invalid identities, and the 257th live placement. Admit 1024 opens in one monotonic 10-second window and reject the 1025th until the window expires. Fill 8 MiB across destination-to-client queues and separately across unsettled client-to-destination writes, release one exact retired stream, admit one replacement, and require the next byte claim to close the route without stale-callback or reentrant-close underflow. Across multiple routes, charge application copies, encrypted queue entries, and dynamic native socket bytes to one 32 MiB browser-host and 128 MiB process ceiling; reject zero-byte claim/socket-source floods, fence released leases, synchronously release JavaScript queue claims while retaining native claims through exact socket close, and yield a parked queue after four frames without reordering. Route nested responses by exact ID under reordering, reject unknown and duplicate IDs, cap pending requests and queued bytes, and tear down every concurrent waiter once on timeout or close. Drive one real paired attach, command, and result through one exact connection ID; reject missing send support and malformed or wrong-runtime acknowledgements while preserving old non-v1 attaches. Drop an authenticated transport, require the same listener to reject CONNECT before and during reconnect, attach the exact existing native v1 payload and capability pair to a strictly newer generation, ignore late old callbacks, and roll an exhausted stream-ID ledger only by replacing the generation. Require SSH descriptors to add an execution-host capability and exact grant, reject missing grants and stale provider authority before resolver or binary registration, pass exact domains to ssh2 and system-SSH SOCKS without local resolution, sanitize connector diagnostics, and close every stream and standalone route process once on timeout, synchronous failure, or rotation. Drive the accepted lease through real paired E2EE native SOCKS-to-HTTP and ephemeral Docker ssh2 remote-only DNS journeys, then exercise exact frame, credit, half-close, stale-stream, remote-DNS, unsupported-command, offline, and teardown assertions.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts", @@ -5017,7 +5006,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/browser-network-execution-route.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts src/main/ssh/system-transport/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/browser-network-execution-route.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts", "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" ], @@ -5054,7 +5043,7 @@ "src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts", "src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts", "src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts", - "src/main/ssh/system-transport/system-ssh-dynamic-forward-process.test.ts", + "src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts", "src/main/ssh/port-forwarding/ssh-port-forward.test.ts", "src/main/browser/network/tunnels/remote-browser-socks-server.test.ts", "src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts", @@ -5272,9 +5261,8 @@ ] }, { - "file": "src/main/ssh/system-transport/system-ssh-dynamic-forward-process.test.ts", + "file": "src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts", "assertions": [ - "system SSH uses BatchMode=yes, disables ControlMaster, and positions one dynamic forward before the destination", "authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately" ] }, @@ -5415,7 +5403,9 @@ "Audit1983 historical original testFiles object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n\"src/main/runtime/rpc/methods/session-tabs/session-tab-browser-placement-mutations.test.ts\"", "Audit1983 historical original testFiles object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n\"src/main/runtime/rpc/methods/session-tabs/session-tab-browser-placement-projection.test.ts\"", "Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. 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/rpc/server/runtime-rpc-browser-host-admission.test.ts\",\n \"assertions\": [\n \"browser-host attachment has a dedicated sub-cap that preserves ordinary wait admission\",\n \"one paired device cannot consume the second device's reserved browser-host share\",\n \"asks and browser hosts share a ceiling that retains one quarter of total capacity for waits\",\n \"socket close aborts the exact host and wait handlers and releases both counters\"\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/rpc/server/runtime-rpc-browser-host-admission.test.ts\",\n \"assertions\": [\n \"browser-host attachment has a dedicated sub-cap that preserves ordinary wait admission\",\n \"one paired device cannot consume the second device's reserved browser-host share\",\n \"asks and browser hosts share a ceiling that retains one quarter of total capacity for waits\",\n \"socket close aborts the exact host and wait handlers and releases both counters\"\n ]\n }", + "Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged.", + "Historical dynamic-forward assertion metadata before inventory retirement, preserved verbatim:\n{\n \"file\": \"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\n \"assertions\": [\n \"system SSH uses BatchMode=yes, disables ControlMaster, and positions one dynamic forward before the destination\",\n \"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"\n ]\n }" ], "demotionRule": "Keep experimental or demote if a self-asserted or ambiguous host can receive a route, an SSH descriptor bypasses capability, lease-bound grant, or provider-authority checks, late cleanup can remove a replacement, a route can resolve names on the desktop, exceed a byte or stream bound, replenish credit before destination settlement, accept a stale or non-increasing generation, reuse a stream ID within one generation, lose or bypass its fail-closed listener during reconnect, expose the SOCKS listener off-loopback, accept BIND/UDP, or fall back when the selected route is unavailable." }, @@ -8591,13 +8581,13 @@ "providers": ["paired-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": [], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: 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. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. 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: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/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/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 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 the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. 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. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. 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. 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. 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. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. 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. 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. 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. 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. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: 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. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. 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: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/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/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 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 the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. 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. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. 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. 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. 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. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. 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. 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. 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. 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. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8652", "https://github.com/stablyai/orca/pull/10625" ], "invariant": "A host advertising terminal.paired-parking.v1 keeps the PTY and bounded authoritative history alive while an ordinary hidden-view park destroys the client xterm and releases its raw per-PTY stream. Reveal must restore up to the requested 5,000 rows, parked-time side effects/output, the same PTY identity, and continued input/output. Parked watcher synchronization compares parking semantics rather than fresh object identity, owns setup and cleanup across StrictMode replay, reconciles real PTY/layout changes, and performs no terminal-state scan when nothing is parked. After a host main-process relaunch, unknown local delivery-sync state must not be treated as proof that a surviving daemon PTY is already foregrounded. An empty headed session-tab inventory is authoritative only after the current renderer graph generation publishes a complete inventory and every execution host answers the PTY census; unpublished, resync-pending, transport-failed, and partially scoped inventories remain unverifiable, while genuinely authoritative empty and non-empty inventories settle and a scope-less legacy empty keeps its pre-authority best-effort settle so outdated hosts retain agent auto-resume. The unpublished-empty regression must keep the resume dispatch parked with exactly one daemon process/writer; restoring unconditional empty hydration must release one dispatch and create two live writers. If subscription precedes provider readiness, authoritative inventory must reconsider that existing subscriber without spawning, resizing, or changing reconnect state. A snapshot without an output high-water must keep it unknown rather than borrowing a layout version that can suppress newer live output. Hosts without the capability must gate hidden raw output before xterm scheduling and repaint from the authoritative snapshot on reveal while retaining the existing limit/TTL force-parking fallback. After the first semantic title state, decorative spinner frequency must add zero paired client-event frames and zero full session-tabs work between status-freshness leases regardless of hidden worktree count. Continuous working or permission evidence may refresh each affected worktree once per 15 minutes through one globally spaced FIFO so current and legacy viewers do not decay before 30 minutes; sibling PTYs share that worktree refresh, while local title animation, raw output, and semantic title, status, bell, completion, and query facts remain intact. A paired terminal stream whose delivery credits stop progressing must replace only that stream; command silence first probes authoritative state and replaces the stream if the probe times out or proves the PTY advanced beyond the client's delivered output sequence. When no comparable delivery high-water exists, the first sequenced probe establishes a baseline and only later advancement proves staleness. A same-sequence snapshot remains valid proof of a responsive silent command. A successful status probe may replace a pre-ready shared-control socket without rejecting or duplicating calls already waiting for that transport. Manual disconnect must retain pairing while preventing queued or passive calls and subscriptions from recreating transport until explicit Connect. A paired pane reconnecting to a relaunched host that has not yet published its window graph (an unpublished frame, bare or client-projected) must stay in recovery rather than retire, and the host's first published snapshot carrying the surface must reattach it; a published frame lacking the surface still retires it. The placeholder is only ever sent before the host's graph first publishes; afterwards a worktree with no tabs gets a real empty answer, pushed once to any client that asked during startup, so a paired client opening a never-opened host worktree still gets its first terminal.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: 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. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): 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: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: 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. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. 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): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. 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): 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: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -9067,7 +9057,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector 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." }, @@ -9244,8 +9235,8 @@ "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], - "coveredProviders": ["ssh"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): 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/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): 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. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. 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: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. 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.", + "coveredProviders": [], + "coverageNotes": "Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): 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/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): 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. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. 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: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. 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.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6836", "https://github.com/stablyai/orca/pull/6858", @@ -9253,24 +9244,24 @@ "https://github.com/stablyai/orca/pull/7054" ], "invariant": "High-volume terminal output must stay bounded across daemon socket writes, SSH relay writer/decoder/source retention/reconnect, main model and projection admission, runtime metadata, detectors, and tail checks, main-to-renderer in-flight bytes, renderer scheduler queues, and hidden-output restore without starving focused input. Every new SSH session offers V1 and every same-build relay supports it; legacy delivery is reachable only when capability negotiation proves the peer cannot use V1. Negotiated SSH spans remain exact and contiguous through activation, exit, cancellation, recovery, desktop projection, and required remote replacement; provisional activation data cannot project, reconnect may release it only into the exact attempt's private recovery quarantine after contract validation, and exit seals that quarantine against later same-token frames until ordered admission or exact cancellation proof. Reconnect checkpoint capture freezes exact provider-generation/PTy admission, cancels queued old work, and waits for the running raw completion before exposing its accepted checkpoint; timeout or failure detaches only that PTy's old model, makes the checkpoint unavailable, and releases the bounded fence without closing the shared provider, while the same failure outside an active exact migration remains generation-fatal and overlapping reconnects preserve any earlier outstanding fence. Pending renderer projection IDs are capped and compacted across split remainders, exit preparation owns its renderer fence through finalization, exit-time cancellation transfers published projections before proof commit, generation close fences late proof while draining exact projection waiters, closed-generation identity compacts without weakening stale rejection, canceled source-delivery retirement retains at most one ordered token per PTY, and pause/resume targets only the exact provider generation. Additional subscribers cannot stall the owner, while the required legacy primary retains backpressure.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): 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/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): 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. Historical prior account (preserved verbatim): Audit1674 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: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", + "oracle": "Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): 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/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): 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. Historical prior account (preserved verbatim): Audit1674 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: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/protocol-backpressure.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/dispatcher.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer.test.ts src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts --reporter=dot" ], "testFiles": [ "src/main/runtime/construction/orca-runtime.test.ts", "src/wsl-guest/protocol-backpressure.test.ts", "src/wsl-guest/dispatcher.test.ts", - "src/main/ssh/ssh-multiplexer-transport-writer.test.ts", - "src/main/ssh/ssh-channel-multiplexer.test.ts", - "src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts", + "src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts", + "src/main/ssh/protocol/ssh-channel-multiplexer.test.ts", + "src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts", "src/wsl-guest/dispatcher-client-writer.test.ts", "src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts" ], @@ -9289,28 +9280,21 @@ ] }, { - "file": "src/main/ssh/ssh-multiplexer-transport-writer.test.ts", + "file": "src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts", "assertions": [ "write(false) owns one frame and later ordinary traffic waits for drain", "queued control is selected before ordinary PTY backlog at drain while each lane remains FIFO", "four-control fairness guarantees ordinary progress without starving control", - "one coalesced liveness bypass is allowed per saturated epoch", - "saturation and drain transitions are reported exactly once" + "one coalesced liveness bypass is allowed per saturated epoch" ] }, { - "file": "src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts", + "file": "src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts", "assertions": [ "source ACK, cancellation, exit, request, and response control frames precede queued pasted PTY input after drain", "control and ordinary frames preserve lane FIFO while ordinary input progresses after four control writes" ] }, - { - "file": "src/main/ssh/ssh-channel-multiplexer.test.ts", - "assertions": [ - "self-imposed writer saturation suppresses false death and rebases both health clocks on drain" - ] - }, { "file": "src/wsl-guest/dispatcher-client-writer.test.ts", "assertions": [ @@ -9335,32 +9319,23 @@ "result": "passed", "durationSeconds": 2.24, "summary": "Sixteen deterministic SSH relay/session/source/decoder files passed 192 tests, including exit-sealed private recovery, retained stale-transfer cancellation authority, exact private-frame proof watermarks, one retirement record across 10,000 same-PTY token rotations, stale-owner fallback, and scheduler rejection isolation; no live topology was exercised." - }, - { - "date": "2026-07-29", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot", - "result": "passed", - "durationSeconds": 6.89, - "summary": "Thirteen current-head deterministic files passed 150 tests across exit-sealed private recovery, stale-transfer cancellation authority, bounded latest-token retirement, restore retirement, fail-closed recovery cancellation, partial ACK and token rotation, reclaimed-span replacement, mux lane fairness, provisional activation, and exit-proof ordering; no live topology was exercised." } ], "runtimeBudget": { "p95Seconds": 120, - "scope": "deterministic provider/IPC contract now; terminal perf soak/report gate before promotion" + "scope": "Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): deterministic provider/IPC contract now; terminal perf soak/report gate before promotion" }, "flakeHistory": { "status": "unknown", - "evidence": "Focused main-process backlog and direct-SSH reconnect/memory/decoder tests are deterministic unit slices. On 2026-07-27 the source-credit reconnect case passed once in the full four-test Docker suite (15.7 seconds) and three consecutive isolated repeat-each runs (21.1, 19.8, and 15.3 seconds). On 2026-07-28 it passed against private recovery transfer in 17.7 seconds alone and 16.0 seconds in the full four-case suite; the combined perf soak still needs longer runtime history before promotion." + "evidence": "Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Focused main-process backlog and direct-SSH reconnect/memory/decoder tests are deterministic unit slices. On 2026-07-27 the source-credit reconnect case passed once in the full four-test Docker suite (15.7 seconds) and three consecutive isolated repeat-each runs (21.1, 19.8, and 15.3 seconds). On 2026-07-28 it passed against private recovery transfer in 17.7 seconds alone and 16.0 seconds in the full four-case suite; the combined perf soak still needs longer runtime history before promotion." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Tests assert ordinary saturated terminal tails retain no rebuilt wait text or repeated phrase scans while every blocked/ready prompt family remains live, main pending renderer output plus projection IDs stay within exact caps, direct-SSH source/recovery memory and both frame decoders stay within exact caps, and 50-PTY reconnect isolates slow/failing siblings. On pre-fix 4bf54da9b, reconnect pause targeted the replacement provider, disposal omitted a pause-only generation, normal and generation-close exit paths never released the renderer preparation lease, and the projection-cap seam did not exist; the same oracles pass with exact generation indexing, paused-generation enumeration, barrier-owned exit leases, and the 1,024-ID transfer latch. The deterministic main-to-relay drain oracle failed with ordinary-2 and ordinary-3 ahead of a later control frame under the single FIFO, then passed with control-first lane selection and four-write ordinary fairness. On exact pre-fix baseline db167ea3d with test-only oracles, cancellation proof reclaimed the published projection span before transfer and generation close allowed a late proof to publish final exit; both deterministic oracles pass after proof acquisition and commit are separated under the exact deadline barrier. Before snapshot admission, the trailing span entered transferring instead of remaining open; after retaining model-sequence ends and reserving at the serialized fence, the joined main/runtime oracle passed for renderer and headless sources with upstream boundaries 4 then 8. Before cumulative partial ACK and source rotation, the ledger rejected ACK 40 of 100 and the multiplex seam detached instead of publishing recovered token B; both exact oracles pass while stale stream and source generations remain rejected. Before restore-record retirement, invalid-checkpoint recovery followed by restore/retry returned restoreRequired a second time instead of opening a fresh activation; the same deterministic oracle passes after exact response-settlement cleanup. With test-only oracles on pre-fix 4bf54da9b, an existing-owner mismatch lacked the stale-owner code and both shared authority and main fallback rows failed; the candidate types that refusal while stale fresh admission remains a subscriber and the retained principal and lease can still recover. Before the recovery-quarantine activation fix, completion was visible at source unit 4 while lease-held recovery ended at 8, so the fence rejected and cancellation failed; the same byte-identical seam now transfers held ranges only into private quarantine, admits output after exact body/fence validation, and the deployed Linux relay reconnect passes. Other controls previously failed with serial reattach, UTF-8-only accounting, and roughly 32 MiB decoder retention. Needs daemon-stream contract coverage and broader hidden-output/input-latency perf artifacts before promotion." + "evidence": "Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Tests assert ordinary saturated terminal tails retain no rebuilt wait text or repeated phrase scans while every blocked/ready prompt family remains live, main pending renderer output plus projection IDs stay within exact caps, direct-SSH source/recovery memory and both frame decoders stay within exact caps, and 50-PTY reconnect isolates slow/failing siblings. On pre-fix 4bf54da9b, reconnect pause targeted the replacement provider, disposal omitted a pause-only generation, normal and generation-close exit paths never released the renderer preparation lease, and the projection-cap seam did not exist; the same oracles pass with exact generation indexing, paused-generation enumeration, barrier-owned exit leases, and the 1,024-ID transfer latch. The deterministic main-to-relay drain oracle failed with ordinary-2 and ordinary-3 ahead of a later control frame under the single FIFO, then passed with control-first lane selection and four-write ordinary fairness. On exact pre-fix baseline db167ea3d with test-only oracles, cancellation proof reclaimed the published projection span before transfer and generation close allowed a late proof to publish final exit; both deterministic oracles pass after proof acquisition and commit are separated under the exact deadline barrier. Before snapshot admission, the trailing span entered transferring instead of remaining open; after retaining model-sequence ends and reserving at the serialized fence, the joined main/runtime oracle passed for renderer and headless sources with upstream boundaries 4 then 8. Before cumulative partial ACK and source rotation, the ledger rejected ACK 40 of 100 and the multiplex seam detached instead of publishing recovered token B; both exact oracles pass while stale stream and source generations remain rejected. Before restore-record retirement, invalid-checkpoint recovery followed by restore/retry returned restoreRequired a second time instead of opening a fresh activation; the same deterministic oracle passes after exact response-settlement cleanup. With test-only oracles on pre-fix 4bf54da9b, an existing-owner mismatch lacked the stale-owner code and both shared authority and main fallback rows failed; the candidate types that refusal while stale fresh admission remains a subscriber and the retained principal and lease can still recover. Before the recovery-quarantine activation fix, completion was visible at source unit 4 while lease-held recovery ended at 8, so the fence rejected and cancellation failed; the same byte-identical seam now transfers held ranges only into private quarantine, admits output after exact body/fence validation, and the deployed Linux relay reconnect passes. Other controls previously failed with serial reattach, UTF-8-only accounting, and roughly 32 MiB decoder retention. Needs daemon-stream contract coverage and broader hidden-output/input-latency perf artifacts before promotion." }, "performanceBudget": { "required": true, - "evidence": "Suggested ceilings: renderer in-flight <=8MB total, <=512KB per PTY plus active reserve, renderer queued chars <=2MB, dropped backlogs 0, hidden restore <=1000ms, active key median/worst <=75ms/300ms in perf scenarios. Always-on capability offers add no persisted setting reads, polling, scans, subprocesses, provider fanout, or reconnect-path reevaluation. Restore-record retirement adds one exact map-identity check at response settlement with no polling, timers, scans, subprocesses, or provider calls. The Docker SSH gate enforces median/worst typing below 500/2,000 ms; the current private-transfer artifact observed 5.5/16.3 ms during an exact 256 KiB stalled-credit plateau, 141.2/151.5 ms during 95 completed filesystem/Git bulk reads, and a 16.0-second reconnect. With 1,024 retained provenance candidates, 4,096 pathless chunks dropped from 78.84ms and 4,096 array replacements to 1.74ms and zero replacements. Brace-free 1 KiB output dropped from 20.32/79.12/318.23ms to 0.31/0.64/2.35ms across 4,096/16,384/65,536 chunks. Repeated ordinary 252,000-character tail checks dropped from 96.34/464.20/941.79/3,796.70ms to 3.21/15.68/31.34/129.72ms across 100/500/1,000/4,096 updates." + "evidence": "Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Suggested ceilings: renderer in-flight <=8MB total, <=512KB per PTY plus active reserve, renderer queued chars <=2MB, dropped backlogs 0, hidden restore <=1000ms, active key median/worst <=75ms/300ms in perf scenarios. Always-on capability offers add no persisted setting reads, polling, scans, subprocesses, provider fanout, or reconnect-path reevaluation. Restore-record retirement adds one exact map-identity check at response settlement with no polling, timers, scans, subprocesses, or provider calls. The Docker SSH gate enforces median/worst typing below 500/2,000 ms; the current private-transfer artifact observed 5.5/16.3 ms during an exact 256 KiB stalled-credit plateau, 141.2/151.5 ms during 95 completed filesystem/Git bulk reads, and a 16.0-second reconnect. With 1,024 retained provenance candidates, 4,096 pathless chunks dropped from 78.84ms and 4,096 array replacements to 1.74ms and zero replacements. Brace-free 1 KiB output dropped from 20.32/79.12/318.23ms to 0.31/0.64/2.35ms across 4,096/16,384/65,536 chunks. Repeated ordinary 252,000-character tail checks dropped from 96.34/464.20/941.79/3,796.70ms to 3.21/15.68/31.34/129.72ms across 100/500/1,000/4,096 updates." }, "promotionCriteria": [ "Split daemon stream backpressure into a deterministic provider/IPC contract if full E2E is flaky.", @@ -9405,7 +9380,12 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed.", + "Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope.", + "Historical original SSH assertion metadata before policy cuts, preserved verbatim; removed assertions are not current coverage:\n{\n \"file\": \"src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts\",\n \"assertions\": [\n \"write(false) owns one frame and later ordinary traffic waits for drain\",\n \"queued control is selected before ordinary PTY backlog at drain while each lane remains FIFO\",\n \"four-control fairness guarantees ordinary progress without starving control\",\n \"one coalesced liveness bypass is allowed per saturated epoch\",\n \"saturation and drain transitions are reported exactly once\"\n ]\n }\n{\n \"file\": \"src/main/ssh/protocol/ssh-channel-multiplexer.test.ts\",\n \"assertions\": [\n \"self-imposed writer saturation suppresses false death and rebases both health clocks on drain\"\n ]\n }", + "Historical complete dated writer/backpressure receipt retired after its source changed, preserved verbatim including executed command and path-only currentCommand; not current validation:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot\",\n \"result\": \"passed\",\n \"durationSeconds\": 6.89,\n \"summary\": \"Thirteen current-head deterministic files passed 150 tests across exit-sealed private recovery, stale-transfer cancellation authority, bounded latest-token retirement, restore retirement, fail-closed recovery cancellation, partial ACK and token rotation, reclaimed-span replacement, mux lane fairness, provisional activation, and exit-proof ordering; no live topology was exercised.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot\"\n }", + "Historical provider scope before changed-source receipt retirement: [\"ssh\"]" ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -12835,14 +12815,14 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): 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.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): 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": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): 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.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): 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/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/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", @@ -13258,7 +13238,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector 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." }, @@ -14502,10 +14483,10 @@ "providers": ["paired-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": ["paired-runtime"], - "coverageNotes": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", + "coverageNotes": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34069063016"], "invariant": "A paired client and host without client-hosted browser capabilities retain server-hosted browser placement across supported version skew.", - "oracle": "Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", + "oracle": "Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", "commands": [ "gh workflow run packaged-browser-e2e.yml", "pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0", @@ -14569,7 +14550,8 @@ "Audit2404 removes whole skill-share-package-name.test.ts, skill-delete-plan original1/6 skill-delete-recovery original2 and skill-share-preparation original2. Lose lookup503 rejection/status propagation through prepare, explicit unblocked unordered alias-kind/canonical sample with cwd undefined, stale classification after +60000ms actual mtime change, successful first-pass single-move rollback/staged-path absence and prior-process preparation-root archive directory cleanup. Retained exact identities use cwd home; public stale guard submits timestamp1; recovery retry cases are not identical first-pass fixtures. No equivalent complete replacement or fresh validation is claimed.", "Audit2412 removes whole useVirtualizedScrollAnchor.marks-restore-signal.test.ts (six fake-hook geometry/mark/convergence/user-takeover/clamp alarms), use-task-creation-draft-retention original3/4 (immediate discard mock-call count/unopened no-write), use-terminal-bulk-close-actions.placement original6/7 (absent new-agent append and one real history-publication count at consumed3/30 scale), PendingNativeChatCreation original6 (unmounted abort completion/timer cleanup), and wsl-move-dialog-store original1/9/13 (default whole-distro count/reference/reuse and rejected-preview/start refusal recovery). The history counter measures genuine publication work without entries/order/reopen assertions; its unique batching alarm is intentionally retired. Fake React scroll tests ignore dependency scheduling and cleanup; unique simulated arithmetic alarms are deliberately lost. Retained existing-terminal reorder is not new-agent append coverage; mounted handoff timeout is not abort coverage. No equivalent complete replacement or fresh validation is claimed.", "Audit2417 removes commit-actions-real-git original3/4 (ordinary clean cherry-pick and revert content, subject and current-branch samples), and pty-startup-ingress-exited-asker original8/12 (actual foreground-group read budget across100queued queries, and zero foreground reads across100normal chunks plus final emitted/accepted raw cursor equality). Counters measure actual callback work and scale is consumed; these internal-work alarms are deliberately retired. Retained unborn, conflict and sequencer cases are not equivalent ordinary-success coverage. No equivalent complete replacement or fresh validation is claimed.", - "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed." + "Audit2425 removes use-workspace-copy-status original5, which returns a fixture-supplied readError string through statusReadError. No consumer blocker or attempted branch switch established refusal; the unique error-forwarding sample is intentionally retired. Other copy ownership and stale-refresh cases are not equivalent error-path coverage. No equivalent replacement or fresh validation is claimed.", + "Audit2432 removes BranchPicker.test.tsx original3, which only asserted onOpenChange(true/false) with an always-mounted mocked Popover. It never reopened the picker or consumed the callback in the parent status-refresh owner, despite its title. Lose that unique open/close notification alarm. Retained blocker/collision recovery and asynchronous post-unmount outcome cases are not equivalent replacement coverage. No fresh validation of the reduced selector is claimed." ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 534366bae1e..3e115b3f7cd 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -4140,8 +4140,8 @@ "src/main/sqlite/sync-database-concurrent-backup.test.ts": 1141, "src/main/sqlite/sync-database-portability.test.ts": 147, "src/main/sqlite/sync-database.test.ts": 860, - "src/main/ssh/connection/ssh-expired-lease-pane-readoption.test.ts": 2799, - "src/main/ssh/connection/ssh-reattach-pane-cardinality.test.ts": 1778, + "src/main/ipc/pty/pane/ssh-expired-lease-pane-readoption.test.ts": 2799, + "src/main/persistence/loading-store/ssh-reattach-pane-cardinality.test.ts": 1778, "src/main/ssh/config/ssh-config-alias-claim.test.ts": 58, "src/main/ssh/config/ssh-config-host-picker.test.ts": 221, "src/main/ssh/config/ssh-config-loader-regression.test.ts": 102, @@ -4149,19 +4149,18 @@ "src/main/ssh/config/ssh-config-parser-host-patterns.test.ts": 50, "src/main/ssh/config/ssh-config-parser.test.ts": 315, "src/main/ssh/config/ssh-g-config-resolution.test.ts": 125, - "src/main/ssh/config/ssh-known-hosts-source.test.ts": 124, - "src/main/ssh/config/ssh-known-hosts.test.ts": 105, - "src/main/ssh/config/zed-ssh-url.test.ts": 55, + "src/main/ssh/host-keys/ssh-known-hosts-source.test.ts": 124, + "src/main/ssh/host-keys/ssh-known-hosts.test.ts": 105, + "src/main/ssh/external-editors/zed-ssh-url.test.ts": 55, "src/main/ssh/connection/ssh-connect-config.test.ts": 182, "src/main/ssh/connection/ssh-connection-attribution.test.ts": 44, "src/main/ssh/connection/ssh-connection-auth-fallback.test.ts": 512, "src/main/ssh/connection/ssh-connection-channel-error.test.ts": 461, - "src/main/ssh/connection/ssh-connection-channel-lifetime.test.ts": 61, "src/main/ssh/connection/ssh-connection-channel-open.test.ts": 1230, "src/main/ssh/connection/ssh-connection-direct-startup.test.ts": 350, - "src/main/ssh/connection/ssh-connection-file-transfer-session-lost.test.ts": 5247, + "src/main/ssh/file-transfer/ssh-connection-file-transfer-session-lost.test.ts": 5247, "src/main/ssh/connection/ssh-connection-file-transfer.test.ts": 335, - "src/main/ssh/connection/ssh-connection-generation.test.ts": 53, + "src/main/ssh/connection/authority/ssh-connection-generation.test.ts": 53, "src/main/ssh/connection/ssh-connection-gssapi-fallback.test.ts": 420, "src/main/ssh/connection/ssh-connection-host-key-pin-race.test.ts": 462, "src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts": 776, @@ -4174,143 +4173,130 @@ "src/main/ssh/connection/ssh-connection-reconnect-ladder.test.ts": 570, "src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts": 1290, "src/main/ssh/connection/ssh-connection-sftp-wire.test.ts": 481, - "src/main/ssh/connection/ssh-connection-store-orcad-ownership.test.ts": 324, - "src/main/ssh/connection/ssh-connection-store-route-dedupe.test.ts": 350, - "src/main/ssh/connection/ssh-connection-store.test.ts": 377, + "src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts": 324, + "src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts": 350, + "src/main/ssh/targets/ssh-connection-store.test.ts": 377, "src/main/ssh/connection/ssh-connection-system-transport.test.ts": 458, "src/main/ssh/connection/ssh-connection-wake-retry.test.ts": 478, "src/main/ssh/connection/ssh-connection.test.ts": 1570, "src/main/ssh/hostile-host-test-support/ssh-hostile-hosts.docker.test.ts": 602, - "src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts": 98, - "src/main/ssh/legacy-relay/legacy-relay-bridge-restart-stop.test.ts": 3114, - "src/main/ssh/legacy-relay/legacy-relay-bridge-runtime-exit.test.ts": 3411, - "src/main/ssh/legacy-relay/legacy-relay-bridge-timers.test.ts": 41, - "src/main/ssh/legacy-relay/legacy-relay-cli-call-limits.test.ts": 7977, - "src/main/ssh/legacy-relay/legacy-relay-cli-legacy-records.test.ts": 6234, - "src/main/ssh/legacy-relay/legacy-relay-cli-output.test.ts": 150, - "src/main/ssh/legacy-relay/legacy-relay-cli-server.test.ts": 9385, - "src/main/ssh/legacy-relay/legacy-relay-client.test.ts": 109, - "src/main/ssh/legacy-relay/legacy-relay-hidden-output.test.ts": 179, - "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-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, - "src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts": 1546, - "src/main/ssh/legacy-relay/ssh-relay-endpoint-runtime.test.ts": 49, - "src/main/ssh/legacy-relay/ssh-relay-incumbent-process.test.ts": 5357, - "src/main/ssh/legacy-relay/ssh-relay-sentinel-copy-budget.test.ts": 74, - "src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts": 392, - "src/main/ssh/managed-server-fence-recheck.test.ts": 436, - "src/main/ssh/managed-server-update-check.test.ts": 316, - "src/main/ssh/managed-server-update-deps.test.ts": 319, - "src/main/ssh/orcad-bash-stdio-bridge.test.ts": 4062, - "src/main/ssh/orcad-exited-own-fence-mutation-race.test.ts": 839, - "src/main/ssh/orcad-exited-own-fence.test.ts": 6057, - "src/main/ssh/orcad-exited-own-install-lock.test.ts": 382, - "src/main/ssh/orcad-exited-own-lock-windows.test.ts": 320, - "src/main/ssh/orcad-fence-lost-classification.test.ts": 227, - "src/main/ssh/orcad-fenced-stop.test.ts": 99, - "src/main/ssh/orcad-launch-ssh-session.test.ts": 689, - "src/main/ssh/orcad-migration-blob-coordinator.test.ts": 1464, - "src/main/ssh/orcad-migration-catalog-client-frame-budget.test.ts": 405, - "src/main/ssh/orcad-migration-catalog-client-source-kind.test.ts": 400, - "src/main/ssh/orcad-migration-catalog-client.test.ts": 400, - "src/main/ssh/orcad-migration-cutover-coordinator.test.ts": 2408, - "src/main/ssh/orcad-migration-cutover-journal.test.ts": 369, - "src/main/ssh/orcad-migration-delta-move.test.ts": 3812, - "src/main/ssh/orcad-migration-delta-snapshot.test.ts": 2611, - "src/main/ssh/orcad-migration-manifest-export.test.ts": 613, - "src/main/ssh/orcad-migration-repository-link.test.ts": 4281, - "src/main/ssh/orcad-migration-snapshot-coordinator.test.ts": 309, - "src/main/ssh/orcad-migration-snapshot-resume.test.ts": 1878, - "src/main/ssh/orcad-migration-source-fence.test.ts": 2000, - "src/main/ssh/orcad-migration-source-retention.test.ts": 2297, - "src/main/ssh/orcad-migration-ssh-relay-source.test.ts": 1903, - "src/main/ssh/orcad-migration-stuck-host-profiles.test.ts": 2402, - "src/main/ssh/orcad-migration-terminal-gate-host-wide.test.ts": 261, - "src/main/ssh/orcad-migration-terminal-gate.test.ts": 63, - "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-runtime-maintenance.test.ts": 916, - "src/main/ssh/orcad-snapshot-room.test.ts": 402, - "src/main/ssh/orcad-stdio-bridge.test.ts": 627, - "src/main/ssh/orcad-terminal-census-client.test.ts": 217, - "src/main/ssh/orcad-tunneled-pairing.test.ts": 94, - "src/main/ssh/orcad-unreachable-setup-release.test.ts": 2336, - "src/main/ssh/pinned-runtime-host-target.test.ts": 45, + "src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-relay-restart.test.ts": 98, + "src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-restart-stop.test.ts": 3114, + "src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-runtime-exit.test.ts": 3411, + + "src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.test.ts": 7977, + "src/main/ssh/legacy-relay/cli/legacy-relay-cli-legacy-records.test.ts": 6234, + + "src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts": 9385, + "src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts": 109, + "src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts": 179, + "src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts": 167, + "src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts": 322, + "src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.test.ts": 53, + "src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts": 232, + "src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts": 178, + "src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-pipe-access.test.ts": 211, + "src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts": 1546, + "src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts": 49, + "src/main/ssh/legacy-relay/endpoints/ssh-relay-incumbent-process.test.ts": 5357, + "src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts": 74, + "src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts": 392, + "src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts": 4062, + "src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts": 839, + "src/main/managed-server/activation/orcad-exited-own-fence.test.ts": 6057, + "src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts": 382, + "src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts": 320, + "src/main/managed-server/host-state/orcad-fence-lost-classification.test.ts": 227, + "src/main/managed-server/activation/orcad-fenced-stop.test.ts": 99, + "src/main/managed-server/install/orcad-launch-ssh-session.test.ts": 689, + "src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.test.ts": 1464, + "src/main/managed-server/migration/catalog/orcad-migration-catalog-client-frame-budget.test.ts": 405, + "src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts": 400, + "src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts": 400, + "src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.test.ts": 2408, + "src/main/persistence/migrating-orcad-catalog/orcad-migration-cutover-journal.test.ts": 369, + "src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts": 3812, + "src/main/managed-server/migration/cutover/orcad-migration-delta-snapshot.test.ts": 2611, + "src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts": 4281, + "src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.test.ts": 309, + "src/main/ssh/migration-source/orcad-migration-source-fence.test.ts": 2000, + "src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.test.ts": 2297, + "src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts": 1903, + "src/main/managed-server/migration/cutover/orcad-migration-stuck-host-profiles.test.ts": 2402, + "src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts": 63, + "src/main/managed-server/install/orcad-remote-deploy.test.ts": 537, + "src/main/managed-server/activation/orcad-retained-fence-takeover.test.ts": 210, + "src/main/persistence/migrating-orcad-catalog/orcad-retained-source-changes.test.ts": 2185, + "src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts": 916, + "src/main/managed-server/host-state/orcad-snapshot-room.test.ts": 402, + "src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts": 627, + "src/main/managed-server/lifecycle/orcad-terminal-census-client.test.ts": 217, + "src/main/managed-server/lifecycle/orcad-tunneled-pairing.test.ts": 94, + "src/main/managed-server/migration/cutover/orcad-unreachable-setup-release.test.ts": 2336, + "src/main/managed-server/install/pinned-runtime-host-target.test.ts": 45, "src/main/ssh/plain-ssh-terminal/plain-ssh-terminal-args.test.ts": 49, "src/main/ssh/plain-ssh-terminal/plain-ssh-terminal-sessions.test.ts": 272, "src/main/ssh/port-forwarding/ssh-port-forward.test.ts": 235, "src/main/ssh/port-forwarding/ssh2-port-forward-listen.test.ts": 44, "src/main/ssh/remote-exec/remote-exec-command.test.ts": 84, "src/main/ssh/remote-exec/remote-exec-input.test.ts": 71, - "src/main/ssh/remote-exec/remote-frame-protocol.test.ts": 126, - "src/main/ssh/remote-exec/remote-host-failure-producers.test.ts": 356, - "src/main/ssh/runtime-ssh-access.test.ts": 739, - "src/main/ssh/sftp-stream-late-error.test.ts": 209, - "src/main/ssh/sftp-upload-pipeline.test.ts": 480, - "src/main/ssh/sftp-upload.test.ts": 533, - "src/main/ssh/ssh-agent-identity-filter.test.ts": 54, - "src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts": 102, - "src/main/ssh/ssh-channel-multiplexer-saturation-wedge.test.ts": 60, - "src/main/ssh/ssh-channel-multiplexer-settlement.test.ts": 56, - "src/main/ssh/ssh-channel-multiplexer.test.ts": 120, - "src/main/ssh/ssh-connect-attempt-cancellation.test.ts": 45, - "src/main/ssh/ssh-control-socket.test.ts": 55, - "src/main/ssh/ssh-credential-decline.test.ts": 115, - "src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts": 6570, - "src/main/ssh/ssh-exec-command-decoder-fallback.test.ts": 290, - "src/main/ssh/ssh-exec-rc-stdout-noise.test.ts": 262, - "src/main/ssh/ssh-exec-stdin-file-transfer.test.ts": 324, - "src/main/ssh/ssh-file-transfer-abort.test.ts": 51, - "src/main/ssh/ssh-host-key-store.test.ts": 238, - "src/main/ssh/ssh-host-key-verifier.test.ts": 97, - "src/main/ssh/ssh-host-platform-memo.test.ts": 38, - "src/main/ssh/ssh-host-proxy-environment.test.ts": 170, - "src/main/ssh/ssh-host-server-on-connect-held-move.test.ts": 510, - "src/main/ssh/ssh-host-server-on-connect-node-download.test.ts": 455, - "src/main/ssh/ssh-host-server-on-connect-stopped-elsewhere.test.ts": 55, - "src/main/ssh/ssh-host-server-on-connect-telemetry.test.ts": 440, - "src/main/ssh/ssh-host-server-on-connect.test.ts": 536, - "src/main/ssh/ssh-host-server-telemetry.test.ts": 194, - "src/main/ssh/ssh-identity-file-read.test.ts": 111, - "src/main/ssh/ssh-keyboard-interactive-wire.test.ts": 471, - "src/main/ssh/ssh-keyboard-interactive.test.ts": 54, - "src/main/ssh/ssh-multi-factor-authentication.test.ts": 269, - "src/main/ssh/ssh-multi-key-authentication.test.ts": 160, - "src/main/ssh/ssh-multiplexer-transport-writer.test.ts": 66, - "src/main/ssh/ssh-multiplexer-writer-retention.test.ts": 561, - "src/main/ssh/ssh-posix-command-wrapper.test.ts": 238, - "src/main/ssh/ssh-proxy-command.test.ts": 83, - "src/main/ssh/ssh-quit-abort-upload.test.ts": 268, - "src/main/ssh/ssh-remote-commands.test.ts": 9359, - "src/main/ssh/ssh-remote-directory-browse.test.ts": 175, - "src/main/ssh/ssh-remote-node-resolution.test.ts": 283, - "src/main/ssh/ssh-remote-platform-detection.test.ts": 177, - "src/main/ssh/ssh-remote-platform.test.ts": 51, - "src/main/ssh/ssh-remote-windows-command-line-limit.test.ts": 164, - "src/main/ssh/ssh-security-key-identity.test.ts": 142, - "src/main/ssh/ssh-system-transport.integration.test.ts": 401, - "src/main/ssh/ssh-tcp-forwarding-probe.test.ts": 971, - "src/main/ssh/ssh2-module-load.test.ts": 271, + "src/main/ssh/protocol/remote-frame-protocol.test.ts": 126, + "src/main/ssh/system-transport/remote-host-failure-producers.test.ts": 356, + "src/main/ssh/runtime-access/runtime-ssh-access.test.ts": 739, + "src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts": 209, + "src/main/ssh/file-transfer/sftp/sftp-upload-pipeline.test.ts": 480, + "src/main/ssh/file-transfer/sftp/sftp-upload.test.ts": 533, + "src/main/ssh/authentication/ssh-agent-identity-filter.test.ts": 54, + "src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts": 102, + "src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts": 60, + "src/main/ssh/protocol/ssh-channel-multiplexer-settlement.test.ts": 56, + "src/main/ssh/protocol/ssh-channel-multiplexer.test.ts": 120, + "src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts": 45, + "src/main/ssh/system-transport/ssh-control-socket.test.ts": 55, + "src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts": 290, + "src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts": 262, + "src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts": 324, + "src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts": 51, + "src/main/ssh/host-keys/ssh-host-key-store.test.ts": 238, + "src/main/ssh/host-keys/ssh-host-key-verifier.test.ts": 97, + "src/main/ssh/remote-host/ssh-host-proxy-environment.test.ts": 170, + "src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts": 510, + "src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts": 455, + "src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts": 55, + "src/main/ssh/host-server/ssh-host-server-on-connect-telemetry.test.ts": 440, + "src/main/ssh/host-server/ssh-host-server-on-connect.test.ts": 536, + "src/main/ssh/host-server/ssh-host-server-telemetry.test.ts": 194, + "src/main/ssh/authentication/ssh-identity-file-read.test.ts": 111, + "src/main/ssh/authentication/ssh-keyboard-interactive.test.ts": 54, + "src/main/ssh/authentication/ssh-multi-factor-authentication.test.ts": 269, + "src/main/ssh/authentication/ssh-multi-key-authentication.test.ts": 160, + "src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts": 66, + "src/main/ssh/protocol/ssh-multiplexer-writer-retention.test.ts": 561, + "src/main/ssh/remote-exec/ssh-posix-command-wrapper.test.ts": 238, + "src/main/ssh/system-transport/ssh-proxy-command.test.ts": 83, + "src/main/ssh/remote-exec/ssh-remote-commands.test.ts": 9359, + "src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts": 175, + "src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.test.ts": 283, + "src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts": 177, + "src/main/ssh/remote-host/ssh-remote-platform.test.ts": 51, + "src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts": 164, + "src/main/ssh/authentication/ssh-security-key-identity.test.ts": 142, + "src/main/ssh/system-transport/ssh-system-transport.integration.test.ts": 401, + "src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts": 971, "src/main/ssh/system-transport/system-ssh-binary.test.ts": 53, - "src/main/ssh/system-transport/system-ssh-dynamic-forward-process.test.ts": 120, - "src/main/ssh/system-transport/system-ssh-forward-port-reservation.test.ts": 51, - "src/main/ssh/system-transport/system-ssh-forward-process-real-openssh.test.ts": 106, - "src/main/ssh/system-transport/system-ssh-forward-process.test.ts": 147, - "src/main/ssh/system-transport/system-ssh-loopback-route-admission.test.ts": 225, - "src/main/ssh/system-transport/system-ssh-loopback-route.test.ts": 622, - "src/main/ssh/system-transport/system-ssh-muxed-forward-cancel.test.ts": 61, + "src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts": 120, + "src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts": 51, + "src/main/ssh/system-transport/forwarding/system-ssh-forward-process-real-openssh.test.ts": 106, + "src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts": 147, + "src/main/ssh/system-transport/forwarding/system-ssh-loopback-route-admission.test.ts": 225, + "src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.test.ts": 622, + "src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts": 61, "src/main/ssh/system-transport/system-ssh-operations.test.ts": 197, - "src/main/ssh/system-transport/system-ssh-orphaned-forward.test.ts": 114, - "src/main/ssh/system-transport/system-ssh-sftp-args.test.ts": 52, - "src/main/ssh/system-transport/system-ssh-sftp-path.test.ts": 52, - "src/main/ssh/system-transport/system-ssh-upload-plan-budget.test.ts": 348, - "src/main/ssh/system-transport/system-ssh-windows-upload.test.ts": 288, - "src/main/ssh/system-transport/system-ssh-windows-write-capabilities.test.ts": 43, + "src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.test.ts": 114, + "src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts": 52, + "src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts": 52, + "src/main/ssh/system-transport/file-transfer/system-ssh-upload-plan-budget.test.ts": 348, + "src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts": 288, "src/main/ssh/targets/ssh-target-id-migration.test.ts": 50, "src/main/ssh/targets/ssh-target-identity.test.ts": 43, "src/main/ssh/targets/ssh-target-orcad-claims.test.ts": 265, @@ -6355,10 +6341,8 @@ "src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts": 3310, "src/renderer/src/hooks/useIpcEvents-browser-certificate-failure.test.ts": 2981, "src/renderer/src/hooks/useIpcEvents-browser-navigation.test.ts": 1511, - "src/renderer/src/hooks/useIpcEvents-cli-worktree-activation.test.ts": 2096, "src/renderer/src/hooks/useIpcEvents-client-hosted-browser-rows.test.ts": 1894, "src/renderer/src/hooks/useIpcEvents-close-routing-active-browser-tab.test.ts": 4572, - "src/renderer/src/hooks/useIpcEvents-close-routing-browser-pages.test.ts": 2554, "src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts": 5812, "src/renderer/src/hooks/useIpcEvents-cmd-j-digit-chord.test.ts": 2703, "src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts": 2326, @@ -6366,7 +6350,6 @@ "src/renderer/src/hooks/useIpcEvents-rate-limit-hydration.test.ts": 1597, "src/renderer/src/hooks/useIpcEvents-runtime-environment-selectors.test.ts": 530, "src/renderer/src/hooks/useIpcEvents-session-tab-close-request.test.ts": 2252, - "src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts": 1581, "src/renderer/src/hooks/useIssueMetadata.test.tsx": 344, "src/renderer/src/hooks/useMacTccAttributionSeveredNotice.test.tsx": 2358, "src/renderer/src/hooks/useMetadataListRequest.test.tsx": 266, diff --git a/config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs b/config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs index 1d3841e74ae..deb2a308bef 100644 --- a/config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs +++ b/config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs @@ -1,11 +1,11 @@ import { spawnSync } from 'node:child_process' const defaultFiles = [ - 'src/main/ssh/sftp-upload.test.ts', - 'src/main/ssh/ssh-file-transfer-abort.test.ts', + 'src/main/ssh/file-transfer/sftp/sftp-upload.test.ts', + 'src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts', 'src/main/ssh/ssh-relay-install-namespace.test.ts', 'src/main/ssh/connection/ssh-connection-sftp-wire.test.ts', - 'src/main/ssh/ssh-remote-commands.test.ts' + 'src/main/ssh/remote-exec/ssh-remote-commands.test.ts' ] const cliArguments = process.argv.slice(2) diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 4b5f8c32d46..ab708cb3808 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -7,8 +7,8 @@ const NODE_RUNTIME_INCLUDE = [ 'tests/e2e/linear-cli-recovery.unit.test.ts', 'src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts', 'config/scripts/ci/workflow-contracts/cloud-security-history-workflow.test.mjs', - 'src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts', - 'src/main/ssh/ssh-remote-commands.test.ts', + 'src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts', + 'src/main/ssh/remote-exec/ssh-remote-commands.test.ts', 'src/packages/process-host/src/run-process.test.ts', 'tests/e2e/cursor-quota-transport.unit.test.ts', 'tests/e2e/helpers/electron-process-shutdown.unit.test.ts', diff --git a/config/unproven-pty-retirement-baseline.txt b/config/unproven-pty-retirement-baseline.txt index 77ae1a16021..692e6577be6 100644 --- a/config/unproven-pty-retirement-baseline.txt +++ b/config/unproven-pty-retirement-baseline.txt @@ -10,4 +10,4 @@ 1 src/main/ipc/pty/provider/ownership-state.ts # deletePtyOwnership, test-only caller 1 src/main/ipc/pty/provider/state-cleanup.ts # clearPtyOwnershipForConnection, test-only caller 3 src/main/ipc/pty/runtime/kill.ts # 2x SSH provider unregistered (R4-4); unconfirmed follow-up stop of a rejected spawn -1 src/main/ssh/legacy-relay/legacy-relay-pane-stops.ts # COMPAT(legacy-relay-bridge): deleted with the folder +1 src/main/ssh/legacy-relay/bridge/legacy-relay-pane-stops.ts # COMPAT(legacy-relay-bridge): deleted with the folder diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 23daba961e0..673eb8847e7 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -32,6 +32,7 @@ const BUNDLED_MAIN_DEPENDENCIES = new Set([ 'unified', 'remark-parse', 'remark-gfm', + 'hast-util-from-html-isomorphic', // Windows NSIS copies app.asar before external resources; bootstrap must not race resources/node_modules. 'zod' ]) diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json index b7969499141..1a61e065e8a 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.branchcompare-1.json @@ -252,6 +252,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "4533fb49ac71": { "branchCompareState": { "kind": "error", @@ -342,38 +374,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6a0cb0684d8b": { "name": "git.branchCompare#1", "ordinal": 10, @@ -592,32 +592,6 @@ } } }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -823,6 +797,32 @@ } } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "bd638c43a536": { "name": "git.branchCompare#1", "ordinal": 10, @@ -933,11 +933,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -946,6 +941,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "fa79ca4a1a0d": { "name": "git.branchCompare#1", "ordinal": 10, @@ -1052,8 +1052,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1064,9 +1064,9 @@ { "id": "sc-changes-loaded.prelude:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1083,14 +1083,14 @@ "id": "sc-changes-loaded.prelude:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "b7127d77e6aa" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1108,14 +1108,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1133,14 +1133,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1158,14 +1158,14 @@ "id": "sc-changes-loaded.result-absent:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "fa79ca4a1a0d" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1183,14 +1183,14 @@ "id": "sc-changes-loaded.result-absent:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "fa79ca4a1a0d" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1208,14 +1208,14 @@ "id": "sc-changes-loaded.result-null:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "86eb3bc4e90c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1233,14 +1233,14 @@ "id": "sc-changes-loaded.result-null:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "86eb3bc4e90c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1258,14 +1258,14 @@ "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "dc48d55bec67" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1283,14 +1283,14 @@ "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "dc48d55bec67" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1308,14 +1308,14 @@ "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "bd638c43a536" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1333,14 +1333,14 @@ "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "bd638c43a536" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1358,14 +1358,14 @@ "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "047f0b230543" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1383,14 +1383,14 @@ "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "047f0b230543" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1408,14 +1408,14 @@ "id": "sc-changes-loaded.outer-refused:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "97a020d83f3c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1433,14 +1433,14 @@ "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "97a020d83f3c" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1458,14 +1458,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "6a0cb0684d8b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1483,14 +1483,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "6a0cb0684d8b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1508,14 +1508,14 @@ "id": "sc-changes-loaded.method-not-found:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "7506958819b1" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1533,14 +1533,14 @@ "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "7506958819b1" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1558,14 +1558,14 @@ "id": "sc-changes-loaded.transport-rejection:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "fdcce09eef21" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1583,14 +1583,14 @@ "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "fdcce09eef21" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1608,14 +1608,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "2cca3e7f3f9b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1633,14 +1633,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "2cca3e7f3f9b" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json index 8944f49a991..bf13a7571d4 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-git.status-1.json @@ -379,6 +379,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "393d2f9f3485": { "name": "git.status#1", "ordinal": 3, @@ -484,38 +516,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6d2d788a9e84": { "name": "git.status#1", "ordinal": 3, @@ -629,32 +629,6 @@ } ] }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -866,6 +840,32 @@ } ] }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "cb462f8b50a3": { "name": "worktree.show#1", "ordinal": 8, @@ -882,11 +882,6 @@ } ] }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -895,6 +890,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f0896523e780": { "name": "git.status#2", "ordinal": 6, @@ -959,8 +959,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -971,8 +971,8 @@ { "id": "sc-changes-loaded.prelude:cleanup", "observation": { - "sender": ["63bc0796d81c", "1dbb1f085bde"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "1dbb1f085bde"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -983,9 +983,9 @@ { "id": "sc-changes-loaded.normal:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1002,14 +1002,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1027,14 +1027,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1051,8 +1051,8 @@ { "id": "sc-changes-loaded.result-absent:compare-pending", "observation": { - "sender": ["891438a18444", "f186683ccf2d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "f186683ccf2d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1063,8 +1063,8 @@ { "id": "sc-changes-loaded.result-absent:settled", "observation": { - "sender": ["891438a18444", "f186683ccf2d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "f186683ccf2d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1075,8 +1075,8 @@ { "id": "sc-changes-loaded.result-absent:cleanup", "observation": { - "sender": ["63bc0796d81c", "f186683ccf2d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "f186683ccf2d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1087,8 +1087,8 @@ { "id": "sc-changes-loaded.result-null:compare-pending", "observation": { - "sender": ["891438a18444", "9ae4367a6ff8"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "9ae4367a6ff8"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1099,8 +1099,8 @@ { "id": "sc-changes-loaded.result-null:settled", "observation": { - "sender": ["891438a18444", "9ae4367a6ff8"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "9ae4367a6ff8"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1111,8 +1111,8 @@ { "id": "sc-changes-loaded.result-null:cleanup", "observation": { - "sender": ["63bc0796d81c", "9ae4367a6ff8"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "9ae4367a6ff8"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1123,8 +1123,8 @@ { "id": "sc-changes-loaded.inner-ok-missing:compare-pending", "observation": { - "sender": ["891438a18444", "19fff093880d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "19fff093880d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1135,8 +1135,8 @@ { "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { - "sender": ["891438a18444", "19fff093880d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "19fff093880d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1147,8 +1147,8 @@ { "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { - "sender": ["63bc0796d81c", "19fff093880d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "19fff093880d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1159,8 +1159,8 @@ { "id": "sc-changes-loaded.inner-false-string-error:compare-pending", "observation": { - "sender": ["891438a18444", "393d2f9f3485"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "393d2f9f3485"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1171,8 +1171,8 @@ { "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { - "sender": ["891438a18444", "393d2f9f3485"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "393d2f9f3485"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1183,8 +1183,8 @@ { "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { - "sender": ["63bc0796d81c", "393d2f9f3485"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "393d2f9f3485"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1195,8 +1195,8 @@ { "id": "sc-changes-loaded.inner-false-object-error:compare-pending", "observation": { - "sender": ["891438a18444", "1940948b426c"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "1940948b426c"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1207,8 +1207,8 @@ { "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { - "sender": ["891438a18444", "1940948b426c"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "1940948b426c"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1219,8 +1219,8 @@ { "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { - "sender": ["63bc0796d81c", "1940948b426c"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "1940948b426c"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1231,8 +1231,8 @@ { "id": "sc-changes-loaded.outer-refused:compare-pending", "observation": { - "sender": ["891438a18444", "085b756c7623"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "085b756c7623"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1243,8 +1243,8 @@ { "id": "sc-changes-loaded.outer-refused:settled", "observation": { - "sender": ["891438a18444", "085b756c7623"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "085b756c7623"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1255,8 +1255,8 @@ { "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { - "sender": ["63bc0796d81c", "085b756c7623"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "085b756c7623"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1267,8 +1267,8 @@ { "id": "sc-changes-loaded.outer-refused-no-message:compare-pending", "observation": { - "sender": ["891438a18444", "207e0351be0d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "207e0351be0d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1279,8 +1279,8 @@ { "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { - "sender": ["891438a18444", "207e0351be0d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "207e0351be0d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1291,8 +1291,8 @@ { "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { - "sender": ["63bc0796d81c", "207e0351be0d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "207e0351be0d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1303,8 +1303,8 @@ { "id": "sc-changes-loaded.method-not-found:compare-pending", "observation": { - "sender": ["891438a18444", "6d2d788a9e84"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "6d2d788a9e84"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1315,8 +1315,8 @@ { "id": "sc-changes-loaded.method-not-found:settled", "observation": { - "sender": ["891438a18444", "6d2d788a9e84"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "6d2d788a9e84"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1327,8 +1327,8 @@ { "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { - "sender": ["63bc0796d81c", "6d2d788a9e84"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["3088889ce80e", "6d2d788a9e84"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1339,8 +1339,8 @@ { "id": "sc-changes-loaded.transport-rejection:compare-pending", "observation": { - "sender": ["891438a18444", "9778e6b1ca17", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "9778e6b1ca17", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1351,8 +1351,8 @@ { "id": "sc-changes-loaded.transport-rejection:settled", "observation": { - "sender": ["891438a18444", "9778e6b1ca17", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "9778e6b1ca17", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1363,8 +1363,8 @@ { "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { - "sender": ["63bc0796d81c", "9778e6b1ca17", "270fa28bd742"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["3088889ce80e", "9778e6b1ca17", "270fa28bd742"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1375,8 +1375,8 @@ { "id": "sc-changes-loaded.transport-rejection-no-message:compare-pending", "observation": { - "sender": ["891438a18444", "953d7e425499", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "953d7e425499", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1387,8 +1387,8 @@ { "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { - "sender": ["891438a18444", "953d7e425499", "f0896523e780"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["b823fdc0d205", "953d7e425499", "f0896523e780"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, @@ -1399,8 +1399,8 @@ { "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { - "sender": ["63bc0796d81c", "953d7e425499", "270fa28bd742"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], + "sender": ["3088889ce80e", "953d7e425499", "270fa28bd742"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "5ab051d969ce"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json index 9c9744e247e..8253a6d33a4 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-repo.list-1.json @@ -147,6 +147,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "3dcba72c2342": { "name": "streams-registered-at-teardown", "ordinal": 10, @@ -245,38 +277,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "687fc7be7b14": { "name": "repo.list#1", "ordinal": 7, @@ -530,32 +530,6 @@ } } }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -691,6 +665,32 @@ } } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "c2c26da9df33": { "name": "repo.list#1", "ordinal": 7, @@ -763,11 +763,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "e610fd221300": { "name": "repo.list#1", "ordinal": 7, @@ -808,6 +803,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f19d3d43b828": { "name": "repo.list#1", "ordinal": 7, @@ -882,8 +882,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -894,9 +894,9 @@ { "id": "sc-changes-loaded.prelude:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -913,14 +913,14 @@ "id": "sc-changes-loaded.prelude:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "f802165696e4", "b60e016a0f1e" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -937,14 +937,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -962,14 +962,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -987,14 +987,14 @@ "id": "sc-changes-loaded.result-absent:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "4b1217ea83ab", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1012,14 +1012,14 @@ "id": "sc-changes-loaded.result-absent:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "4b1217ea83ab", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1037,14 +1037,14 @@ "id": "sc-changes-loaded.result-null:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "772f9a3bbdd8", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1062,14 +1062,14 @@ "id": "sc-changes-loaded.result-null:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "772f9a3bbdd8", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1087,14 +1087,14 @@ "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "7eb62de26957", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1112,14 +1112,14 @@ "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "7eb62de26957", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1137,14 +1137,14 @@ "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "d7b92d364b7b", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1162,14 +1162,14 @@ "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "d7b92d364b7b", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1187,14 +1187,14 @@ "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "6fe24defc416", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1212,14 +1212,14 @@ "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "6fe24defc416", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1237,14 +1237,14 @@ "id": "sc-changes-loaded.outer-refused:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "f19d3d43b828", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1262,14 +1262,14 @@ "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "f19d3d43b828", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1287,14 +1287,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "687fc7be7b14", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1312,14 +1312,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "687fc7be7b14", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1337,14 +1337,14 @@ "id": "sc-changes-loaded.method-not-found:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "75e5bfff5576", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1362,14 +1362,14 @@ "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "75e5bfff5576", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1387,14 +1387,14 @@ "id": "sc-changes-loaded.transport-rejection:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "e610fd221300", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1412,14 +1412,14 @@ "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "e610fd221300", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1437,14 +1437,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "c2c26da9df33", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1462,14 +1462,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "c2c26da9df33", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json b/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json index cebb910d6e1..13bd3cef82b 100644 --- a/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json +++ b/mobile/rpc-foundation/goldens/matrix-git.changes-load-worktree.show-1.json @@ -248,6 +248,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "3403b59cf439": { "name": "worktree.show#1", "ordinal": 6, @@ -450,38 +482,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6f4a5d6a5a86": { "name": "worktree.show#1", "ordinal": 6, @@ -560,32 +560,6 @@ } ] }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8989d6980fc9": { "name": "repo.baseRefDefault#1", "ordinal": 10, @@ -782,6 +756,32 @@ } } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "cb462f8b50a3": { "name": "worktree.show#1", "ordinal": 8, @@ -924,11 +924,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -937,6 +932,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f802165696e4": { "name": "repo.list#1", "ordinal": 7, @@ -976,8 +976,8 @@ { "id": "sc-changes-loaded.prelude:status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -988,9 +988,9 @@ { "id": "sc-changes-loaded.prelude:compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1007,14 +1007,14 @@ "id": "sc-changes-loaded.prelude:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "da80647539b5", "f802165696e4", "99df70fb15d8" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1031,14 +1031,14 @@ "id": "sc-changes-loaded.normal:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1056,14 +1056,14 @@ "id": "sc-changes-loaded.normal:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1081,14 +1081,14 @@ "id": "sc-changes-loaded.result-absent:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "b1f1cf609f1a", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1106,14 +1106,14 @@ "id": "sc-changes-loaded.result-absent:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "b1f1cf609f1a", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1131,14 +1131,14 @@ "id": "sc-changes-loaded.result-null:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "3fa278bfc300", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1156,14 +1156,14 @@ "id": "sc-changes-loaded.result-null:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "3fa278bfc300", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1181,14 +1181,14 @@ "id": "sc-changes-loaded.inner-ok-missing:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "12cda398ef1c", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1206,14 +1206,14 @@ "id": "sc-changes-loaded.inner-ok-missing:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "12cda398ef1c", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1231,14 +1231,14 @@ "id": "sc-changes-loaded.inner-false-string-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "cbba4d974cd2", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1256,14 +1256,14 @@ "id": "sc-changes-loaded.inner-false-string-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "cbba4d974cd2", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1281,14 +1281,14 @@ "id": "sc-changes-loaded.inner-false-object-error:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "3403b59cf439", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1306,14 +1306,14 @@ "id": "sc-changes-loaded.inner-false-object-error:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "3403b59cf439", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1331,14 +1331,14 @@ "id": "sc-changes-loaded.outer-refused:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "db7a4d8e637e", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1356,14 +1356,14 @@ "id": "sc-changes-loaded.outer-refused:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "db7a4d8e637e", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1381,14 +1381,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "1266df2a91af", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1406,14 +1406,14 @@ "id": "sc-changes-loaded.outer-refused-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "1266df2a91af", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1431,14 +1431,14 @@ "id": "sc-changes-loaded.method-not-found:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "d67ff8e687bf", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1456,14 +1456,14 @@ "id": "sc-changes-loaded.method-not-found:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "d67ff8e687bf", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1481,14 +1481,14 @@ "id": "sc-changes-loaded.transport-rejection:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "5782be802edd", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1506,14 +1506,14 @@ "id": "sc-changes-loaded.transport-rejection:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "5782be802edd", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1531,14 +1531,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "1ff055d43072", "2ca33da4d135", "8989d6980fc9" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -1556,14 +1556,14 @@ "id": "sc-changes-loaded.transport-rejection-no-message:cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "1ff055d43072", "2ca33da4d135", "3718b7e83a50" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json b/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json index 21ea2e4599a..ed5e635fd8f 100644 --- a/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json +++ b/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json @@ -43,41 +43,6 @@ } } }, - "0d02c4637af4": { - "name": "info", - "ordinal": 3, - "value": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, - "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, - "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, - "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } - } - }, "11008b947f78": { "name": "worktree.ps#1", "ordinal": 1, @@ -158,6 +123,21 @@ } } }, + "19a302575563": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { + "displayName": "One", + "repo": "Repo", + "status": "working", + "worktreeId": "w-1" + }, + "totalWorktrees": 2 + } + }, "298c6fbd5d42": { "name": "worktree.ps#1", "ordinal": 1, @@ -313,6 +293,25 @@ } } }, + "7858e4e82b0f": { + "name": "info", + "ordinal": 3, + "value": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { + "displayName": "One", + "repo": "Repo", + "status": "working", + "worktreeId": "w-1" + }, + "totalWorktrees": 2 + } + } + }, "817623c64ce1": { "name": "worktree.ps#1", "ordinal": 1, @@ -348,37 +347,6 @@ } } }, - "87aae336d391": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, - "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, - "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, - "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } - }, "922cb68379ac": { "name": "worktree.ps#1", "ordinal": 2, @@ -599,8 +567,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "87aae336d391", - "effects": ["0d02c4637af4"] + "state": "19a302575563", + "effects": ["7858e4e82b0f"] } }, { diff --git a/mobile/rpc-foundation/goldens/sc-changes-loaded.json b/mobile/rpc-foundation/goldens/sc-changes-loaded.json index a170eba82de..ed045bdb30b 100644 --- a/mobile/rpc-foundation/goldens/sc-changes-loaded.json +++ b/mobile/rpc-foundation/goldens/sc-changes-loaded.json @@ -147,6 +147,38 @@ } } }, + "3088889ce80e": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "5d30d477f0d5": { "name": "git.branchCompare#1", "ordinal": 10, @@ -203,38 +235,6 @@ "ordinal": 11, "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"git.branchCompare\",\"params\":{\"worktree\":\"id:repo42::/p\",\"baseRef\":\"origin/dev\"}}" }, - "63bc0796d81c": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "6f4a5d6a5a86": { "name": "worktree.show#1", "ordinal": 6, @@ -313,32 +313,6 @@ } ] }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "8fda864c66d6": { "branchCompareState": { "kind": "loading" @@ -441,16 +415,37 @@ "kind": "loading" } }, + "b823fdc0d205": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "cb462f8b50a3": { "name": "worktree.show#1", "ordinal": 8, "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -458,6 +453,11 @@ "value": { "$rpc": "undefined" } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" } }, "recording": { @@ -466,8 +466,8 @@ { "id": "status-pending", "observation": { - "sender": ["891438a18444", "2ab4c978da8d"], - "payloads": ["e539e80d06e9", "1c2564f1daca", "92a577a15fcc"], + "sender": ["b823fdc0d205", "2ab4c978da8d"], + "payloads": ["eef1ee3c2773", "1c2564f1daca", "92a577a15fcc"], "settlements": { "mount": "eb79a9b3682a" }, @@ -478,9 +478,9 @@ { "id": "compare-pending", "observation": { - "sender": ["891438a18444", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], + "sender": ["b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a"], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -497,14 +497,14 @@ "id": "settled", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -522,14 +522,14 @@ "id": "cleanup", "observation": { "sender": [ - "63bc0796d81c", + "3088889ce80e", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json b/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json index fb6db7f022d..3e3e22cf70a 100644 --- a/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json +++ b/mobile/rpc-foundation/goldens/sc-changes-return-from-memory.json @@ -127,6 +127,38 @@ "$rpc": "undefined" } }, + "22bf66c852bb": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 3001, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "2ca33da4d135": { "name": "repo.list#1", "ordinal": 7, @@ -411,32 +443,6 @@ "ordinal": 17, "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "92a577a15fcc": { "name": "git.status#1", "ordinal": 5, @@ -540,9 +546,9 @@ } ] }, - "ade0dae5eee8": { + "b823fdc0d205": { "name": "settings.get#1", - "ordinal": 1, + "ordinal": 2, "args": [ { "name": "method", @@ -562,14 +568,8 @@ } ], "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 3001, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } + "status": "pending", + "startedAt": 0 } }, "cb462f8b50a3": { @@ -646,11 +646,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -658,6 +653,11 @@ "value": { "$rpc": "undefined" } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" } }, "recording": { @@ -667,14 +667,14 @@ "id": "loaded", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", "5d30d477f0d5" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -692,7 +692,7 @@ "id": "rows-while-revalidating", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", @@ -700,7 +700,7 @@ "7d368b32d250" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -722,7 +722,7 @@ "id": "revalidated", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "74d102469d68", "2ca33da4d135", @@ -732,7 +732,7 @@ "a6d51875b1b0" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -756,7 +756,7 @@ "id": "cleanup", "observation": { "sender": [ - "ade0dae5eee8", + "22bf66c852bb", "962f91336a50", "74d102469d68", "2ca33da4d135", @@ -767,7 +767,7 @@ "d29ae612a0e8" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json b/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json index adb6c27e5c8..712bfcbf5d9 100644 --- a/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json +++ b/mobile/rpc-foundation/goldens/sc-changes-write-reads-live.json @@ -203,6 +203,38 @@ } } }, + "22bf66c852bb": { + "name": "settings.get#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "settings.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 3001, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "334b41f87c41": { "name": "worktree.show#1", "ordinal": 6, @@ -380,32 +412,6 @@ "ordinal": 17, "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" }, - "891438a18444": { - "name": "settings.get#1", - "ordinal": 1, - "args": [ - { - "name": "method", - "value": "settings.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "92a577a15fcc": { "name": "git.status#1", "ordinal": 5, @@ -562,9 +568,14 @@ "startedAt": 3001 } }, - "ade0dae5eee8": { + "b06ca46466ca": { + "name": "git.status#3", + "ordinal": 14, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"git.status\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" + }, + "b823fdc0d205": { "name": "settings.get#1", - "ordinal": 1, + "ordinal": 2, "args": [ { "name": "method", @@ -584,21 +595,10 @@ } ], "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 3001, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } + "status": "pending", + "startedAt": 0 } }, - "b06ca46466ca": { - "name": "git.status#3", - "ordinal": 14, - "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"git.status\",\"params\":{\"worktree\":\"id:repo42::/p\"}}" - }, "bf019629baab": { "name": "repo.list#1", "ordinal": 7, @@ -673,11 +673,6 @@ } } }, - "e539e80d06e9": { - "name": "runtime.clientEvents.subscribe#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -686,6 +681,11 @@ "$rpc": "undefined" } }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "f0a6f14b92e4": { "name": "source-control.status-load-success", "ordinal": 20, @@ -699,7 +699,7 @@ "id": "post-write-status", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a", @@ -709,7 +709,7 @@ "a6d51875b1b0" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -734,7 +734,7 @@ "id": "superseded-revalidation-ignored", "observation": { "sender": [ - "891438a18444", + "b823fdc0d205", "962f91336a50", "6f4a5d6a5a86", "1934c215114a", @@ -744,7 +744,7 @@ "a6d51875b1b0" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", @@ -769,7 +769,7 @@ "id": "cleanup", "observation": { "sender": [ - "ade0dae5eee8", + "22bf66c852bb", "962f91336a50", "334b41f87c41", "bf019629baab", @@ -781,7 +781,7 @@ "1a6e003b2d53" ], "payloads": [ - "e539e80d06e9", + "eef1ee3c2773", "1c2564f1daca", "92a577a15fcc", "cb462f8b50a3", diff --git a/mobile/rpc-foundation/goldens/worktree-home-catalog.json b/mobile/rpc-foundation/goldens/worktree-home-catalog.json index 39c48cc8afa..a8c20584939 100644 --- a/mobile/rpc-foundation/goldens/worktree-home-catalog.json +++ b/mobile/rpc-foundation/goldens/worktree-home-catalog.json @@ -4,39 +4,19 @@ "family": "worktree.home-catalog", "namedDeltas": [], "values": { - "0d02c4637af4": { - "name": "info", - "ordinal": 3, - "value": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, - "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, - "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, - "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } + "19a302575563": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { + "displayName": "One", + "repo": "Repo", + "status": "working", + "worktreeId": "w-1" + }, + "totalWorktrees": 2 } }, "34fb08d01b03": { @@ -70,35 +50,23 @@ } }, "44136fa355b3": {}, - "87aae336d391": { - "host-1": { - "activeCount": 2, - "attention": [ - { - "branch": { - "$rpc": "undefined" - }, + "7858e4e82b0f": { + "name": "info", + "ordinal": 3, + "value": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "lastActiveWorktree": { "displayName": "One", - "dotStatus": "working", - "lastOutputAt": { - "$rpc": "undefined" - }, "repo": "Repo", - "workingMode": { - "$rpc": "undefined" - }, + "status": "working", "worktreeId": "w-1" - } - ], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 + }, + "totalWorktrees": 2 + } } }, "922cb68379ac": { @@ -193,8 +161,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "87aae336d391", - "effects": ["0d02c4637af4"] + "state": "19a302575563", + "effects": ["7858e4e82b0f"] } } ] diff --git a/mobile/src/agents/MobileAgentListRows.tsx b/mobile/src/agents/MobileAgentListRows.tsx new file mode 100644 index 00000000000..0f5f5b7908b --- /dev/null +++ b/mobile/src/agents/MobileAgentListRows.tsx @@ -0,0 +1,346 @@ +import { Bell, ChevronDown, ChevronRight, Eye, EyeOff, X } from 'lucide-react-native' +import { Fragment, memo, useCallback, useState } from 'react' +import { Alert, Pressable, Text, View } from 'react-native' +import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' +import type { WorktreeStatus } from '../../../src/shared/worktree-status-rollup' +import { AgentSpinner, agentStatusColors } from '../components/AgentSpinner' +import { MobileAgentIcon } from '../components/MobileAgentIcon' +import { SwipeRowActions } from '../components/SwipeRowActions' +import { HOME_ROW_TEXT_INSET, homeListStyles } from '../home/home-list-styles' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { triggerMediumImpact } from '../platform/haptics' +import { colors, spacing } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import type { HostProfile } from '../transport/hosts/host-profile' +import { useHostDisplay } from '../transport/hosts/use-host-display' +import { agentStateLabel, formatTimeAgo, type AgentDotState } from '../worktree/agent-row-display' +import { isDisclosureOpen, toggleDisclosure } from '../worktree/agent-child-disclosure' +import { areStructurallyEqual } from '../worktree/structural-equality' +import type { AgentListSection } from './agent-list-model' +import { agentStatusGroup, type AgentListRow } from './agent-list-rows' +import { agentListPreview } from './agent-list-row-text' + +// The Home rollup glyph is the list's size; this maps a per-agent state onto its palette. +const GLYPH_STATUS: Record = { + working: 'working', + monitoring: 'monitoring', + blocked: 'permission', + waiting: 'permission', + permission: 'permission', + failed: 'failed', + done: 'done', + interrupted: 'interrupted', + unconfirmed: 'unconfirmed', + idle: 'inactive', + unverifiable: 'inactive' +} + +const WORKER_INDENT = 22 +const TOGGLE_HIT_SLOP = { top: 10, bottom: 10, left: 12, right: 12 } as const + +const workersKey = (row: AgentListRow) => `agents:workers:${row.key}` + +type ShownRow = { row: AgentListRow; key: string; workersOpen?: boolean } + +export type AgentListRowHandlers = Readonly<{ + onOpen: (row: AgentListRow) => void + onLongPress: (row: AgentListRow) => void + onSetRead: (rows: readonly AgentListRow[], read: boolean) => void + onClear: (rows: readonly AgentListRow[]) => void +}> + +/** One inset group of agent rows, with each coordinator's workers and an optional idle fold. */ +export function MobileAgentListRows(props: { + handlers: AgentListRowHandlers + rows: readonly AgentListRow[] + idleRows?: readonly AgentListRow[] + footer: AgentListSection['footer'] + nameDesktop: boolean + hosts: readonly HostProfile[] + now: number + /** Remembers the idle fold per list. */ + idleKey?: string +}) { + const t = useMobileTranslation() + useMobileColorScheme() + // Disclosures live in a module cache so they survive remounts; this only redraws after a toggle. + const [, setRevision] = useState(0) + const toggle = useCallback((key: string) => { + toggleDisclosure(key) + setRevision((revision) => revision + 1) + }, []) + const idleKey = `agents:idle:${props.idleKey ?? ''}` + const idleOpen = isDisclosureOpen(idleKey) + const idleRows = props.idleRows ?? [] + const hostById = new Map(props.hosts.map((host) => [host.id, host])) + const withWorkers = (rows: readonly AgentListRow[], prefix: string) => + rows.flatMap((row): ShownRow[] => { + const key = `${prefix}${row.key}` + const workersOpen = row.workers.length > 0 ? isDisclosureOpen(workersKey(row)) : undefined + const workers = workersOpen + ? row.workers.map((worker) => ({ row: worker, key: `${key}>${worker.key}` })) + : [] + return [{ row, key, workersOpen }, ...workers] + }) + const renderRows = (items: readonly ShownRow[], separateFirst: boolean) => + items.map((item, index) => ( + + {index > 0 || separateFirst ? ( + + ) : null} + + + )) + return ( + + {renderRows(withWorkers(props.rows, ''), false)} + {idleRows.length > 0 ? ( + <> + {props.rows.length > 0 ? : null} + [styles.foldRow, pressed && homeListStyles.rowPressed]} + onPress={() => toggle(idleKey)} + > + {idleOpen ? ( + + ) : ( + + )} + + {t('agents.list.idleCount', '{{count}} idle', { count: idleRows.length })} + + + {idleOpen ? renderRows(withWorkers(idleRows, 'idle>'), true) : null} + + ) : null} + + ) +} + +// Each refresh rebuilds every row; compare by value so only changed rows redraw. +const MobileAgentListRow = memo(function MobileAgentListRow(props: { + handlers: AgentListRowHandlers + row: AgentListRow + host: HostProfile | null + footer: AgentListSection['footer'] + nameDesktop: boolean + now: number + /** Undefined when the row has no workers to show. */ + workersOpen?: boolean + onToggleWorkers: (key: string) => void +}) { + const t = useMobileTranslation() + useMobileColorScheme() + const { row } = props + const { agent } = row.entry + const desktop = useHostDisplay(props.host).title + const { title } = row + const group = row.stale ? null : agentStatusGroup(row.dotState) + const preview = agentListPreview(agent, group, title) + const needsYou = group === 'needs-you' + const stateWord = needsYou ? agentStateLabel(row.dotState) : '' + const place = [ + props.footer === 'agent' ? formatAgentTypeLabel(agent.agentType) : row.entry.workspaceName, + props.nameDesktop ? desktop : null + ] + .filter(Boolean) + .join(' · ') + const time = row.timeAt > 0 ? formatTimeAgo(row.timeAt, props.now) : '' + const workerCount = row.workers.length + const workersLabel = + workerCount === 1 + ? t('agents.list.workers_one', '{{count}} worker', { count: workerCount }) + : t('agents.list.workers_other', '{{count}} workers', { count: workerCount }) + // The row is one accessibility element, so screen readers reach the workers toggle through it. + const workersAction = + props.workersOpen === undefined + ? null + : { + name: 'toggleWorkers', + label: props.workersOpen + ? t('agents.list.hideWorkers', 'Hide {{workers}}', { workers: workersLabel }) + : t('agents.list.showWorkers', 'Show {{workers}}', { workers: workersLabel }) + } + const longPress = () => { + triggerMediumImpact() + props.handlers.onLongPress(row) + } + const open = () => { + if (row.offline) { + Alert.alert( + t('agents.list.offlineTitle', '{{desktop}} is offline', { desktop }), + t('agents.list.offlineMessage', 'Reconnect it to open this agent.') + ) + return + } + props.handlers.onOpen(row) + } + const actionsLabel = t('agents.list.actions', 'Actions for {{title}}', { title }) + const unread = row.unread === true + return ( + props.handlers.onSetRead([row], unread) + } + } + trailing={ + row.clearable && !row.offline + ? { + label: t('agents.swipe.clear', 'Clear'), + accessibilityLabel: t('agents.actions.clear', 'Clear from list'), + icon: X, + background: colors.textMuted, + foreground: colors.onAccent, + onPress: () => props.handlers.onClear([row]) + } + : undefined + } + > + {(guardPress) => ( + { + if (event.nativeEvent.actionName === 'longpress') { + longPress() + } else if (event.nativeEvent.actionName === 'toggleWorkers') { + props.onToggleWorkers(workersKey(row)) + } + }} + style={({ pressed }) => [ + homeListStyles.row, + styles.row, + row.depth > 0 && { paddingLeft: spacing.lg + row.depth * WORKER_INDENT }, + pressed && homeListStyles.rowPressed + ]} + onPress={guardPress(open)} + onLongPress={longPress} + delayLongPress={400} + > + + + + + + + {title} + + {time ? {time} : null} + + {stateWord || preview ? ( + + {stateWord ? ( + + {stateWord} + + ) : null} + {stateWord && preview ? ' · ' : ''} + {preview} + + ) : null} + + {agent.agentType ? : null} + + {place} + + + {unread ? ( + + ) : null} + {props.workersOpen !== undefined ? ( + { + event.stopPropagation() + guardPress(() => props.onToggleWorkers(workersKey(row)))() + }} + > + {props.workersOpen ? ( + + ) : ( + + )} + {workersLabel} + + ) : null} + + + + + )} + + ) +}, areStructurallyEqual) + +const styles = themedStyleSheet(() => ({ + text: { flex: 1, minWidth: 0, paddingTop: 9, paddingBottom: 10, paddingRight: 14, gap: 3 }, + titleLine: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm }, + // Opaque so a swipe's actions stay hidden until the row slides off them. + row: { backgroundColor: colors.bgPanel }, + title: { flex: 1, minWidth: 0, fontSize: 15, lineHeight: 20, color: colors.textPrimary }, + titleUnread: { fontWeight: '600' }, + time: { fontSize: 12, color: colors.textMuted, fontVariant: ['tabular-nums'] }, + preview: { fontSize: 14, lineHeight: 19, color: colors.textSecondary }, + stateWord: { fontWeight: '600' }, + footer: { flexDirection: 'row', alignItems: 'center', gap: 6, minWidth: 0 }, + place: { flexShrink: 1, fontSize: 12, color: colors.textMuted }, + trailing: { flexDirection: 'row', alignItems: 'center', gap: 8, marginLeft: 'auto' }, + workers: { flexDirection: 'row', alignItems: 'center', gap: 4 }, + workersLabel: { fontSize: 12, fontWeight: '500', color: colors.textSecondary }, + foldRow: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + minHeight: 44, + paddingLeft: HOME_ROW_TEXT_INSET - 4, + paddingRight: spacing.lg + }, + foldLabel: { fontSize: 14, color: colors.textSecondary } +})) diff --git a/mobile/src/agents/agent-list-model.test.ts b/mobile/src/agents/agent-list-model.test.ts new file mode 100644 index 00000000000..0001a6684d0 --- /dev/null +++ b/mobile/src/agents/agent-list-model.test.ts @@ -0,0 +1,287 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { ConnectionState } from '../transport/connection/connection-state' +import type { HostWorktreeInfo } from '../worktree/home-worktree-info' +import { buildAgentList, type AgentListSection } from './agent-list-model' +import { + selectAgentsNeedingYou, + type AgentListInput, + type AgentListRow, + type ListedAgentVerdict +} from './agent-list-rows' + +const NOW = 1_800_000_000_000 +const MINUTE = 60_000 + +function agent( + paneKey: string, + state: RuntimeWorktreeAgentRow['state'], + overrides: Partial = {} +): RuntimeWorktreeAgentRow { + return { + paneKey, + parentPaneKey: null, + state, + agentType: 'claude', + prompt: '', + taskTitle: null, + displayName: null, + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: NOW - MINUTE, + updatedAt: NOW - MINUTE, + ...overrides + } +} + +function entries(agents: RuntimeWorktreeAgentRow[]) { + return agents.map((row) => ({ + worktreeId: 'wt-1', + workspaceName: 'mobile-tabs', + repo: 'orca', + branch: 'main', + agent: row + })) +} + +function input( + hosts: Record }> +): AgentListInput { + return { + hosts: Object.keys(hosts).map((id) => ({ id })), + hostStates: Object.fromEntries(Object.entries(hosts).map(([id, host]) => [id, host.state])), + worktreeInfo: Object.fromEntries( + Object.entries(hosts).map(([id, host]) => [ + id, + { hostId: id, totalWorktrees: 1, activeCount: 0, lastActiveWorktree: null, ...host.info } + ]) + ), + now: NOW + } +} + +const panes = (rows: readonly AgentListRow[] | undefined) => + rows?.map((row) => row.entry.agent.paneKey) +const shape = (sections: AgentListSection[]) => + sections.map((section) => ({ + kind: section.kind, + rows: panes(section.rows), + workers: section.rows.map((row) => panes(row.workers)), + idle: panes(section.idleRows) + })) +const statusView = (showWorkers: boolean, unreadOnly = false) => ({ + view: { groupBy: 'status' as const, showWorkers, unreadOnly }, + hostFilter: null, + query: '' +}) + +describe('buildAgentList by status', () => { + it('buckets agents by what they ask of the user, newest first, and folds idle ones', () => { + const list = buildAgentList( + input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('asking', 'waiting'), + agent('older-run', 'working', { stateStartedAt: NOW - 5 * MINUTE }), + agent('newer-run', 'working', { stateStartedAt: NOW - 2 * MINUTE }), + agent('finished', 'done'), + // Silent past the 30-minute freshness window. + agent('quiet', 'working', { updatedAt: NOW - 31 * MINUTE }) + ]) + } + } + }), + statusView(true) + ) + expect(shape(list.sections)).toEqual([ + { kind: 'needs-you', rows: ['asking'], workers: [[]], idle: undefined }, + { + kind: 'working', + rows: ['newer-run', 'older-run'], + workers: [[], []], + idle: undefined + }, + { kind: 'done', rows: ['finished'], workers: [[]], idle: ['quiet'] } + ]) + }) + + it('nests workers under their coordinator and still lists the one that needs the user', () => { + const host = input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('coordinator', 'working'), + agent('worker-busy', 'working', { parentPaneKey: 'coordinator' }), + agent('worker-asking', 'blocked', { parentPaneKey: 'coordinator' }) + ]) + } + } + }) + expect(shape(buildAgentList(host, statusView(true)).sections)).toEqual([ + { kind: 'needs-you', rows: ['worker-asking'], workers: [[]], idle: undefined }, + { + kind: 'working', + rows: ['coordinator'], + workers: [['worker-busy', 'worker-asking']], + idle: undefined + } + ]) + expect(shape(buildAgentList(host, statusView(false)).sections)).toEqual([ + { kind: 'needs-you', rows: ['worker-asking'], workers: [[]], idle: undefined }, + { kind: 'working', rows: ['coordinator'], workers: [[]], idle: undefined } + ]) + expect(panes(selectAgentsNeedingYou(host))).toEqual(['worker-asking']) + }) + + it('keeps a lost desktop’s agents as last seen, outside the status groups and the counts', () => { + const lastSeen = entries([agent('was-asking', 'waiting')]) + const disconnected = input({ + mac: { state: 'connected', info: { agents: entries([agent('asking', 'waiting')]) } }, + studio: { state: 'disconnected', info: { lastSeenAgents: lastSeen, countsProvenAt: NOW } } + }) + const list = buildAgentList(disconnected, statusView(true)) + expect(shape(list.sections)).toEqual([ + { kind: 'needs-you', rows: ['asking'], workers: [[]], idle: undefined }, + { kind: 'desktop', rows: ['was-asking'], workers: [[]], idle: undefined } + ]) + expect(list.sections[1]).toMatchObject({ + hostId: 'studio', + lastSeen: { offline: true, at: NOW } + }) + expect(list.sections[1].rows[0]).toMatchObject({ stale: true, offline: true, dotState: 'idle' }) + expect(panes(selectAgentsNeedingYou(disconnected))).toEqual(['asking']) + + // Reconnected, but until its own read lands the old rows still claim nothing. + const reconnected = input({ + studio: { state: 'connected', info: { lastSeenAgents: lastSeen, countsProvenAt: NOW } } + }) + expect(selectAgentsNeedingYou(reconnected)).toEqual([]) + expect(buildAgentList(reconnected, statusView(true)).sections[0].rows[0]).toMatchObject({ + stale: true, + offline: false + }) + }) + + it('lists, orders and marks agents by the desktop Agents list’s verdicts', () => { + // Every raw state says working: only the verdicts decide. + const listed = (paneKey: string, verdict: Partial) => + agent(paneKey, 'working', { + activity: { + listed: true, + status: 'done', + unread: false, + clearable: false, + sortAt: NOW - MINUTE, + title: `Task ${paneKey}`, + ...verdict + } + }) + const host = (pendingActivity?: AgentListInput['pendingActivity']) => ({ + ...input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('session-start', 'working', { activity: { listed: false } }), + listed('failed', { status: 'failed', clearable: true, sortAt: NOW - MINUTE }), + listed('asking', { status: 'permission', unread: true, sortAt: NOW - 5 * MINUTE }), + listed('unconfirmed', { status: 'unconfirmed', clearable: true }), + listed('finished', { status: 'done', unread: true, clearable: true }), + listed('quiet', { status: 'unverifiable' }), + listed('stopped', { status: 'interrupted', clearable: true }) + ]) + } + } + }), + pendingActivity + }) + const rows = (list: ReturnType) => + list.sections.map((section) => [ + section.kind, + section.rows.map((row) => [row.entry.agent.paneKey, row.unread, row.clearable]) + ]) + expect(rows(buildAgentList(host(), statusView(true)))).toEqual([ + [ + 'needs-you', + [ + ['asking', true, false], + ['failed', false, true], + ['unconfirmed', false, true] + ] + ], + [ + 'done', + [ + ['stopped', false, true], + ['quiet', false, false], + ['finished', true, true] + ] + ] + ]) + expect(buildAgentList(host(), statusView(true)).sections[0].rows[0]).toMatchObject({ + title: 'Task asking', + dotState: 'permission' + }) + expect(panes(selectAgentsNeedingYou(host()))).toEqual(['asking', 'failed', 'unconfirmed']) + // Unread only is the desktop's unread alone, needs-you rows included. + expect(rows(buildAgentList(host(), statusView(true, true)))).toEqual([ + ['needs-you', [['asking', true, false]]], + ['done', [['finished', true, true]]] + ]) + // A write in flight shows until the desktop's next list read carries it. + const pending = host({ 'mac:failed': { unread: true }, 'mac:finished': { cleared: true } }) + expect(rows(buildAgentList(pending, statusView(true, true)))).toEqual([ + [ + 'needs-you', + [ + ['asking', true, false], + ['failed', true, true] + ] + ] + ]) + }) + + it('nests workers where the desktop does and hides the ones it folds', () => { + const verdict = (status: ListedAgentVerdict['status'], extra: Partial) => ({ + listed: true as const, + status, + unread: false, + clearable: false, + sortAt: NOW - MINUTE, + title: 'Task', + ...extra + }) + const host = input({ + mac: { + state: 'connected', + info: { + agents: entries([ + agent('coordinator', 'working', { activity: verdict('working', {}) }), + agent('worker-done', 'done', { + activity: verdict('done', { childOf: 'coordinator', foldedChild: true }) + }), + agent('worker-busy', 'working', { + activity: verdict('working', { childOf: 'coordinator', sortAt: NOW }) + }) + ]) + } + } + }) + expect(shape(buildAgentList(host, statusView(true)).sections)).toEqual([ + { + kind: 'working', + rows: ['coordinator'], + workers: [['worker-done', 'worker-busy']], + idle: undefined + } + ]) + expect(shape(buildAgentList(host, statusView(false)).sections)).toEqual([ + { kind: 'working', rows: ['worker-busy', 'coordinator'], workers: [[], []], idle: undefined } + ]) + }) +}) diff --git a/mobile/src/agents/agent-list-model.ts b/mobile/src/agents/agent-list-model.ts new file mode 100644 index 00000000000..3ee9d124589 --- /dev/null +++ b/mobile/src/agents/agent-list-model.ts @@ -0,0 +1,250 @@ +import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' +import { agentListEntryMatches } from './agent-list-row-text' +import { + agentStatusGroup, + asTopLevel, + byStatusThenRecent, + everyRow, + hostAgents, + listedAgentVerdict, + newestFirst, + rowNeedsYou, + type AgentListInput, + type AgentListRow, + type AgentStatusGroup, + type HostAgents +} from './agent-list-rows' + +export const AGENT_LIST_GROUP_BY_CHOICES = [ + 'status', + 'workspace', + 'project', + 'agent', + 'desktop' +] as const + +export type AgentListGroupBy = (typeof AGENT_LIST_GROUP_BY_CHOICES)[number] + +export type AgentListView = Readonly<{ + groupBy: AgentListGroupBy + showWorkers: boolean + unreadOnly: boolean +}> + +export const DEFAULT_AGENT_LIST_VIEW: AgentListView = { + groupBy: 'status', + showWorkers: true, + unreadOnly: false +} + +export type AgentListSectionKind = AgentStatusGroup | 'workspace' | 'project' | 'agent' | 'desktop' + +export type AgentListSection = Readonly<{ + key: string + kind: AgentListSectionKind + /** The workspace, project or agent a data-named section is for. */ + title?: string + hostId?: string + rows: readonly AgentListRow[] + /** Status grouping folds idle agents into one row at the end of the list. */ + idleRows?: readonly AgentListRow[] + /** A desktop whose rows are last seen, and when they were read. */ + lastSeen?: Readonly<{ offline: boolean; at?: number }> + /** What each row's footer names; the section header names the rest. */ + footer: 'workspace' | 'agent' + nameDesktop: boolean +}> + +type GroupDraft = { key: string; title?: string; hostId?: string; rows: AgentListRow[] } + +function groupRows( + rows: readonly AgentListRow[], + keyOf: (row: AgentListRow) => Omit +): GroupDraft[] { + const groups = new Map() + for (const row of rows) { + const draft = keyOf(row) + const group = groups.get(draft.key) + if (group) { + group.rows.push(row) + } else { + groups.set(draft.key, { ...draft, rows: [row] }) + } + } + return [...groups.values()] +} + +// Groups with something that needs the user lead, then the most recently active. +function byUrgencyThenRecent(a: GroupDraft, b: GroupDraft): number { + const urgent = (group: GroupDraft) => (group.rows.some(rowNeedsYou) ? 0 : 1) + const latest = (group: GroupDraft) => Math.max(...group.rows.map((row) => row.timeAt)) + return urgent(a) - urgent(b) || latest(b) - latest(a) +} + +const STATUS_SECTIONS: readonly Exclude[] = [ + 'needs-you', + 'working', + 'done' +] + +export function buildAgentList( + input: AgentListInput, + options: Readonly<{ view: AgentListView; hostFilter: string | null; query: string }> +): { sections: AgentListSection[]; anyLive: boolean } { + const { view } = options + const hosts = input.hosts + .filter((host) => options.hostFilter === null || host.id === options.hostFilter) + .map((host) => hostAgents(input, host.id)) + // With no desktop read this session, an empty list says nothing about running agents. + const anyLive = hosts.some((host) => host.live) + const nameDesktop = input.hosts.length > 1 && options.hostFilter === null + const query = options.query.trim().toLowerCase() + + // Unread is the desktop's verdict alone. Rows it gave none stay: hiding them would claim they + // were read. A coordinator stays for its unread worker. + const shown = (row: AgentListRow) => + !view.unreadOnly || + row.unread === true || + (row.unread === undefined && !listedAgentVerdict(row.entry.agent)) || + row.workers.some((worker) => worker.unread) + const topLevel = (host: HostAgents): AgentListRow[] => { + if (query) { + // A match is shown on its own; its coordinator may not match. + return everyRow(host.roots) + .filter((row) => agentListEntryMatches(row.entry, query)) + .map(asTopLevel) + .filter(shown) + } + if (!view.showWorkers) { + // Desktop hides a finished worker and lists a live one on its own; without its verdict, only + // a worker that needs the user shows. + return everyRow(host.roots) + .filter((row) => { + const verdict = listedAgentVerdict(row.entry.agent) + return verdict ? !verdict.foldedChild : row.depth === 0 || rowNeedsYou(row) + }) + .map(asTopLevel) + .filter(shown) + } + // A worker that needs the user can't hide inside a folded coordinator. + const surfaced = host.roots.flatMap((root) => root.workers.filter(rowNeedsYou).map(asTopLevel)) + return [...host.roots, ...surfaced].filter(shown) + } + + const section = ( + draft: GroupDraft, + kind: AgentListSectionKind, + footer: AgentListSection['footer'], + names: boolean, + order = newestFirst + ): AgentListSection => ({ + ...draft, + kind, + rows: [...draft.rows].sort(order), + footer, + nameDesktop: names + }) + + if (view.groupBy === 'desktop') { + const sections = hosts.flatMap((host): AgentListSection[] => { + const rows = topLevel(host) + // An offline desktop keeps its header, so its absence reads as offline rather than idle. + if (rows.length === 0 && (host.live || query)) { + return [] + } + return [ + { + ...section( + { key: host.hostId, hostId: host.hostId, rows }, + 'desktop', + 'workspace', + false + ), + ...(host.live ? {} : { lastSeen: { offline: host.offline, at: host.seenAt } }) + } + ] + }) + return { sections, anyLive } + } + + if (view.groupBy === 'status') { + const live = hosts.filter((host) => host.live).flatMap(topLevel) + const sections: AgentListSection[] = STATUS_SECTIONS.map((kind) => + section( + { key: kind, rows: live.filter((row) => agentStatusGroup(row.dotState) === kind) }, + kind, + 'workspace', + nameDesktop, + byStatusThenRecent + ) + ).filter((entry) => entry.rows.length > 0) + const idleRows = live.filter((row) => agentStatusGroup(row.dotState) === 'idle') + if (idleRows.length > 0) { + const folded = [...idleRows].sort(newestFirst) + const last = sections.at(-1) + if (last) { + sections[sections.length - 1] = { ...last, idleRows: folded } + } else { + sections.push({ + ...section({ key: 'idle', rows: [] }, 'idle', 'workspace', nameDesktop), + idleRows: folded + }) + } + } + // Last-seen rows claim no status, so they stay under their desktop. + for (const host of hosts) { + const rows = host.live ? [] : topLevel(host) + if (rows.length > 0) { + sections.push({ + ...section( + { key: host.hostId, hostId: host.hostId, rows }, + 'desktop', + 'workspace', + false + ), + lastSeen: { offline: host.offline, at: host.seenAt } + }) + } + } + return { sections, anyLive } + } + + const rows = hosts.flatMap(topLevel) + const drafts = + view.groupBy === 'workspace' + ? groupRows(rows, (row) => ({ + key: `${row.hostId}:${row.entry.worktreeId}`, + title: row.entry.workspaceName, + hostId: row.hostId + })) + : view.groupBy === 'project' + ? groupRows(rows, (row) => ({ + key: `${row.hostId}:${row.entry.repo}`, + title: row.entry.repo, + hostId: row.hostId + })) + : groupRows(rows, (row) => { + const label = formatAgentTypeLabel(row.entry.agent.agentType) + return { key: label, title: label } + }) + const kind = view.groupBy + const sections = drafts + .sort(byUrgencyThenRecent) + .map((draft) => + kind === 'agent' + ? section(draft, kind, 'workspace', nameDesktop) + : section(draft, kind, kind === 'workspace' ? 'agent' : 'workspace', false) + ) + return { sections, anyLive } +} + +/** Every row the list holds, folded ones included, once each: what "Mark all read" and "Clear finished" act on. */ +export function agentListRowsIn(sections: readonly AgentListSection[]): AgentListRow[] { + const rows = new Map() + for (const section of sections) { + for (const row of everyRow([...section.rows, ...(section.idleRows ?? [])])) { + rows.set(row.key, row) + } + } + return [...rows.values()] +} diff --git a/mobile/src/agents/agent-list-preferences.ts b/mobile/src/agents/agent-list-preferences.ts new file mode 100644 index 00000000000..c3e0aaf5729 --- /dev/null +++ b/mobile/src/agents/agent-list-preferences.ts @@ -0,0 +1,35 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import { + AGENT_LIST_GROUP_BY_CHOICES, + DEFAULT_AGENT_LIST_VIEW, + type AgentListView +} from './agent-list-model' + +const AGENT_LIST_VIEW_KEY = 'orca:agentListView' + +export async function loadAgentListView(): Promise { + try { + const raw = await AsyncStorage.getItem(AGENT_LIST_VIEW_KEY) + const parsed: unknown = raw ? JSON.parse(raw) : null + if (!parsed || typeof parsed !== 'object') { + return DEFAULT_AGENT_LIST_VIEW + } + const groupBy = 'groupBy' in parsed ? parsed.groupBy : undefined + const showWorkers = 'showWorkers' in parsed ? parsed.showWorkers : undefined + const unreadOnly = 'unreadOnly' in parsed ? parsed.unreadOnly : undefined + return { + groupBy: + AGENT_LIST_GROUP_BY_CHOICES.find((choice) => choice === groupBy) ?? + DEFAULT_AGENT_LIST_VIEW.groupBy, + showWorkers: + typeof showWorkers === 'boolean' ? showWorkers : DEFAULT_AGENT_LIST_VIEW.showWorkers, + unreadOnly: typeof unreadOnly === 'boolean' ? unreadOnly : DEFAULT_AGENT_LIST_VIEW.unreadOnly + } + } catch { + return DEFAULT_AGENT_LIST_VIEW + } +} + +export async function saveAgentListView(view: AgentListView): Promise { + await AsyncStorage.setItem(AGENT_LIST_VIEW_KEY, JSON.stringify(view)) +} diff --git a/mobile/src/agents/agent-list-row-text.ts b/mobile/src/agents/agent-list-row-text.ts new file mode 100644 index 00000000000..c3e9d8ef8b7 --- /dev/null +++ b/mobile/src/agents/agent-list-row-text.ts @@ -0,0 +1,63 @@ +import { getAgentRowPrimaryText } from '../../../src/shared/agent-status/presentation/agent-row-primary-text' +import { formatAgentToolPreviewLine } from '../../../src/shared/agent-status/presentation/agent-tool-preview' +import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' +import { withoutNativeChatVisualDirectiveLines } from '../../../src/shared/native-chat/native-chat-visual-directive' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { HomeAgentEntry } from '../worktree/home-worktree-info' +import type { AgentStatusGroup } from './agent-list-rows' + +/** The row's name: what the conversation is called, else its task, else what it was asked. */ +export function agentListTitle(agent: RuntimeWorktreeAgentRow): string { + return ( + agent.conversationName?.trim() || + agent.displayName?.trim() || + agent.taskTitle?.trim() || + getAgentRowPrimaryText({ prompt: agent.prompt }) || + formatAgentTypeLabel(agent.agentType) + ) +} + +function oneLine(text: string | null | undefined): string { + return text?.replace(/\s+/g, ' ').trim() ?? '' +} + +function lastMessage(agent: RuntimeWorktreeAgentRow): string { + const message = agent.lastAssistantMessage + return message ? oneLine(withoutNativeChatVisualDirectiveLines(message)) : '' +} + +/** + * The row's second line: what it waits on or is doing, else what it last said. A last-seen row + * (`group` null) shows no tool, since the tool call is long over. + */ +export function agentListPreview( + agent: RuntimeWorktreeAgentRow, + group: AgentStatusGroup | null, + title: string +): string { + const tool = group === null ? '' : oneLine(formatAgentToolPreviewLine(agent, false)) + const preview = + group === 'needs-you' || group === 'working' + ? tool || lastMessage(agent) + : lastMessage(agent) || tool + if (preview) { + return preview + } + const prompt = oneLine(getAgentRowPrimaryText({ prompt: agent.prompt })) + return prompt === title ? '' : prompt +} + +/** Search covers what the row shows plus the prompt; `query` is already lower-cased. */ +export function agentListEntryMatches(entry: HomeAgentEntry, query: string): boolean { + const { agent } = entry + return [ + agentListTitle(agent), + agent.activity?.listed === true ? agent.activity.title : null, + entry.workspaceName, + entry.branch, + entry.repo, + formatAgentTypeLabel(agent.agentType), + agent.prompt, + agent.lastAssistantMessage + ].some((field) => field?.toLowerCase().includes(query)) +} diff --git a/mobile/src/agents/agent-list-rows.ts b/mobile/src/agents/agent-list-rows.ts new file mode 100644 index 00000000000..a9490a5929b --- /dev/null +++ b/mobile/src/agents/agent-list-rows.ts @@ -0,0 +1,190 @@ +import { + AGENT_LIST_STATUS_RANK, + type AgentListVerdict +} from '../../../src/shared/agent-status/presentation/agent-list-status' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { ConnectionState } from '../transport/connection/connection-state' +import { agentDotState, agentRowTimeAt, type AgentDotState } from '../worktree/agent-row-display' +import { flattenAgentRowLineage, type AgentRowNode } from '../worktree/agent-row-lineage' +import type { HomeAgentEntry, HostWorktreeInfo } from '../worktree/home-worktree-info' +import { agentListTitle } from './agent-list-row-text' + +export type AgentStatusGroup = 'needs-you' | 'working' | 'done' | 'idle' + +/** Desktop's status ranks cut into sections: everything ranked above live work needs the user. */ +export function agentStatusGroup(state: AgentDotState): AgentStatusGroup { + const rank = AGENT_LIST_STATUS_RANK[state] + if (rank < AGENT_LIST_STATUS_RANK.working) { + return 'needs-you' + } + if (rank <= AGENT_LIST_STATUS_RANK.monitoring) { + return 'working' + } + return state === 'idle' ? 'idle' : 'done' +} + +export type ListedAgentVerdict = Extract + +/** The desktop Agents list's row for this agent; undefined when the host sent no verdict. */ +export function listedAgentVerdict(agent: RuntimeWorktreeAgentRow): ListedAgentVerdict | undefined { + return agent.activity?.listed === true ? agent.activity : undefined +} + +export type AgentListRow = Readonly<{ + key: string + hostId: string + entry: HomeAgentEntry + title: string + dotState: AgentDotState + timeAt: number + /** A copy from a read the desktop no longer backs: it claims no state. */ + stale: boolean + /** Its desktop isn't connected, so the row can't open. */ + offline: boolean + /** The desktop's read verdict; undefined when it gave none, so the phone claims nothing. */ + unread?: boolean + /** A finished turn the desktop can clear from its Agents list. */ + clearable: boolean + depth: number + /** Nested workers in tree order; empty when workers are hidden. */ + workers: readonly AgentListRow[] +}> + +export type AgentListInput = Readonly<{ + /** Paired desktops in Home's order. */ + hosts: readonly { id: string }[] + hostStates: Readonly> + worktreeInfo: Readonly> + now: number + /** Writes sent but not yet read back, by row key. */ + pendingActivity?: Readonly> +}> + +/** A read or clear the phone asked its desktop for. */ +export type AgentActivityChange = Readonly<{ unread: boolean } | { cleared: true }> + +export function agentListRowKey(hostId: string, paneKey: string): string { + return `${hostId}:${paneKey}` +} + +export type HostAgents = { + hostId: string + roots: AgentListRow[] + live: boolean + offline: boolean + seenAt?: number +} + +export function hostAgents(input: AgentListInput, hostId: string): HostAgents { + const info = input.worktreeInfo[hostId] + const connected = input.hostStates[hostId] === 'connected' + // Only this connection's own read may show states; anything else is what the agents last were. + const liveAgents = connected && !info?.catalogUnavailable ? info?.agents : undefined + const live = liveAgents !== undefined + const pending = (paneKey: string) => input.pendingActivity?.[agentListRowKey(hostId, paneKey)] + // Only what the desktop lists, less what the phone just cleared; a cleared agent's workers stay, as roots. + const entries = (liveAgents ?? info?.lastSeenAgents ?? info?.agents ?? []).filter((entry) => { + const change = pending(entry.agent.paneKey) + return entry.agent.activity?.listed !== false && !(change && 'cleared' in change) + }) + const entryByPaneKey = new Map(entries.map((entry) => [entry.agent.paneKey, entry])) + const toRow = (node: AgentRowNode, depth: number): AgentListRow | null => { + const entry = entryByPaneKey.get(node.row.paneKey) + if (!entry) { + return null + } + const { agent } = entry + const verdict = listedAgentVerdict(agent) + const liveVerdict = live ? verdict : undefined + const change = pending(agent.paneKey) + return { + key: agentListRowKey(hostId, agent.paneKey), + hostId, + entry, + title: verdict?.title.trim() || agentListTitle(agent), + dotState: !live ? 'idle' : verdict ? verdict.status : agentDotState(agent, input.now), + timeAt: verdict?.sortAt ?? agentRowTimeAt(agent), + stale: !live, + offline: !connected, + // Read state is the desktop's call; a host that sends none gets no bell and no actions. + unread: liveVerdict + ? change && 'unread' in change + ? change.unread + : liveVerdict.unread + : undefined, + clearable: liveVerdict?.clearable === true, + depth, + workers: node.children.flatMap((child) => descendants(child, depth + 1)) + } + } + const descendants = (node: AgentRowNode, depth: number): AgentListRow[] => { + const row = toRow(node, depth) + return row ? [{ ...row, workers: [] }, ...row.workers] : [] + } + // Lineage spans the desktop: a coordinator's workers often run in other workspaces. Desktop's + // own nesting wins where it gave a verdict. + const lineage = entries.map(({ agent }) => { + const verdict = listedAgentVerdict(agent) + return verdict ? { ...agent, parentPaneKey: verdict.childOf ?? null } : agent + }) + const roots = flattenAgentRowLineage(lineage) + .filter((node) => node.depth === 0) + .map((node) => toRow(node, 0)) + .filter((row): row is AgentListRow => row !== null) + return { hostId, roots, live, offline: !connected, seenAt: info?.countsProvenAt } +} + +export function everyRow(roots: readonly AgentListRow[]): AgentListRow[] { + return roots.flatMap((row) => [row, ...row.workers]) +} + +export const asTopLevel = (row: AgentListRow): AgentListRow => ({ ...row, depth: 0, workers: [] }) + +export const newestFirst = (a: AgentListRow, b: AgentListRow): number => b.timeAt - a.timeAt + +/** Desktop's status order, newest first within a status. */ +export const byStatusThenRecent = (a: AgentListRow, b: AgentListRow): number => + AGENT_LIST_STATUS_RANK[a.dotState] - AGENT_LIST_STATUS_RANK[b.dotState] || newestFirst(a, b) + +export function rowNeedsYou(row: AgentListRow): boolean { + return !row.stale && agentStatusGroup(row.dotState) === 'needs-you' +} + +/** Live agents that need the user, workers included: Feed's rows and both badge counts. */ +export function selectAgentsNeedingYou(input: AgentListInput): AgentListRow[] { + return input.hosts + .flatMap((host) => everyRow(hostAgents(input, host.id).roots)) + .filter(rowNeedsYou) + .map(asTopLevel) + .sort(byStatusThenRecent) +} + +export function countAgentsNeedingYouByHost( + rows: readonly AgentListRow[] +): Readonly> { + const counts: Record = {} + for (const row of rows) { + counts[row.hostId] = (counts[row.hostId] ?? 0) + 1 + } + return counts +} + +export type AgentListHostSummary = Readonly<{ + hostId: string + agents: number + needsYou: number + offline: boolean +}> + +export function summarizeAgentListHosts(input: AgentListInput): AgentListHostSummary[] { + return input.hosts.map((host) => { + const agents = hostAgents(input, host.id) + const rows = everyRow(agents.roots) + return { + hostId: host.id, + agents: rows.length, + needsYou: rows.filter(rowNeedsYou).length, + offline: agents.offline + } + }) +} diff --git a/mobile/src/agents/use-agent-activity-writes.ts b/mobile/src/agents/use-agent-activity-writes.ts new file mode 100644 index 00000000000..2adc52d6718 --- /dev/null +++ b/mobile/src/agents/use-agent-activity-writes.ts @@ -0,0 +1,133 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { z } from 'zod' +import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' +import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { AgentActivityChange, AgentListRow } from './agent-list-rows' + +// The host's bound on one request's pane keys. +const PANE_KEYS_PER_REQUEST = 500 +const applied = rpcResultVariant('applied', z.object({ applied: z.literal(true) })) + +const agentActivitySetReadWrite = bindDeferredRpcOperation( + defineRpcOperation({ + name: 'agentActivity.mobile-set-read', + method: 'agentActivity.setRead', + acceptance: 'require-result-or-throw', + barrier: 'after-caller-barrier', + read: applied + }) +) +const agentActivityClearWrite = bindDeferredRpcOperation( + defineRpcOperation({ + name: 'agentActivity.mobile-clear', + method: 'agentActivity.clear', + acceptance: 'require-result-or-throw', + barrier: 'after-caller-barrier', + read: applied + }) +) + +export type AgentActivityFailure = Readonly<{ hostId: string; needsDesktopWindow: boolean }> + +async function sendAgentActivity( + client: RpcClient, + paneKeys: string[], + change: AgentActivityChange +): Promise { + for (let start = 0; start < paneKeys.length; start += PANE_KEYS_PER_REQUEST) { + const chunk = paneKeys.slice(start, start + PANE_KEYS_PER_REQUEST) + if ('cleared' in change) { + agentActivityClearWrite.interpret( + await agentActivityClearWrite.request(client, { paneKeys: chunk }) + ) + } else { + agentActivitySetReadWrite.interpret( + await agentActivitySetReadWrite.request(client, { paneKeys: chunk, read: !change.unread }) + ) + } + } +} + +/** + * Sends read and clear changes to each row's desktop, showing them until that desktop's next + * list read carries them; a refused write rolls back to the desktop's list and reports which + * desktop refused. + */ +export function useAgentActivityWrites( + clients: readonly { hostId: string; client: RpcClient }[], + refetchHost: (hostId: string) => Promise +) { + const [pending, setPending] = useState< + Readonly> + >({}) + const tokenRef = useRef(0) + const clientsRef = useRef(clients) + useEffect(() => { + clientsRef.current = clients + }, [clients]) + + const apply = useCallback( + async ( + rows: readonly AgentListRow[], + change: AgentActivityChange + ): Promise => { + tokenRef.current += 1 + const token = tokenRef.current + const paneKeysByHost = new Map() + for (const row of rows) { + paneKeysByHost.set(row.hostId, [ + ...(paneKeysByHost.get(row.hostId) ?? []), + row.entry.agent.paneKey + ]) + } + setPending((previous) => ({ + ...previous, + ...Object.fromEntries(rows.map((row) => [row.key, { change, token }])) + })) + const settle = (hostId: string) => + setPending((previous) => + Object.fromEntries( + Object.entries(previous).filter( + ([key, entry]) => entry.token !== token || !key.startsWith(`${hostId}:`) + ) + ) + ) + const outcomes = await Promise.all( + [...paneKeysByHost].map( + async ([hostId, paneKeys]): Promise => { + try { + const client = clientsRef.current.find((entry) => entry.hostId === hostId)?.client + if (!client) { + throw new Error('desktop not connected') + } + await sendAgentActivity(client, paneKeys, change) + // The host's next list already carries the change; hold the guess until it lands. + await refetchHost(hostId) + return null + } catch (error) { + // A timeout or a partial batch may still have applied; roll back to what the desktop has. + await refetchHost(hostId) + return { + hostId, + needsDesktopWindow: + error instanceof Error && + error.message.includes('agent_activity_needs_desktop_window') + } + } finally { + settle(hostId) + } + } + ) + ) + return outcomes.filter((outcome): outcome is AgentActivityFailure => outcome !== null) + }, + [refetchHost] + ) + + const pendingActivity = useMemo( + () => Object.fromEntries(Object.entries(pending).map(([key, entry]) => [key, entry.change])), + [pending] + ) + return { pendingActivity, apply } +} diff --git a/mobile/src/agents/use-agent-list-row-actions.tsx b/mobile/src/agents/use-agent-list-row-actions.tsx new file mode 100644 index 00000000000..dcd191a4b6c --- /dev/null +++ b/mobile/src/agents/use-agent-list-row-actions.tsx @@ -0,0 +1,160 @@ +import { ArrowUpRight, Copy, Eye, EyeOff, Folder, X } from 'lucide-react-native' +import { useCallback, useMemo, useState } from 'react' +import { Alert } from 'react-native' +import { ActionSheetModal, type ActionSheetAction } from '../components/ActionSheetModal' +import { TransientToast, useTransientToast } from '../components/TransientToast' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { useClipboardWriter } from '../platform/clipboard' +import { useOpenMobileSession } from '../session/use-open-mobile-session' +import type { HostProfile } from '../transport/hosts/host-profile' +import type { AgentActivityChange, AgentListRow } from './agent-list-rows' +import type { AgentListRowHandlers } from './MobileAgentListRows' +import type { AgentActivityFailure } from './use-agent-activity-writes' + +/** + * Tap opens the agent's tab and marks it read; long-press offers it, its workspace, its title and + * the desktop's read and clear. Shared by Feed and Agents. + */ +export function useAgentListRowActions( + toastBottomInset: number, + hosts: readonly HostProfile[], + applyActivity: ( + rows: readonly AgentListRow[], + change: AgentActivityChange + ) => Promise +) { + const t = useMobileTranslation() + const openMobileSession = useOpenMobileSession() + const clipboard = useClipboardWriter() + const { message, showToast } = useTransientToast() + const [target, setTarget] = useState(null) + + const open = useCallback( + (row: AgentListRow, withPane: boolean) => + openMobileSession({ + hostId: row.hostId, + worktreeId: row.entry.worktreeId, + name: row.entry.workspaceName, + ...(withPane ? { paneKey: row.entry.agent.paneKey } : {}) + }), + [openMobileSession] + ) + const change = useCallback( + (rows: readonly AgentListRow[], next: AgentActivityChange) => { + if (rows.length === 0) { + return + } + void applyActivity(rows, next).then((failures) => { + const failure = failures[0] + if (!failure) { + return + } + const desktop = hosts.find((host) => host.id === failure.hostId)?.name + showToast( + failure.needsDesktopWindow && desktop + ? t('agents.activity.needsWindow', 'Couldn’t update. Open Orca on {{desktop}}.', { + desktop + }) + : t('agents.activity.failed', 'Couldn’t update the agent list.') + ) + }) + }, + [applyActivity, hosts, showToast, t] + ) + const handlers = useMemo( + () => ({ + onOpen: (row) => { + // Like desktop opening a pane; a refusal here isn't worth interrupting the open. + if (row.unread) { + void applyActivity([row], { unread: false }) + } + open(row, true) + }, + onLongPress: setTarget, + // Only rows the desktop gave a verdict for; the phone never invents read state. + onSetRead: (rows, read) => + change( + rows.filter((row) => row.unread !== undefined), + { unread: !read } + ), + onClear: (rows) => + change( + rows.filter((row) => row.clearable), + { cleared: true } + ) + }), + [applyActivity, change, open] + ) + + const title = target?.title + const offlineHint = target?.offline + ? t('agents.actions.offlineHint', 'Its desktop is offline.') + : undefined + const actions = (row: AgentListRow): ActionSheetAction[] => [ + { + id: 'open', + label: t('agents.actions.open', 'Open'), + icon: ArrowUpRight, + disabled: row.offline, + hint: offlineHint, + closeBeforePress: true, + onPress: () => handlers.onOpen(row) + }, + { + id: 'workspace', + label: t('agents.actions.goToWorkspace', 'Go to workspace'), + icon: Folder, + disabled: row.offline, + hint: offlineHint, + closeBeforePress: true, + onPress: () => open(row, false) + }, + ...(row.unread === undefined + ? [] + : [ + { + id: 'read', + label: row.unread + ? t('agents.actions.markRead', 'Mark as read') + : t('agents.actions.markUnread', 'Mark as unread'), + icon: row.unread ? Eye : EyeOff, + onPress: () => handlers.onSetRead([row], row.unread === true) + } + ]), + { + id: 'copy-title', + label: t('agents.actions.copyTitle', 'Copy title'), + icon: Copy, + closeBeforePress: true, + onPress: () => { + void clipboard.writeText(title ?? '').then( + () => showToast(t('agents.actions.copied', 'Copied')), + () => Alert.alert(t('agents.actions.copyFailed', 'Couldn’t copy the title')) + ) + } + }, + ...(row.clearable + ? [ + { + id: 'clear', + label: t('agents.actions.clear', 'Clear from list'), + icon: X, + onPress: () => handlers.onClear([row]) + } + ] + : []) + ] + const sheet = ( + <> + setTarget(null)} + /> + + + ) + return { handlers, sheet } +} diff --git a/mobile/src/cache/worktree-cache.test.ts b/mobile/src/cache/worktree-cache.test.ts index fc47972a2a8..4c076eb4e08 100644 --- a/mobile/src/cache/worktree-cache.test.ts +++ b/mobile/src/cache/worktree-cache.test.ts @@ -1,68 +1,15 @@ import { describe, expect, it } from 'vitest' -import { setCachedWorktrees, getCachedWorktrees, getProvenCachedWorktrees } from './worktree-cache' +import { setCachedWorktrees, getCachedWorktrees } from './worktree-cache' -// Pin reconnect write-through to cache seeded by host detail (#8498), preventing stale reconnect snapshots. -describe('worktree-cache write-through', () => { - it('returns the most-recently written snapshot, not a stale one', () => { - const hostId = 'host-write-through' - const stale = [{ worktreeId: 'a', name: 'stale' }] - const fresh = [ - { worktreeId: 'a', name: 'fresh' }, - { worktreeId: 'b', name: 'added' } - ] - - setCachedWorktrees(hostId, stale) - expect(getCachedWorktrees(hostId)).toEqual(stale) - - // Reconnect write-through must fully replace poisoned cache. - setCachedWorktrees(hostId, fresh) - expect(getCachedWorktrees(hostId)).toEqual(fresh) - expect(getCachedWorktrees(hostId)).not.toEqual(stale) - }) -}) - -// Only live worktree.ps can prove absence for Resume redirects; persisted cold-start seeds must never be authoritative (F7). +// A persisted cold-start seed must not truncate the rows a live worktree.ps listed. describe('worktree-cache provenance', () => { - it('withholds unmarked writes from the proven reader', () => { - const hostId = 'host-seeded' - const seeded = [{ worktreeId: 'a' }] - - setCachedWorktrees(hostId, seeded) - - expect(getCachedWorktrees(hostId)).toEqual(seeded) - expect(getProvenCachedWorktrees(hostId)).toBeNull() - }) - - it('exposes a host-listed catalog to the proven reader', () => { - const hostId = 'host-proven' - const listed = [{ worktreeId: 'a' }, { worktreeId: 'b' }] - - setCachedWorktrees(hostId, listed, { proven: true }) - - expect(getProvenCachedWorktrees(hostId)).toEqual(listed) - }) - - it('keeps a fresh proven catalog when an unproven seed lands after it', () => { + it('keeps a fresh host-listed catalog when a cold-start seed lands after it', () => { const hostId = 'host-kept' const listed = [{ worktreeId: 'a' }, { worktreeId: 'b' }] setCachedWorktrees(hostId, listed, { proven: true }) - // A cold-start snapshot seed must neither truncate nor de-prove the host-listed rows. setCachedWorktrees(hostId, [{ worktreeId: 'a' }]) - expect(getProvenCachedWorktrees(hostId)).toEqual(listed) - }) - - it('lets an unproven seed replace another unproven entry', () => { - const hostId = 'host-reseeded' - setCachedWorktrees(hostId, [{ worktreeId: 'a' }]) - setCachedWorktrees(hostId, [{ worktreeId: 'b' }]) - - expect(getCachedWorktrees(hostId)).toEqual([{ worktreeId: 'b' }]) - expect(getProvenCachedWorktrees(hostId)).toBeNull() - }) - - it('reports nothing proven for a host it has never cached', () => { - expect(getProvenCachedWorktrees('host-never-seen')).toBeNull() + expect(getCachedWorktrees(hostId)).toEqual(listed) }) }) diff --git a/mobile/src/cache/worktree-cache.ts b/mobile/src/cache/worktree-cache.ts index 2b7c8900782..ad05d45c98e 100644 --- a/mobile/src/cache/worktree-cache.ts +++ b/mobile/src/cache/worktree-cache.ts @@ -3,7 +3,7 @@ type CachedWorktrees = { worktrees: unknown[] at: number - // Only live host-listed rows can prove absence; persisted cold-start seeds cannot. + // Live host-listed rows; a persisted cold-start seed must not replace them. proven: boolean } @@ -17,13 +17,12 @@ export function setCachedWorktrees( worktrees: unknown[], options?: { proven?: boolean } ): void { - // Late cold-start seed must neither erase proof nor truncate live host-listed rows used by Resume. + // A late cold-start seed must not truncate live host-listed rows. if (options?.proven !== true && readFreshEntry(hostId)?.proven) { return } // Delete before Map.set to move key to newest position for LRU eviction. cache.delete(hostId) - // Default unproven: unknown row origin cannot justify redirecting user from workspace. cache.set(hostId, { worktrees, at: Date.now(), proven: options?.proven === true }) if (cache.size > MAX_ENTRIES) { const oldest = cache.keys().next().value @@ -37,12 +36,6 @@ export function getCachedWorktrees(hostId: string): unknown[] | null { return readFreshEntry(hostId)?.worktrees ?? null } -// Return live host-listed rows only; expired/unproven entries cannot establish absence. -export function getProvenCachedWorktrees(hostId: string): unknown[] | null { - const entry = readFreshEntry(hostId) - return entry?.proven ? entry.worktrees : null -} - function readFreshEntry(hostId: string): CachedWorktrees | null { const entry = cache.get(hostId) if (!entry) { diff --git a/mobile/src/components/AgentLaunchNotice.test.tsx b/mobile/src/components/AgentLaunchNotice.test.tsx deleted file mode 100644 index 90305675274..00000000000 --- a/mobile/src/components/AgentLaunchNotice.test.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { createElement, type ReactNode } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('react-native', async () => { - const React = await import('react') - return { - Pressable: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Pressable', props, children), - Text: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('Text', props, children), - View: ({ children, ...props }: { children?: ReactNode }) => - React.createElement('View', props, children), - StyleSheet: { create: (styles: unknown) => styles } - } -}) -vi.mock('../platform/clipboard', () => ({ - useClipboardWriter: () => ({ writeText: async () => {} }) -})) - -import { AgentLaunchNotice } from './AgentLaunchNotice' - -import type { MobileAgentLaunchAvailability } from '../session/agent-launch/mobile-agent-launch-availability' - -const ERROR_STYLE = { color: 'red' } - -describe('AgentLaunchNotice', () => { - let renderer: ReactTestRenderer | null = null - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - function lines(props: { - availability?: MobileAgentLaunchAvailability - success?: string | null - error?: string | null - warning?: string | null - }): { text: string; isError: boolean }[] { - act(() => { - renderer = create( - createElement(AgentLaunchNotice, { - availability: props.availability ?? 'available', - success: props.success ?? null, - error: props.error ?? null, - warning: props.warning ?? null, - undeliveredPrompt: null, - errorStyle: ERROR_STYLE - }) - ) - }) - return (renderer?.root.findAll((node) => String(node.type) === 'Text') ?? []).map((node) => ({ - text: String(node.props.children), - isError: node.props.style === ERROR_STYLE - })) - } - - it('renders nothing with nothing to say', () => { - expect(lines({})).toEqual([]) - }) -}) diff --git a/mobile/src/components/AgentStateDot.tsx b/mobile/src/components/AgentStateDot.tsx index f9c67d3a3cf..bfa48b0a068 100644 --- a/mobile/src/components/AgentStateDot.tsx +++ b/mobile/src/components/AgentStateDot.tsx @@ -17,6 +17,7 @@ const dotColors = (): Record< done: '#10b981', blocked: '#ef4444', waiting: '#ef4444', + permission: '#ef4444', interrupted: colors.textMuted, failed: '#ef4444', unconfirmed: colors.statusAmber, diff --git a/mobile/src/components/SwipeRowActions.tsx b/mobile/src/components/SwipeRowActions.tsx new file mode 100644 index 00000000000..704077f636d --- /dev/null +++ b/mobile/src/components/SwipeRowActions.tsx @@ -0,0 +1,151 @@ +import type { LucideIcon } from 'lucide-react-native' +import type { ReactNode } from 'react' +import { Pressable, Text, View } from 'react-native' +import { Gesture, GestureDetector } from 'react-native-gesture-handler' +import Animated, { + Easing, + ReduceMotion, + useAnimatedStyle, + useSharedValue, + withTiming +} from 'react-native-reanimated' +import { feedback, typography } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { useDrawerReducedMotion } from './bottom-drawer/bottom-drawer-constants' +import { SHEET_CURVE } from './sheet-motion-values' + +// The width an action uncovers; a swipe past half of it settles open. +const ACTION_WIDTH = 84 +const SWIPE_SETTLE_MS = 250 +const DRAG_CLICK_WINDOW_MS = 400 + +export type SwipeRowAction = { + label: string + accessibilityLabel: string + icon: LucideIcon + background: string + foreground: string + onPress: () => void +} + +/** + * A row that slides to uncover an action: `leading` behind a right swipe, `trailing` behind a left + * one. Tapping the uncovered action runs it. Rows without either action render as they are; + * gaining or losing both remounts the row. + */ +export function SwipeRowActions({ + leading, + trailing, + enabled = true, + children +}: { + leading?: SwipeRowAction + trailing?: SwipeRowAction + enabled?: boolean + /** Gets a wrapper for the row's press: a tap on a swiped row closes it instead. */ + children: (guardPress: (onPress: () => void) => () => void) => ReactNode +}) { + useMobileColorScheme() + const reducedMotion = useDrawerReducedMotion() + const offset = useSharedValue(0) + const start = useSharedValue(0) + // When the last drag ended: on the web, releasing a mouse drag also clicks the row. + const dragEndedAt = useSharedValue(0) + const maxRight = leading ? ACTION_WIDTH : 0 + const maxLeft = trailing ? -ACTION_WIDTH : 0 + // Built per render: a module-level easing would run before a test's Reanimated mock can serve it. + const settle = (to: number) => { + 'worklet' + return withTiming( + to, + reducedMotion + ? { duration: 0, reduceMotion: ReduceMotion.Never } + : { duration: SWIPE_SETTLE_MS, easing: Easing.bezier(...SHEET_CURVE) } + ) + } + // Horizontal only, so the list keeps scrolling under a vertical drag. + const pan = Gesture.Pan() + .enabled(enabled) + .activeOffsetX([-12, 12]) + .failOffsetY([-10, 10]) + .onBegin(() => { + start.value = offset.value + }) + .onUpdate((event) => { + offset.value = Math.min(maxRight, Math.max(maxLeft, start.value + event.translationX)) + }) + .onEnd(() => { + // oxlint-disable-next-line react/purity -- runs when the drag ends, never during render. + dragEndedAt.value = Date.now() + offset.value = settle( + offset.value > ACTION_WIDTH / 2 ? maxRight : offset.value < -ACTION_WIDTH / 2 ? maxLeft : 0 + ) + }) + // Web has no worklet plugin; mapper hooks need this explicit dependency list. + const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }), [offset]) + // A tap on an open row closes it rather than pressing the row. + const guardPress = (onPress: () => void) => () => { + // The click a drag release produces belongs to the drag, not to the row. + if (Date.now() - dragEndedAt.value < DRAG_CLICK_WINDOW_MS) { + return + } + if (offset.value !== 0) { + offset.value = settle(0) + return + } + onPress() + } + if (!leading && !trailing) { + return children((onPress) => onPress) + } + const renderAction = (action: SwipeRowAction, side: 'leading' | 'trailing') => { + const Icon = action.icon + return ( + [ + styles.action, + side === 'leading' ? styles.leading : styles.trailing, + { backgroundColor: action.background }, + pressed && styles.actionPressed + ]} + disabled={!enabled} + onPress={() => { + offset.value = settle(0) + action.onPress() + }} + accessibilityRole="button" + accessibilityLabel={action.accessibilityLabel} + > + + {action.label} + + ) + } + return ( + + {leading ? renderAction(leading, 'leading') : null} + {trailing ? renderAction(trailing, 'trailing') : null} + {/* pan-y keeps the page scrolling vertically over the row on the web. */} + + {children(guardPress)} + + + ) +} + +const styles = themedStyleSheet(() => ({ + action: { + position: 'absolute', + top: 0, + bottom: 0, + width: ACTION_WIDTH, + alignItems: 'center', + justifyContent: 'center', + gap: 2 + }, + leading: { left: 0 }, + trailing: { right: 0 }, + actionPressed: { opacity: feedback.pressedOpacity }, + actionText: { fontSize: typography.metaSize, fontWeight: '600' } +})) diff --git a/mobile/src/components/mobile-markdown-visual-lines.test.ts b/mobile/src/components/mobile-markdown-visual-lines.test.ts index b7380d337f5..62dd3318518 100644 --- a/mobile/src/components/mobile-markdown-visual-lines.test.ts +++ b/mobile/src/components/mobile-markdown-visual-lines.test.ts @@ -69,20 +69,6 @@ describe('native-chat visual lines in mobile markdown', () => { expect(directives).toEqual([{ file: 'after.html', title: null }]) }) - it('leaves malformed or path-like directives as literal text', () => { - for (const line of [ - '::orca-visual{file="../secret.html"}', - '::orca-visual{file="a.html" file="b.html"}', - '::orca-visual{file="a.htm"}', - '::orca-visual{file="a.html"', - '::orca-visual{file="a.html"} trailing words' - ]) { - const { directives, blocks } = blocksOf(line) - expect(directives, line).toEqual([]) - expect(blocks, line).toEqual([{ type: 'paragraph', text: line }]) - } - }) - it('renders directives past the per-message cap as text', () => { const lines = Array.from( { length: NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE + 1 }, diff --git a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts b/mobile/src/components/pr-sidebar/pr-actions-state.test.ts index ea067a09a8c..dfc489ea490 100644 --- a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts +++ b/mobile/src/components/pr-sidebar/pr-actions-state.test.ts @@ -21,14 +21,6 @@ describe('presentPrMerge', () => { mergeable: 'MERGEABLE' as const } - it('disables Merge with desktop copy when GitHub reports conflicts', () => { - expect(presentPrMerge(pr, 'squash')).toMatchObject({ - enabled: false, - label: 'Conflicts', - hint: 'GitHub reports merge conflicts' - }) - }) - it('lets a complete stack merge through, and names a blocking downstack PR', () => { const stack = { number: 51, diff --git a/mobile/src/components/use-connected-host-picker.test.ts b/mobile/src/components/use-connected-host-picker.test.ts index 76831119827..40e23a8f684 100644 --- a/mobile/src/components/use-connected-host-picker.test.ts +++ b/mobile/src/components/use-connected-host-picker.test.ts @@ -50,41 +50,6 @@ describe('useConnectedHostPicker', () => { act(() => handle.current!.pickHost(action, hosts)) } - it('runs the action on the only offered host without a picker', () => { - render([desk, laptop]) - const action = vi.fn() - - pickHost(action, [laptop]) - - expect(action).toHaveBeenCalledWith('laptop') - expect(picker().visible).toBe(false) - }) - - it('offers only the hosts passed in', () => { - render([desk, laptop, server]) - const action = vi.fn() - - pickHost(action, [desk, server]) - - expect(picker().visible).toBe(true) - expect(picker().options.map((option) => option.value)).toEqual(['desk', 'server']) - act(() => picker().onSelect('server')) - act(() => picker().onAfterClose()) - expect(action).toHaveBeenCalledWith('server') - }) - - it('runs nothing when the picker is dismissed', () => { - render([desk, laptop]) - const action = vi.fn() - - pickHost(action) - act(() => picker().onClose()) - act(() => picker().onAfterClose()) - - expect(picker().visible).toBe(false) - expect(action).not.toHaveBeenCalled() - }) - it('disambiguates path-routed hosts without exposing endpoint paths', () => { render([ host('desk-a', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-a'), diff --git a/mobile/src/diagnostics/connection-diagnostics-relay-dial.test.ts b/mobile/src/diagnostics/connection-diagnostics-relay-dial.test.ts deleted file mode 100644 index fd49007585a..00000000000 --- a/mobile/src/diagnostics/connection-diagnostics-relay-dial.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getReportableConnectionIncidentId } from './connection-diagnostics-analysis' -import type { ConnectionLogEntry } from './connection/connection-log-types' - -// Reproduce a 0.0.50 phone / 1.4.203 host export (2026-09-18): relay dials failed 4404, LAN timed out, and a resume before export erased the reported cause. - -const ENDPOINT = 'ws://192.168.1.2:55927' -let sequence = 0 - -function entry(fields: Omit): ConnectionLogEntry { - sequence += 1 - return { id: `export-${sequence}`, ts: Date.parse('2026-09-18T22:44:00Z') + sequence, ...fields } -} - -const appResumed = () => - entry({ - level: 'info', - code: 'app-resumed', - message: 'App returned to foreground', - detail: 'Connection recovery notified' - }) - -const lanOpening = () => - entry({ level: 'info', path: 'lan', message: 'Opening WebSocket', detail: '192.168.1.2:55927' }) - -const relayDialFailed = (closeCode: number) => - entry({ - level: 'error', - code: 'relay-dial-failed', - path: 'relay', - message: 'Relay: relay dial failed', - detail: `Error: relay_outer_${closeCode}`, - relayCloseCode: closeCode - }) - -const lanConnectTimeout = () => - entry({ - level: 'error', - code: 'connect-timeout', - path: 'lan', - message: 'WebSocket connect timeout', - detail: 'No TCP/WS handshake within 12s — endpoint unreachable?' - }) - -const retryScheduled = () => - entry({ - level: 'info', - code: 'retry-scheduled', - path: 'lan', - message: 'Reconnect scheduled in 500ms', - detail: 'Attempt 1' - }) - -function resumeWindow(closeCode: number): ConnectionLogEntry[] { - return [ - appResumed(), - lanOpening(), - relayDialFailed(closeCode), - lanConnectTimeout(), - retryScheduled() - ] -} - -describe('diagnoseConnection on the relay-4404 export', () => { - // The export ends before a new outcome, so the latest evidence predates resume. - const CUT_MID_WINDOW = [...resumeWindow(4404), ...resumeWindow(4404), appResumed(), lanOpening()] - - // The later LAN timeout only means the phone is off LAN; it must not outrank the relay verdict. - - it('is never a sendable relay incident', () => { - expect( - getReportableConnectionIncidentId({ - endpoint: ENDPOINT, - state: 'connecting', - entries: CUT_MID_WINDOW - }) - ).toBeNull() - expect( - getReportableConnectionIncidentId({ - endpoint: ENDPOINT, - state: 'connecting', - entries: resumeWindow(4404) - }) - ).toBeNull() - }) -}) diff --git a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts b/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts index fd988ad7b72..3a895518657 100644 --- a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts +++ b/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts @@ -1,8 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - resolveDiagnosticsHostId, - selectDiagnosticsHostId -} from './connection-diagnostics-screen-data' +import { resolveDiagnosticsHostId } from './connection-diagnostics-screen-data' import type { HostProfile } from '../transport/hosts/host-profile' @@ -16,11 +13,6 @@ const host = (id: string): HostProfile => ({ }) describe('connection diagnostics screen data', () => { - it('prefers a valid route host when navigation changes', () => { - expect(selectDiagnosticsHostId([host('a'), host('b')], 'b', 'a')).toBe('b') - expect(selectDiagnosticsHostId([host('a')], 'missing', 'missing')).toBe('a') - }) - it('applies route changes synchronously without discarding a chip choice for the same route', () => { const hosts = [host('a'), host('b')] expect(resolveDiagnosticsHostId(hosts, undefined, null)).toBe('a') diff --git a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts index 9ab77a51796..631d5af747b 100644 --- a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts +++ b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts @@ -7,24 +7,6 @@ function entry(id: number): ConnectionLogEntry { } describe('connection log buffer', () => { - it('keeps entries per host without cross-talk', () => { - const store = createConnectionLogStore() - store.append('host-a', entry(1)) - store.append('host-b', entry(2)) - - expect(store.get('host-a').map((e) => e.id)).toEqual(['log-1']) - expect(store.get('host-b').map((e) => e.id)).toEqual(['log-2']) - }) - - it('drops the oldest entries past the cap', () => { - const store = createConnectionLogStore(3) - for (let i = 1; i <= 5; i++) { - store.append('host-a', entry(i)) - } - - expect(store.get('host-a').map((e) => e.id)).toEqual(['log-3', 'log-4', 'log-5']) - }) - it('redacts credentials before retaining or persisting an event', async () => { const save = vi.fn(async () => {}) const store = createConnectionLogStore(3, { diff --git a/mobile/src/diagnostics/connection/connection-log-persistence-revisions.test.ts b/mobile/src/diagnostics/connection/connection-log-persistence-revisions.test.ts deleted file mode 100644 index 4bd01ca4241..00000000000 --- a/mobile/src/diagnostics/connection/connection-log-persistence-revisions.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createConnectionLogStore } from './connection-log-buffer' - -import type { ConnectionLogEntry } from './connection-log-types' - -const entry = (id: number): ConnectionLogEntry => ({ - id: `${id}`, - ts: id, - level: 'info', - message: `event ${id}` -}) -const drain = () => vi.advanceTimersByTimeAsync(0) - -beforeEach(() => { - vi.useFakeTimers() -}) - -afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() -}) - -describe('connection log persistence revisions', () => { - it('replaces obsolete queued revisions while a save is delayed', async () => { - const saved: string[][] = [] - let release!: () => void - let delay = false - const store = createConnectionLogStore(2, { - load: async () => [], - save: async (_host, entries) => { - saved.push(entries.map((item) => item.id)) - if (delay) { - delay = false - await new Promise((resolve) => { - release = resolve - }) - } - } - }) - await store.hydrate('a') - await drain() - saved.length = 0 - delay = true - store.append('a', entry(1)) - await drain() - store.append('a', entry(2)) - await drain() - store.append('a', entry(3)) - await drain() - expect(saved).toEqual([['1']]) - release() - await drain() - expect(saved).toEqual([['1'], ['2', '3']]) - }) -}) diff --git a/mobile/src/diagnostics/connection/mobile-relay-recovery-log.test.ts b/mobile/src/diagnostics/connection/mobile-relay-recovery-log.test.ts deleted file mode 100644 index a79d44d3254..00000000000 --- a/mobile/src/diagnostics/connection/mobile-relay-recovery-log.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createRelayRecoveryLog } from './mobile-relay-recovery-log' -import type { ConnectionLogEntry } from './connection-log-types' - -afterEach(() => vi.restoreAllMocks()) - -describe('createRelayRecoveryLog', () => { - it('uses distinct ids across logger instances', () => { - vi.spyOn(Date, 'now').mockReturnValue(1) - const entries: ConnectionLogEntry[] = [] - const sink = vi.fn((entry: ConnectionLogEntry) => entries.push(entry)) - createRelayRecoveryLog(() => 1, sink)('first') - createRelayRecoveryLog(() => 1, sink)('second') - - expect(entries).toHaveLength(2) - expect(entries[0]?.id).not.toBe(entries[1]?.id) - }) -}) diff --git a/mobile/src/diagnostics/native-diagnostics-operations.test.ts b/mobile/src/diagnostics/native-diagnostics-operations.test.ts index ab4a7048401..f87c0f062bc 100644 --- a/mobile/src/diagnostics/native-diagnostics-operations.test.ts +++ b/mobile/src/diagnostics/native-diagnostics-operations.test.ts @@ -79,13 +79,4 @@ describe('native connection diagnostic reports', () => { expect(report).toContain('Host Orca version: unknown') expect(report).not.toContain('1.4.197') }) - - it('keeps disconnected reports explicit even with a captured version', async () => { - const context = createContext() - context.setConnection('disconnected', 1_000) - const device = createNativeDiagnosticsOperations(host, context, '1.4.197') - const { report } = await device.report() - expect(report).toContain('Host Orca version: unknown (not currently connected)') - expect(report).not.toContain('1.4.197') - }) }) diff --git a/mobile/src/files/attachments/mobile-clipboard-image.test.ts b/mobile/src/files/attachments/mobile-clipboard-image.test.ts index 5d9aae440ad..e6122a67084 100644 --- a/mobile/src/files/attachments/mobile-clipboard-image.test.ts +++ b/mobile/src/files/attachments/mobile-clipboard-image.test.ts @@ -1,12 +1,9 @@ import { describe, expect, it, vi } from 'vitest' import { - buildMobileImagePastePayload, buildMobileTerminalImagePastePayload, - normalizeMobileClipboardImageBase64, saveMobileClipboardImageAsTempFile } from './mobile-clipboard-image' -import { computeMobileClipboardImageDownscale } from './mobile-clipboard-image-downscale' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import '../../transport/connection/stable-logical-rpc-client' @@ -39,16 +36,6 @@ function clientWithResponses(responses: RpcResponse[]): Pick { - it('strips data URL image prefixes', () => { - expect(normalizeMobileClipboardImageBase64('data:image/png;base64,aGVsbG8=')).toBe('aGVsbG8=') - }) - - it('rejects non-base64 image data', () => { - expect(() => normalizeMobileClipboardImageBase64('not base64!')).toThrow( - 'Clipboard image content must be base64' - ) - }) - it('falls back to the legacy single-frame image save method when needed', async () => { const client = clientWithResponses([ fail('start', 'method_not_found', 'missing'), @@ -87,32 +74,6 @@ describe('mobile clipboard image paste helpers', () => { }) }) - it('brackets generated image paths before sending to the terminal', () => { - expect(buildMobileImagePastePayload('/tmp/orca.png', 'claude')).toBe( - '\x1b[200~/tmp/orca.png\x1b[201~' - ) - expect(buildMobileImagePastePayload('/tmp/\x1b.png', 'claude')).toBe( - '\x1b[200~/tmp/\u241b.png\x1b[201~' - ) - }) - - it('escapes spaced paths for Codex and unidentified terminals', () => { - const escaped = '\x1b[200~/tmp/or\\ ca.png\x1b[201~' - expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', 'codex')).toBe(escaped) - expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', null)).toBe(escaped) - expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', undefined)).toBe(escaped) - expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', 'unknown')).toBe(escaped) - expect(buildMobileTerminalImagePastePayload('/tmp/\x1b.png', null)).toBe( - '\x1b[200~/tmp/\u241b.png\x1b[201~' - ) - }) - - it('keeps file mentions for agents that need them', () => { - const mention = '\x1b[200~@"/tmp/or ca.png"\x1b[201~' - expect(buildMobileTerminalImagePastePayload('/tmp/or ca.png', 'opencode')).toBe(mention) - expect(buildMobileImagePastePayload('/tmp/or ca.png', null)).toBe(mention) - }) - it.each([null, 'unknown', 'codex', 'omp'])( 'contains embedded paste markers inside the image paste for %s', (agent) => { @@ -126,25 +87,4 @@ describe('mobile clipboard image paste helpers', () => { expect(payload).toContain('image\u241b[201~\ncommand\u241b[200~.png') } ) - - it('quotes Windows paths with spaces using the host path dialect', () => { - expect( - buildMobileTerminalImagePastePayload('C:\\Users\\Jane Doe\\Temp\\orca-paste.png', null) - ).toBe('\x1b[200~"C:\\Users\\Jane Doe\\Temp\\orca-paste.png"\x1b[201~') - }) -}) - -describe('mobile clipboard image downscaling', () => { - it('does not downscale images already within the byte budget', () => { - expect(computeMobileClipboardImageDownscale(50, 100, 100, 100)).toBeNull() - }) - - it('shrinks both edges by ~sqrt(budget/actual) when over the budget', () => { - expect(computeMobileClipboardImageDownscale(400, 40, 20, 100)).toEqual({ width: 17, height: 8 }) - }) - - it('refuses to downscale when source dimensions are unusable', () => { - expect(computeMobileClipboardImageDownscale(400, 0, 20, 100)).toBeNull() - expect(computeMobileClipboardImageDownscale(400, 40, -1, 100)).toBeNull() - }) }) diff --git a/mobile/src/files/attachments/mobile-file-source-picker.test.ts b/mobile/src/files/attachments/mobile-file-source-picker.test.ts deleted file mode 100644 index 2f9448e549d..00000000000 --- a/mobile/src/files/attachments/mobile-file-source-picker.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('expo-image-picker', () => ({})) -vi.mock('expo-document-picker', () => ({ getDocumentAsync: vi.fn() })) -vi.mock('expo-file-system', () => ({ File: vi.fn() })) - -import '../../platform/media-picker-contract' -import type { PickedMobileFile } from '../../platform/media-picker-contract' -import { pickMobileFiles } from './mobile-file-source-picker' - -type Asset = { uri: string; name: string; size?: number; mimeType?: string } - -function launcher(assets: Asset[] | null) { - return vi.fn(async () => - assets === null - ? { canceled: true as const, assets: null } - : { canceled: false as const, assets: assets.map((asset) => ({ lastModified: 0, ...asset })) } - ) -} - -async function collect(files: AsyncIterable): Promise { - const taken: PickedMobileFile[] = [] - for await (const file of files) { - taken.push(file) - } - return taken -} - -describe('pickMobileFiles', () => { - it('yields nothing for a cancelled picker', async () => { - expect(await collect(pickMobileFiles({ launch: launcher(null) }))).toEqual([]) - }) -}) diff --git a/mobile/src/files/attachments/use-mobile-attachment-input-lease-gate.test.ts b/mobile/src/files/attachments/use-mobile-attachment-input-lease-gate.test.ts index 1efbc4bad18..18883e59f8d 100644 --- a/mobile/src/files/attachments/use-mobile-attachment-input-lease-gate.test.ts +++ b/mobile/src/files/attachments/use-mobile-attachment-input-lease-gate.test.ts @@ -56,15 +56,6 @@ describe('useMobileAttachmentInputLeaseGate', () => { } } - it('passes immediately when the lease is ready and the target is active', async () => { - const refs = baseRefs() - const showToast = vi.fn() - const { gate } = renderGate({ ...refs, showToast }) - - await expect(gate()('terminal-1')).resolves.toBe(true) - expect(showToast).not.toHaveBeenCalled() - }) - it('waits out a lease-not-ready window and then sends', async () => { const refs = baseRefs() refs.leaseReady.current = false diff --git a/mobile/src/files/mobile-file-tab-doc.test.ts b/mobile/src/files/mobile-file-tab-doc.test.ts deleted file mode 100644 index 11d7f6c826a..00000000000 --- a/mobile/src/files/mobile-file-tab-doc.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { RpcResponse } from '../transport/rpc/rpc-wire-types' -import { resolveMobileFileTabDoc } from './mobile-file-tab-doc' - -function ok(result: unknown): RpcResponse { - return { id: 'x', ok: true, result, _meta: { runtimeId: 'r' } } -} - -function fail(code: string, message: string): RpcResponse { - return { id: 'x', ok: false, error: { code, message }, _meta: { runtimeId: 'r' } } -} - -function clientOf(byMethod: Record): { - sendRequest: (method: string, params?: unknown) => Promise - calls: string[] - requests: { method: string; params: unknown }[] -} { - const calls: string[] = [] - const requests: { method: string; params: unknown }[] = [] - return { - calls, - requests, - sendRequest: (method: string, params?: unknown) => { - calls.push(method) - requests.push({ method, params }) - const response = byMethod[method] - if (!response) { - throw new Error(`unexpected method ${method}`) - } - return Promise.resolve(response) - } - } -} - -const WT = { worktreeId: 'wt1' } - -describe('resolveMobileFileTabDoc', () => { - it('renders a staged text diff', async () => { - const client = clientOf({ - 'git.diff': ok({ kind: 'text', originalContent: 'a\n', modifiedContent: 'a\nb\n' }) - }) - const doc = await resolveMobileFileTabDoc(client, { - ...WT, - relativePath: 'a.ts', - diffSource: 'staged' - }) - expect(doc).toEqual({ - status: 'ready', - kind: 'diff', - lines: [ - { kind: 'context', text: 'a', oldLineNumber: 1, newLineNumber: 1 }, - { kind: 'add', text: 'b', newLineNumber: 2 } - ], - truncated: false - }) - expect(client.requests).toEqual([ - { method: 'git.diff', params: { worktree: 'id:wt1', filePath: 'a.ts', staged: true } } - ]) - }) - - it('throws binary_file for an image modify whose bytes are empty (no stale fallback)', async () => { - const client = clientOf({ - 'git.diff': ok({ - kind: 'binary', - originalContent: 'b2xk', - modifiedContent: '', - modifiedIsBinary: true, - isImage: true, - mimeType: 'image/png' - }) - }) - await expect( - resolveMobileFileTabDoc(client, { ...WT, relativePath: 'm1.png', diffSource: 'unstaged' }) - ).rejects.toThrow('binary_file') - }) - - it('throws binary_file for a non-image binary diff', async () => { - const client = clientOf({ 'git.diff': ok({ kind: 'binary', modifiedContent: 'AAAA' }) }) - await expect( - resolveMobileFileTabDoc(client, { ...WT, relativePath: 'a.bin', diffSource: 'unstaged' }) - ).rejects.toThrow('binary_file') - }) - - it('throws binary_file when readPreview returns no image bytes', async () => { - const client = clientOf({ - 'files.readPreview': ok({ content: '', isImage: true, mimeType: 'image/png' }) - }) - await expect( - resolveMobileFileTabDoc(client, { ...WT, relativePath: 'logo.png' }) - ).rejects.toThrow('binary_file') - }) - - // An older client must still surface the host’s oversized-diff error message rather than render an empty diff. - it('propagates a host diff_too_large failure instead of rendering an empty diff', async () => { - const client = clientOf({ - 'git.diff': fail('diff_too_large', 'This diff is too large to open over a remote connection.') - }) - await expect( - resolveMobileFileTabDoc(client, { ...WT, relativePath: 'a.ts', diffSource: 'staged' }) - ).rejects.toThrow('This diff is too large to open over a remote connection.') - }) - - it('propagates the RPC error message when a read fails', async () => { - const client = clientOf({ 'files.read': fail('EIO', 'file_too_large') }) - await expect( - resolveMobileFileTabDoc(client, { ...WT, relativePath: 'notes.txt' }) - ).rejects.toThrow('file_too_large') - }) -}) diff --git a/mobile/src/files/session-documents/markdown-floating-actions-layout.test.ts b/mobile/src/files/session-documents/markdown-floating-actions-layout.test.ts deleted file mode 100644 index a4e139acc2f..00000000000 --- a/mobile/src/files/session-documents/markdown-floating-actions-layout.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveMarkdownFloatingActionsBottom, - shouldShowMarkdownFloatingActions -} from './markdown-floating-actions-layout' - -describe('resolveMarkdownFloatingActionsBottom', () => { - it('keeps markdown actions at their resting bottom when the keyboard is closed', () => { - expect( - resolveMarkdownFloatingActionsBottom({ - keyboardLift: 0, - restingBottom: 16, - liftedClearance: 12 - }) - ).toBe(16) - }) - - it('raises markdown actions above the keyboard with clearance', () => { - expect( - resolveMarkdownFloatingActionsBottom({ - keyboardLift: 291, - restingBottom: 16, - liftedClearance: 12 - }) - ).toBe(303) - }) -}) - -describe('shouldShowMarkdownFloatingActions', () => { - const idle = { - keyboardLift: 0, - hasStatus: false, - showRefresh: false, - showCopy: false, - showSave: false - } - - it('shows the floating row for keyboard dismissal without document actions', () => { - expect(shouldShowMarkdownFloatingActions({ ...idle, keyboardLift: 291 })).toBe(true) - }) - - it('hides the floating row on a clean document with the keyboard closed', () => { - expect(shouldShowMarkdownFloatingActions(idle)).toBe(false) - }) - - it.each(['hasStatus', 'showRefresh', 'showCopy', 'showSave'] as const)( - 'shows the floating row for %s alone', - (field) => { - expect(shouldShowMarkdownFloatingActions({ ...idle, [field]: true })).toBe(true) - } - ) -}) diff --git a/mobile/src/home/MobileHomeDesktopRow.tsx b/mobile/src/home/MobileHomeDesktopRow.tsx index 617a9c29ee8..2d8786ddb8a 100644 --- a/mobile/src/home/MobileHomeDesktopRow.tsx +++ b/mobile/src/home/MobileHomeDesktopRow.tsx @@ -12,7 +12,6 @@ import type { ConnectionState } from '../transport/connection/connection-state' import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { homeAgentNeedsYou } from '../worktree/home-jump-back-in' import { homeHostWorktreeSummary, type HostWorktreeInfo } from '../worktree/home-worktree-info' import { homeListStyles as styles } from './home-list-styles' @@ -52,6 +51,8 @@ export function MobileHomeDesktopRow(props: { path: MobileConnectionPath // The row owns fresh/stale/unavailable wording so callers cannot hide retained counts again (STA-3123). worktreeInfo?: HostWorktreeInfo + /** Agents on this desktop waiting on the user. */ + needsYou: number onPress: () => void onLongPress: () => void }) { @@ -95,12 +96,7 @@ export function MobileHomeDesktopRow(props: { Boolean(line) ) const statusLine = connected && worktreeSummary.visual ? worktreeSummary.visual : statusLabel - const attention = props.worktreeInfo?.catalogUnavailable - ? undefined - : props.worktreeInfo?.attention - const needsYou = connected - ? (attention?.filter((worktree) => homeAgentNeedsYou(worktree.dotStatus)).length ?? 0) - : 0 + const needsYou = connected ? props.needsYou : 0 const needsYouLabel = needsYou > 0 ? needsYou === 1 diff --git a/mobile/src/home/MobileHomeHostList.tsx b/mobile/src/home/MobileHomeHostList.tsx index cef4133c87f..ad442bc3472 100644 --- a/mobile/src/home/MobileHomeHostList.tsx +++ b/mobile/src/home/MobileHomeHostList.tsx @@ -22,6 +22,8 @@ type MobileHomeHostListProps = { hostConnections: HomeHostConnections hosts: HostCatalogEntry[] hostStates: Record + /** Agents waiting on the user, per desktop. */ + needsYouByHost: Readonly> worktreeInfo: Record onOpen: (host: HostCatalogEntry) => void onOpenActions: (host: HostCatalogEntry) => void @@ -48,6 +50,7 @@ export function MobileHomeHostList(props: MobileHomeHostListProps) { hostLastConnected={props.hostLastConnected} hostConnections={props.hostConnections} hostStates={props.hostStates} + needsYou={props.needsYouByHost[host.id] ?? 0} worktreeInfo={props.worktreeInfo} onOpen={props.onOpen} onOpenActions={props.onOpenActions} @@ -86,7 +89,7 @@ type MobileHomeHostRowProps = Pick< | 'worktreeInfo' | 'onOpen' | 'onOpenActions' -> & { item: HostCatalogEntry } +> & { item: HostCatalogEntry; needsYou: number } const MobileHomeHostRow = memo(function MobileHomeHostRow(props: MobileHomeHostRowProps) { const { item, onOpen, onOpenActions } = props @@ -117,6 +120,7 @@ const MobileHomeHostRow = memo(function MobileHomeHostRow(props: MobileHomeHostR verdict={verdict} path={connection?.path ?? 'lan'} worktreeInfo={props.worktreeInfo[item.id]} + needsYou={props.needsYou} onPress={open} onLongPress={openActions} /> diff --git a/mobile/src/home/MobileHomeJumpBackIn.tsx b/mobile/src/home/MobileHomeJumpBackIn.tsx deleted file mode 100644 index 3af562be54c..00000000000 --- a/mobile/src/home/MobileHomeJumpBackIn.tsx +++ /dev/null @@ -1,171 +0,0 @@ -import { ChevronRight } from 'lucide-react-native' -import { memo, useMemo, useState } from 'react' -import { Pressable, Text, View } from 'react-native' -import Animated, { FadeIn, FadeOut, LinearTransition } from 'react-native-reanimated' -import type { WorktreeStatus } from '../../../src/shared/worktree-status-rollup' -import { AgentSpinner, agentStatusColors } from '../components/AgentSpinner' -import { useMobileTranslation } from '../i18n/use-mobile-translation' -import { useReducedMotionEnabled } from '../platform/use-reduced-motion' -import { colors } from '../theme/mobile-theme' -import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { useHostDisplay } from '../transport/hosts/use-host-display' -import { areStructurallyEqual } from '../worktree/structural-equality' -import type { HostCatalogEntry } from '../transport/hosts/host-profile' -import type { HomeJumpBackInRow } from '../worktree/home-jump-back-in' -import { agentStateLabel, type AgentDotState } from '../worktree/agent-row-display' -import { homeListStyles as styles } from './home-list-styles' -import { MobileHomeSectionHeading } from './MobileHomeSectionHeading' -import { HOME_EASE_OUT } from './tabs/home-tabs' - -const LABEL_STATE: Partial> = { - permission: 'waiting', - failed: 'failed', - done: 'done', - working: 'working', - monitoring: 'monitoring' -} - -// Only states that ask something of the user take the dot's colour; running work stays quiet. -const TINTED_STATUSES: ReadonlySet = new Set(['permission', 'failed', 'done']) - -// Enough to see what needs you without the list pushing Desktops off the first screen. -const AGENT_ROWS_COLLAPSED = 5 - -// Usage, stats and connection ticks re-render Home; the section redraws only when its rows change. -export const MobileHomeJumpBackIn = memo(function MobileHomeJumpBackIn(props: { - rows: readonly HomeJumpBackInRow[] - hosts: readonly HostCatalogEntry[] - first: boolean - onOpen: (row: HomeJumpBackInRow) => void -}) { - const t = useMobileTranslation() - useMobileColorScheme() - const reducedMotion = useReducedMotionEnabled() === true - const [expanded, setExpanded] = useState(false) - // Rows glide to their new place when an agent's state reorders the list. - const layout = useMemo( - () => (reducedMotion ? undefined : LinearTransition.duration(220).easing(HOME_EASE_OUT)), - [reducedMotion] - ) - if (props.rows.length === 0) { - return null - } - // One desktop needs no naming. - const nameDesktops = props.hosts.length > 1 - const collapsible = props.rows.length > AGENT_ROWS_COLLAPSED - const shown = expanded || !collapsible ? props.rows : props.rows.slice(0, AGENT_ROWS_COLLAPSED) - const activeCount = props.rows.filter((row) => !row.lastOpened).length - const entering = reducedMotion ? undefined : FadeIn.duration(180) - return ( - <> - 0 - ? t('home.agents.activeCount', '{{count}} active', { count: activeCount }) - : undefined - } - first={props.first} - /> - - {shown.map((row, index) => ( - - {index > 0 ? : null} - host.id === row.hostId) ?? null} - nameDesktop={nameDesktops} - onOpen={props.onOpen} - /> - - ))} - {collapsible ? ( - - - [styles.actionRow, pressed && styles.rowPressed]} - onPress={() => setExpanded((value) => !value)} - > - - {expanded - ? t('home.agents.showFewer', 'Show fewer') - : t('home.agents.showAll', 'Show all {{count}}', { count: props.rows.length })} - - - - ) : null} - - - ) -}) - -// Each refresh rebuilds every row object; compare by value so only changed rows redraw. -const JumpBackInRow = memo(function JumpBackInRow(props: { - row: HomeJumpBackInRow - host: HostCatalogEntry | null - nameDesktop: boolean - onOpen: (row: HomeJumpBackInRow) => void -}) { - const t = useMobileTranslation() - useMobileColorScheme() - const { row } = props - const desktopName = useHostDisplay(props.host).title - const workspace = row.worktree.displayName || row.worktree.repo - const conversation = row.worktree.conversationName - const title = conversation ?? workspace - const labelState = LABEL_STATE[row.worktree.dotStatus] - const status = row.lastOpened - ? row.actionable - ? t('home.jumpBackIn.lastOpened', 'Last opened') - : t('home.jumpBackIn.connectToOpen', 'Connect {{desktop}} to open', { desktop: desktopName }) - : labelState - ? agentStateLabel(labelState) - : '' - // Branch names repeat across projects, so the repo is always named (#37642); "Connect X" already names the desktop. - // A named conversation takes the title and moves the workspace to the subtitle (#38007). - const where = [ - conversation ? workspace : null, - row.worktree.repo && row.worktree.repo !== workspace ? row.worktree.repo : null, - props.nameDesktop && (row.actionable || !row.lastOpened) ? desktopName : null - ] - .filter(Boolean) - .join(' · ') - const statusColor = - !row.lastOpened && TINTED_STATUSES.has(row.worktree.dotStatus) - ? agentStatusColors()[row.worktree.dotStatus] - : colors.textSecondary - - return ( - [styles.row, pressed && styles.rowPressed]} - onPress={() => props.onOpen(row)} - > - - - - - - {title} - - - {status} - {where ? `${status ? ' · ' : ''}${where}` : ''} - - - - - - - ) -}, areStructurallyEqual) diff --git a/mobile/src/home/MobileHomeNeedsYou.tsx b/mobile/src/home/MobileHomeNeedsYou.tsx new file mode 100644 index 00000000000..e31ca0db5c1 --- /dev/null +++ b/mobile/src/home/MobileHomeNeedsYou.tsx @@ -0,0 +1,43 @@ +import { memo } from 'react' +import type { AgentListRow } from '../agents/agent-list-rows' +import { MobileAgentListRows, type AgentListRowHandlers } from '../agents/MobileAgentListRows' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import type { HostProfile } from '../transport/hosts/host-profile' +import { areStructurallyEqual } from '../worktree/structural-equality' +import { MobileHomeSectionHeading } from './MobileHomeSectionHeading' + +// Enough to act on without pushing Desktops off the first screen; the Agents tab has the rest. +const NEEDS_YOU_ROWS_SHOWN = 3 + +/** Feed's short list of agents waiting on the user; hidden when none are. */ +export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou(props: { + handlers: AgentListRowHandlers + rows: readonly AgentListRow[] + hosts: readonly HostProfile[] + now: number + onSeeAll: () => void +}) { + const t = useMobileTranslation() + if (props.rows.length === 0) { + return null + } + return ( + <> + + 1} + hosts={props.hosts} + now={props.now} + handlers={props.handlers} + /> + + ) +}, areStructurallyEqual) diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index c3e56a26534..fadfbfcd5aa 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -1,16 +1,15 @@ import { useFocusEffect } from 'expo-router' import { useCallback, useState } from 'react' import { Alert, BackHandler, View } from 'react-native' +import { GestureHandlerRootView } from 'react-native-gesture-handler' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { useOpenMobileAccounts } from '../accounts/use-open-mobile-accounts' -import { getProvenCachedWorktrees } from '../cache/worktree-cache' import { ActionSheetModal } from '../components/ActionSheetModal' import { ConfirmModal } from '../components/ConfirmModal' import { getHostListActionSheetActions } from '../host-list-action-sheet-actions' -import { hostRouteWithNotice } from '../host-route-notice' import { triggerMediumImpact } from '../platform/haptics' -import { useOpenMobileSession } from '../session/use-open-mobile-session' +import { useAgentListRowActions } from '../agents/use-agent-list-row-actions' import { useOpenMobileTasks } from '../tasks/use-open-mobile-tasks' import { useOpenMobileAutomations } from '../automations/use-open-mobile-automations' import { colors, spacing } from '../theme/mobile-theme' @@ -28,11 +27,10 @@ import { loadHostCatalog } from '../transport/hosts/host-store' import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' import { useOpenMobileHostEdit } from '../host-screen/use-open-mobile-host-edit' import { mobileConnectionPathLabel } from '../transport/connection/mobile-connection-path-label' -import { homeAgentNeedsYou, type HomeJumpBackInRow } from '../worktree/home-jump-back-in' -import { isResumeTargetConfirmedMissing } from '../worktree/home-resume-card' import { newWorkspaceOverlayHref } from '../new-workspace/new-workspace-overlay-route' import { useMobileHomeData } from './use-mobile-home-data' import { HOME_TABS, type HomeTabId } from './tabs/home-tabs' +import { MobileHomeAgentsTab } from './tabs/MobileHomeAgentsTab' import { MobileHomeAutomationsTab } from './tabs/MobileHomeAutomationsTab' import { MobileHomeFab } from './tabs/MobileHomeFab' import { MobileHomeFeedTab } from './tabs/MobileHomeFeedTab' @@ -51,7 +49,6 @@ export function MobileHomeScreen() { const openMobileHostEdit = useOpenMobileHostEdit() const openMobileTasks = useOpenMobileTasks() const openMobileAutomations = useOpenMobileAutomations() - const openMobileSession = useOpenMobileSession() const openMobileAccounts = useOpenMobileAccounts() const disconnectHostClient = useDisconnectHostClient() const forgetHostClient = useForgetHostClient() @@ -63,6 +60,11 @@ export function MobileHomeScreen() { const [visitedTabs, setVisitedTabs] = useState>(() => new Set(['feed'])) const [automationsHostId, setAutomationsHostId] = useState(null) const [tabBarHeight, setTabBarHeight] = useState(0) + const agentActions = useAgentListRowActions( + tabBarHeight, + data.sortedHosts, + data.applyAgentActivity + ) const selectTab = useCallback((next: HomeTabId) => { setTab(next) @@ -85,21 +87,7 @@ export function MobileHomeScreen() { // Stable handlers keep the memoized Feed sections and desktop rows from redrawing on every Home update. const { router, setHostCatalog } = data - const openWorktree = useCallback( - (row: HomeJumpBackInRow) => { - if (isResumeTargetConfirmedMissing(row, getProvenCachedWorktrees(row.hostId))) { - router.push(hostRouteWithNotice(row.hostId, 'worktree-missing')) - return - } - openMobileSession({ - hostId: row.hostId, - worktreeId: row.worktree.worktreeId, - name: row.worktree.displayName || row.worktree.repo, - paneKey: row.worktree.paneKey - }) - }, - [router, openMobileSession] - ) + const seeAllAgents = useCallback(() => selectTab('agents'), [selectTab]) const openHost = useCallback( (host: HostCatalogEntry) => { @@ -156,9 +144,6 @@ export function MobileHomeScreen() { actionTarget != null && data.hostStates[actionTarget.id] === 'connected' const paired = data.hostCatalogLoaded && data.hostCatalog.length > 0 - const feedBadge = data.jumpBackInRows.filter( - (row) => !row.lastOpened && homeAgentNeedsYou(row.worktree.dotStatus) - ).length const automationsHostConnected = automationsHostId != null && data.hostStates[automationsHostId] === 'connected' const fab = @@ -185,113 +170,124 @@ export function MobileHomeScreen() { const contentBottom = spacing.xl + (fab ? FAB_CLEARANCE : 0) return ( - - - {HOME_TABS.map((id) => - visitedTabs.has(id) ? ( - - {id === 'feed' ? ( - - ) : id === 'usage' ? ( - - ) : id === 'automations' ? ( - openMobileAutomations(hostId)} - onHostChange={setAutomationsHostId} - /> - ) : ( - - )} - - ) : null - )} - - fab?.onPress()} - /> - setTabBarHeight(event.nativeEvent.layout.height)}> - + + + {HOME_TABS.map((id) => + visitedTabs.has(id) ? ( + + {id === 'feed' ? ( + + ) : id === 'agents' ? ( + + ) : id === 'usage' ? ( + + ) : id === 'automations' ? ( + openMobileAutomations(hostId)} + onHostChange={setAutomationsHostId} + /> + ) : ( + + )} + + ) : null + )} + + fab?.onPress()} /> - - setActionTarget(null), - onReconnect: (hostId) => void forceReconnectHost?.(hostId), - onDisconnect: disconnectHostClient, - onDiagnostics: (hostId) => - data.router.push({ pathname: '/connection-log', params: { hostId } }), - onEdit: openMobileHostEdit, - onRemove: (host) => setConfirmRemove(host) - })} - onClose={() => setActionTarget(null)} - /> - void handleRemove()} - onCancel={() => setConfirmRemove(null)} - /> - + setTabBarHeight(event.nativeEvent.layout.height)}> + + + {agentActions.sheet} + setActionTarget(null), + onReconnect: (hostId) => void forceReconnectHost?.(hostId), + onDisconnect: disconnectHostClient, + onDiagnostics: (hostId) => + data.router.push({ pathname: '/connection-log', params: { hostId } }), + onEdit: openMobileHostEdit, + onRemove: (host) => setConfirmRemove(host) + })} + onClose={() => setActionTarget(null)} + /> + void handleRemove()} + onCancel={() => setConfirmRemove(null)} + /> + + ) } diff --git a/mobile/src/home/MobileHomeSectionHeading.tsx b/mobile/src/home/MobileHomeSectionHeading.tsx index c05bc13aa78..d1ef1eb0f80 100644 --- a/mobile/src/home/MobileHomeSectionHeading.tsx +++ b/mobile/src/home/MobileHomeSectionHeading.tsx @@ -1,16 +1,48 @@ -import { Text, View } from 'react-native' +import type { LucideIcon } from 'lucide-react-native' +import { Pressable, Text, View } from 'react-native' +import { colors } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { homeListStyles as styles } from './home-list-styles' +const ASIDE_HIT_SLOP = { top: 10, bottom: 10, left: 12, right: 12 } as const + /** A Home section's title, with an optional muted note on the right; the first section sits closer to the bar. */ -export function MobileHomeSectionHeading(props: { title: string; first: boolean; aside?: string }) { +export function MobileHomeSectionHeading(props: { + title: string + first: boolean + /** Shown muted after the title. */ + count?: number + aside?: string + asideIcon?: LucideIcon + /** Turns the aside into a link. */ + onAsidePress?: () => void +}) { useMobileColorScheme() + const AsideIcon = props.asideIcon return ( - + {props.title} + {props.count !== undefined ? ( + {` ${props.count}`} + ) : null} - {props.aside ? {props.aside} : null} + {props.aside && props.onAsidePress ? ( + + {({ pressed }) => ( + + {props.aside} + + )} + + ) : props.aside ? ( + + {AsideIcon ? : null} + + {props.aside} + + + ) : null} ) } diff --git a/mobile/src/home/home-list-styles.ts b/mobile/src/home/home-list-styles.ts index 0b1ae21bc9b..780ccc85973 100644 --- a/mobile/src/home/home-list-styles.ts +++ b/mobile/src/home/home-list-styles.ts @@ -5,6 +5,8 @@ import { themedStyleSheet } from '../theme/themed-styles' // Text starts after the status column, so separators inset to it. const STATUS_COLUMN_WIDTH = 24 const ROW_LEADING_PADDING = spacing.lg +/** Where a row's text starts: separators and nested rows line up with it. */ +export const HOME_ROW_TEXT_INSET = ROW_LEADING_PADDING + STATUS_COLUMN_WIDTH const TILE_SIZE = 30 const TILE_GAP = 11 const TILE_DOT_SIZE = 10 @@ -21,8 +23,12 @@ export const homeListStyles = themedStyleSheet(() => ({ marginTop: 20, marginBottom: 7 }, - sectionHeading: { fontSize: 15, fontWeight: '600', color: colors.textPrimary }, + sectionHeading: { flexShrink: 1, fontSize: 15, fontWeight: '600', color: colors.textPrimary }, + sectionCount: { fontWeight: '500', color: colors.textMuted, fontVariant: ['tabular-nums'] }, sectionAside: { fontSize: 14, color: colors.textMuted, fontVariant: ['tabular-nums'] }, + sectionAsideRow: { flexShrink: 1, flexDirection: 'row', alignItems: 'center', gap: 6 }, + sectionLink: { color: colors.accentBlue, fontWeight: '500' }, + linkPressed: { opacity: 0.5 }, firstSectionHeading: { marginTop: spacing.xs }, // Matches a heading's top gap for a group that has none. headinglessGroup: { marginTop: 20 }, @@ -33,7 +39,7 @@ export const homeListStyles = themedStyleSheet(() => ({ separator: { height: StyleSheet.hairlineWidth, backgroundColor: colors.borderSubtle, - marginLeft: ROW_LEADING_PADDING + STATUS_COLUMN_WIDTH + marginLeft: HOME_ROW_TEXT_INSET }, fullSeparator: { marginLeft: ROW_LEADING_PADDING }, tileSeparator: { marginLeft: ROW_LEADING_PADDING + TILE_SIZE + TILE_GAP }, diff --git a/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx b/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx new file mode 100644 index 00000000000..04b40720156 --- /dev/null +++ b/mobile/src/home/tabs/MobileHomeAgentsDesktopFilter.tsx @@ -0,0 +1,107 @@ +import { Monitor, WifiOff } from 'lucide-react-native' +import { useState } from 'react' +import type { AgentListHostSummary } from '../../agents/agent-list-rows' +import { PickerModal, type PickerOption } from '../../components/PickerModal' +import { hostPickerOptions } from '../../components/use-connected-host-picker' +import type { Translate } from '../../i18n/mobile-i18n' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { colors } from '../../theme/mobile-theme' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { HostProfile } from '../../transport/hosts/host-profile' +import { useHostDisplay } from '../../transport/hosts/use-host-display' +import { MobileHomePill } from './MobileHomeHostPill' + +const ALL_DESKTOPS = '__all__' + +/** The Agents tab's desktop filter: "All desktops" or one, each with its agent counts. */ +export function AgentsDesktopFilter(props: { + hosts: readonly HostProfile[] + selected: string | null + summaries: readonly AgentListHostSummary[] + onSelect: (hostId: string | null) => void +}) { + const t = useMobileTranslation() + const [open, setOpen] = useState(false) + return ( + <> + setOpen(true)} /> + props.onSelect(value === ALL_DESKTOPS ? null : value)} + onClose={() => setOpen(false)} + /> + + ) +} + +function desktopFilterOptions( + hosts: readonly HostProfile[], + summaries: readonly AgentListHostSummary[], + t: Translate +): PickerOption[] { + const agentCount = (count: number) => + count === 1 + ? t('agents.desktops.agents_one', '{{count}} agent', { count }) + : t('agents.desktops.agents_other', '{{count}} agents', { count }) + const total = summaries.reduce((sum, summary) => sum + summary.agents, 0) + const icon = (offline: boolean) => () => + offline ? ( + + ) : ( + + ) + return [ + { + value: ALL_DESKTOPS, + label: t('agents.desktops.all', 'All desktops'), + subtitle: agentCount(total), + renderIcon: icon(false) + }, + ...hostPickerOptions([...hosts]).map((option) => { + const summary = summaries.find((entry) => entry.hostId === option.value) + const needsYou = summary?.needsYou ?? 0 + return { + value: option.value, + label: option.label, + subtitle: summary?.offline + ? t('agents.desktops.offline', 'Offline') + : [ + agentCount(summary?.agents ?? 0), + needsYou > 0 + ? needsYou === 1 + ? t('agents.desktops.needsYou_one', '{{count}} needs you', { count: needsYou }) + : t('agents.desktops.needsYou_other', '{{count}} need you', { count: needsYou }) + : null + ] + .filter(Boolean) + .join(' · '), + renderIcon: icon(summary?.offline ?? false) + } + }) + ] +} + +function DesktopPill(props: { + hosts: readonly HostProfile[] + selected: string | null + onOpen: () => void +}) { + const t = useMobileTranslation() + useMobileColorScheme() + const selected = props.hosts.find((host) => host.id === props.selected) ?? null + const title = useHostDisplay(selected).title + const label = selected ? title : t('agents.desktops.all', 'All desktops') + return ( + } + accessibilityLabel={t('home.tabs.chooseDesktop', '{{desktop}}, choose another desktop', { + desktop: label + })} + onPress={props.onOpen} + /> + ) +} diff --git a/mobile/src/home/tabs/MobileHomeAgentsTab.tsx b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx new file mode 100644 index 00000000000..c31b8a37079 --- /dev/null +++ b/mobile/src/home/tabs/MobileHomeAgentsTab.tsx @@ -0,0 +1,375 @@ +import { + Bot, + CheckCheck, + ChevronRight, + Search, + SlidersHorizontal, + Trash2, + WifiOff +} from 'lucide-react-native' +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { ActivityIndicator, ScrollView, Text, View } from 'react-native' +import { + AGENT_LIST_GROUP_BY_CHOICES, + agentListRowsIn, + buildAgentList, + DEFAULT_AGENT_LIST_VIEW, + type AgentListGroupBy, + type AgentListSection +} from '../../agents/agent-list-model' +import { summarizeAgentListHosts } from '../../agents/agent-list-rows' +import { loadAgentListView, saveAgentListView } from '../../agents/agent-list-preferences' +import { MobileAgentListRows, type AgentListRowHandlers } from '../../agents/MobileAgentListRows' +import type { ActionSheetAction } from '../../components/ActionSheetModal' +import { MobileSearchField } from '../../components/MobileSearchField' +import { PullDownMenu } from '../../components/nav-bar/PullDownMenu' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { useResponsiveLayout } from '../../layout/responsive-layout' +import { useSerializedStoredState } from '../../storage/use-serialized-stored-state' +import { colors, spacing } from '../../theme/mobile-theme' +import { themedStyleSheet } from '../../theme/themed-styles' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import type { HostProfile } from '../../transport/hosts/host-profile' +import { useHostDisplay } from '../../transport/hosts/use-host-display' +import { formatTimeAgo } from '../../worktree/agent-row-display' +import { homeListStyles } from '../home-list-styles' +import { MobileHomeSectionHeading } from '../MobileHomeSectionHeading' +import type { MobileHomeData } from '../use-mobile-home-data' +import { AgentsDesktopFilter } from './MobileHomeAgentsDesktopFilter' +import { MobileHomeTabHeader, MobileHomeTabHeaderButton } from './MobileHomeTabHeader' + +/** Every agent on every paired desktop, grouped the way the user picked. */ +export function MobileHomeAgentsTab(props: { + data: MobileHomeData + bottomInset: number + handlers: AgentListRowHandlers +}) { + const t = useMobileTranslation() + useMobileColorScheme() + const { isWideLayout, contentMaxWidth } = useResponsiveLayout() + const { data } = props + const hosts = data.sortedHosts + const stored = useSerializedStoredState( + DEFAULT_AGENT_LIST_VIEW, + loadAgentListView, + saveAgentListView + ) + const { refresh } = stored + useEffect(() => refresh(), [refresh]) + const view = stored.value + const [searchOpen, setSearchOpen] = useState(false) + const [query, setQuery] = useState('') + const [pickedHost, setPickedHost] = useState(null) + const [menu, setMenu] = useState<'closed' | 'options' | 'group-by'>('closed') + const optionsRef = useRef(null) + // An unpaired desktop's filter falls back to every desktop. + const hostFilter = hosts.some((host) => host.id === pickedHost) ? pickedHost : null + const { now } = data.agentList + const list = useMemo( + () => buildAgentList(data.agentList, { view, hostFilter, query }), + [data.agentList, view, hostFilter, query] + ) + const nameDesktops = hosts.length > 1 && hostFilter === null + const listed = useMemo(() => agentListRowsIn(list.sections), [list.sections]) + const unreadRows = listed.filter((row) => row.unread === true) + const clearableRows = listed.filter((row) => row.clearable) + const clearFinished = () => props.handlers.onClear(clearableRows) + // The Done heading's Clear acts on Done alone; a failed agent under Needs you stays. + const clearSection = (section: AgentListSection) => { + const rows = agentListRowsIn([section]).filter((row) => row.clearable) + return rows.length > 0 ? () => props.handlers.onClear(rows) : undefined + } + const hostSummaries = useMemo(() => summarizeAgentListHosts(data.agentList), [data.agentList]) + const setView = (next: typeof view) => { + stored.setValue(next) + stored.persist(next) + } + + const groupByLabels: Record = { + status: t('agents.groupBy.status', 'Status'), + workspace: t('agents.groupBy.workspace', 'Workspace'), + project: t('agents.groupBy.project', 'Project'), + agent: t('agents.groupBy.agent', 'Agent'), + desktop: t('agents.groupBy.desktop', 'Desktop') + } + const menuGroups: ActionSheetAction[][] = + menu === 'group-by' + ? [ + AGENT_LIST_GROUP_BY_CHOICES.map((groupBy) => ({ + id: groupBy, + label: groupByLabels[groupBy], + checked: view.groupBy === groupBy, + onPress: () => setView({ ...view, groupBy }) + })) + ] + : [ + [ + { + id: 'group-by', + label: t('agents.options.groupBy', 'Group by'), + skipAutoClose: true, + renderIcon: () => ( + + {groupByLabels[view.groupBy]} + + + ), + onPress: () => setMenu('group-by') + }, + { + id: 'unread-only', + label: t('agents.options.unreadOnly', 'Unread only'), + checked: view.unreadOnly, + onPress: () => setView({ ...view, unreadOnly: !view.unreadOnly }) + }, + { + id: 'show-workers', + label: t('agents.options.showWorkers', 'Show worker agents'), + checked: view.showWorkers, + onPress: () => setView({ ...view, showWorkers: !view.showWorkers }) + } + ], + [ + { + id: 'mark-all-read', + label: t('agents.options.markAllRead', 'Mark all read'), + icon: CheckCheck, + disabled: unreadRows.length === 0, + onPress: () => props.handlers.onSetRead(unreadRows, true) + }, + { + id: 'clear-finished', + label: t('agents.options.clearFinished', 'Clear finished'), + icon: Trash2, + disabled: clearableRows.length === 0, + onPress: clearFinished + } + ] + ] + + const filteredHosts = hosts.filter((host) => hostFilter === null || host.id === hostFilter) + // A desktop still connecting, or connected with its first list read pending, may yet have agents. + const awaitingDesktop = filteredHosts.some((host) => { + const state = data.hostStates[host.id] + return state === 'connected' + ? !data.worktreeInfo[host.id]?.catalogUnavailable + : state === undefined || state === 'connecting' || state === 'handshaking' + }) + const emptyState = (): ReactNode => { + const trimmed = query.trim() + if (trimmed) { + return ( + + ) + } + if (hosts.length === 0) { + return ( + + ) + } + // "No agents running" is only true of a desktop that answered. + if (!list.anyLive) { + return awaitingDesktop ? ( + + + + ) : ( + + ) + } + return ( + + ) + } + + const body = !data.hostCatalogLoaded + ? null + : list.sections.length === 0 + ? emptyState() + : list.sections.map((section, index) => ( + + host.id === section.hostId) ?? null} + nameDesktop={nameDesktops} + first={index === 0} + now={now} + onClear={section.kind === 'done' ? clearSection(section) : undefined} + /> + + + )) + + return ( + <> + + { + setSearchOpen((open) => !open) + setQuery('') + }} + /> + setMenu('options')} + /> + + } + /> + {searchOpen ? ( + setQuery('')} + autoFocus + style={styles.search} + /> + ) : null} + {hosts.length > 1 ? ( + + + + ) : null} + + {body} + + setMenu('closed')} + /> + + ) +} + +function AgentListSectionHeading(props: { + section: AgentListSection + host: HostProfile | null + nameDesktop: boolean + first: boolean + now: number + /** The Done heading's "Clear": the same as Clear finished. */ + onClear?: () => void +}) { + const t = useMobileTranslation() + const { section } = props + const desktop = useHostDisplay(props.host).title + if (section.kind === 'idle') { + return + } + const titles: Partial> = { + 'needs-you': t('agents.sections.needsYou', 'Needs you'), + working: t('agents.sections.working', 'Working'), + done: t('agents.sections.done', 'Done'), + desktop + } + const counted = section.kind !== 'workspace' && section.kind !== 'project' + const seen = section.lastSeen + const seenAgo = + seen?.at === undefined + ? null + : props.now - seen.at < 60_000 + ? null + : formatTimeAgo(seen.at, props.now) + const aside = seen + ? seen.offline + ? seen.at === undefined + ? t('agents.sections.offline', 'Offline') + : seenAgo + ? t('agents.sections.offlineSeenAgo', 'Offline · seen {{ago}} ago', { ago: seenAgo }) + : t('agents.sections.offlineSeenJustNow', 'Offline · seen just now') + : seenAgo + ? t('agents.sections.seenAgo', 'Seen {{ago}} ago', { ago: seenAgo }) + : t('agents.sections.seenJustNow', 'Seen just now') + : props.nameDesktop && (section.kind === 'workspace' || section.kind === 'project') + ? desktop + : undefined + return ( + + ) +} + +function AgentsEmpty(props: { title: string; message?: string }) { + useMobileColorScheme() + return ( + + + + {props.title} + + {props.message ? {props.message} : null} + + ) +} + +const styles = themedStyleSheet(() => ({ + content: { paddingHorizontal: spacing.lg }, + search: { marginHorizontal: spacing.lg, marginBottom: spacing.sm }, + filters: { paddingHorizontal: spacing.lg }, + menuValue: { flexDirection: 'row', alignItems: 'center', gap: 2 }, + connecting: { alignItems: 'center', paddingVertical: spacing.xl, marginTop: 32 }, + menuValueText: { fontSize: 15, color: colors.textMuted }, + empty: { + alignItems: 'center', + paddingHorizontal: spacing.xl, + paddingVertical: 28, + marginTop: 32, + gap: spacing.sm + }, + emptyTitle: { fontSize: 16, fontWeight: '600', color: colors.textPrimary }, + emptyBody: { fontSize: 14, lineHeight: 20, color: colors.textSecondary, textAlign: 'center' } +})) diff --git a/mobile/src/home/tabs/MobileHomeFeedTab.tsx b/mobile/src/home/tabs/MobileHomeFeedTab.tsx index 61809896ba5..68e1d7ad013 100644 --- a/mobile/src/home/tabs/MobileHomeFeedTab.tsx +++ b/mobile/src/home/tabs/MobileHomeFeedTab.tsx @@ -3,21 +3,22 @@ import { useMobileTranslation } from '../../i18n/use-mobile-translation' import { useResponsiveLayout } from '../../layout/responsive-layout' import { spacing } from '../../theme/mobile-theme' import { themedStyleSheet } from '../../theme/themed-styles' +import type { AgentListRowHandlers } from '../../agents/MobileAgentListRows' import type { HostCatalogEntry } from '../../transport/hosts/host-profile' -import type { HomeJumpBackInRow } from '../../worktree/home-jump-back-in' import { MobileHomeAppUpdateCard } from '../MobileHomeAppUpdateCard' import { MobileHomeEmptyState } from '../MobileHomeEmptyState' import { MobileHomeHostList } from '../MobileHomeHostList' -import { MobileHomeJumpBackIn } from '../MobileHomeJumpBackIn' +import { MobileHomeNeedsYou } from '../MobileHomeNeedsYou' import { MobileHomeTasksSection } from '../MobileHomeTasksSection' import type { MobileHomeData } from '../use-mobile-home-data' import { MobileHomeTabHeader } from './MobileHomeTabHeader' -/** Home's first tab: agents to get back to, the desktops, and Tasks. */ +/** Home's first tab: agents that need you, the desktops, and Tasks. */ export function MobileHomeFeedTab(props: { data: MobileHomeData bottomInset: number - onOpenWorktree: (row: HomeJumpBackInRow) => void + agentHandlers: AgentListRowHandlers + onSeeAllAgents: () => void onOpenHost: (host: HostCatalogEntry) => void onOpenHostActions: (host: HostCatalogEntry) => void onPairDesktop: () => void @@ -41,7 +42,7 @@ export function MobileHomeFeedTab(props: { /> ) } - const hasAgents = data.jumpBackInRows.length > 0 + const needsYou = data.agentsNeedingYou.length > 0 return ( <> {title} @@ -52,20 +53,22 @@ export function MobileHomeFeedTab(props: { isWideLayout && { maxWidth: contentMaxWidth, width: '100%', alignSelf: 'center' } ]} > - 1 const dot = statusDotColor(props.state ?? 'disconnected') return ( <> - } accessibilityLabel={ choosable ? t('home.tabs.chooseDesktop', '{{desktop}}, choose another desktop', { @@ -50,30 +50,8 @@ export function MobileHomeHostPill(props: { }) : title } - disabled={!choosable} - onPressIn={() => setPressed(true)} - onPressOut={() => setPressed(false)} - onPress={() => setOpen(true)} - style={styles.pillHit} - > - - - - {title} - - {choosable ? : null} - - + onPress={choosable ? () => setOpen(true) : undefined} + /> {choosable ? ( void +}) { + useMobileColorScheme() + const [pressed, setPressed] = useState(false) + const choosable = props.onPress !== undefined + return ( + setPressed(true)} + onPressOut={() => setPressed(false)} + onPress={props.onPress} + style={styles.pillHit} + > + + {props.leading} + + {props.label} + + {choosable ? : null} + + + ) +} + const styles = themedStyleSheet(() => ({ pillHit: { alignSelf: 'flex-start', maxWidth: '100%' }, pill: { diff --git a/mobile/src/home/tabs/MobileHomeTabBar.tsx b/mobile/src/home/tabs/MobileHomeTabBar.tsx index 3d9dad7e528..f5d84087a79 100644 --- a/mobile/src/home/tabs/MobileHomeTabBar.tsx +++ b/mobile/src/home/tabs/MobileHomeTabBar.tsx @@ -1,4 +1,11 @@ -import { CalendarClock, Gauge, LayoutList, Settings, type LucideIcon } from 'lucide-react-native' +import { + Bot, + CalendarClock, + Gauge, + LayoutList, + Settings, + type LucideIcon +} from 'lucide-react-native' import { useEffect, useState } from 'react' import { Platform, Pressable, StyleSheet, Text, View } from 'react-native' import Animated, { @@ -16,6 +23,7 @@ import { HOME_EASE_OUT, type HomeTabId } from './home-tabs' const TAB_ICONS: Record = { feed: LayoutList, + agents: Bot, usage: Gauge, automations: CalendarClock, settings: Settings @@ -27,14 +35,15 @@ export function MobileHomeTabBar(props: { tabs: readonly HomeTabId[] active: HomeTabId bottomInset: number - /** Agents that need you; shown on Feed. */ - feedBadge: number + /** Agents that need you; shown on Agents. */ + agentsBadge: number onSelect: (tab: HomeTabId) => void }) { const t = useMobileTranslation() useMobileColorScheme() const labels: Record = { feed: t('home.tabs.feed', 'Feed'), + agents: t('home.tabs.agents', 'Agents'), usage: t('home.tabs.usage', 'Usage'), automations: t('home.tabs.automations', 'Automations'), settings: t('common.settings', 'Settings') @@ -51,7 +60,7 @@ export function MobileHomeTabBar(props: { icon={TAB_ICONS[tab]} label={labels[tab]} selected={tab === props.active} - badge={tab === 'feed' ? props.feedBadge : 0} + badge={tab === 'agents' ? props.agentsBadge : 0} onPress={() => props.onSelect(tab)} /> ))} diff --git a/mobile/src/home/tabs/MobileHomeTabHeader.tsx b/mobile/src/home/tabs/MobileHomeTabHeader.tsx index 29b415be876..4e05b072cff 100644 --- a/mobile/src/home/tabs/MobileHomeTabHeader.tsx +++ b/mobile/src/home/tabs/MobileHomeTabHeader.tsx @@ -1,5 +1,5 @@ import type { LucideIcon } from 'lucide-react-native' -import { useState, type ReactNode } from 'react' +import { useState, type ReactNode, type Ref } from 'react' import { Pressable, Text, View } from 'react-native' import Animated from 'react-native-reanimated' import { colors, radii, spacing } from '../../theme/mobile-theme' @@ -20,11 +20,15 @@ export function MobileHomeTabHeader(props: { title: string; trailing?: ReactNode } export function MobileHomeTabHeaderButton(props: { + /** The anchor a pull-down menu drops from. */ + ref?: Ref icon: LucideIcon accessibilityLabel: string disabled?: boolean /** Spins the glyph while a refresh it started is in flight. */ spinning?: boolean + /** What the button opens is showing. */ + active?: boolean onPress: () => void }) { useMobileColorScheme() @@ -32,14 +36,23 @@ export function MobileHomeTabHeaderButton(props: { const Icon = props.icon return ( setPressed(true)} onPressOut={() => setPressed(false)} onPress={props.onPress} - style={[styles.button, pressed && styles.buttonPressed, props.disabled && styles.disabled]} + style={[ + styles.button, + (pressed || props.active) && styles.buttonPressed, + props.disabled && styles.disabled + ]} > ({ setWorktreeInfo, setStats: setStatsByHost, setAccounts: setAccountsByHost }), [] ) - const [lastVisited, setLastVisited] = useState<{ hostId: string; worktreeId: string } | null>( - null - ) const onboardingCheckedRef = useRef(false) const hydratedRef = useRef(false) const focusedRef = useRef(false) const isHomeFocused = useCallback(() => focusedRef.current, []) + // Drives the agent clock; Home stays mounted under other screens. + const [homeFocused, setHomeFocused] = useState(false) const hosts = useMemo(() => selectConnectableHostProfiles(hostCatalog), [hostCatalog]) const connections = useMobileHomeHostConnections(hosts, hostCatalog, hostSetters, isHomeFocused) const allClientsRef = useRef(connections.allClients) @@ -90,7 +85,10 @@ export function useMobileHomeData() { useEffect(() => { if (Object.keys(worktreeInfo).length > 0) { - saveHomeSnapshot({ worktreeInfo, savedAt: Date.now() }) + const saved = Object.fromEntries( + Object.entries(worktreeInfo).map(([hostId, info]) => [hostId, withoutHomeAgentStates(info)]) + ) + saveHomeSnapshot({ worktreeInfo: saved, savedAt: Date.now() }) } }, [worktreeInfo]) @@ -109,6 +107,7 @@ export function useMobileHomeData() { useCallback(() => { let stale = false focusedRef.current = true + setHomeFocused(true) void loadHostCatalog() // A failed read proves nothing about the desktops; keep the ones already shown. .catch((): HostCatalogEntry[] | null => null) @@ -130,11 +129,6 @@ export function useMobileHomeData() { router.replace(mobileOnboardingDestination(steps)) } }) - void AsyncStorage.getItem(LAST_VISITED_WORKTREE_STORAGE_KEY).then((raw) => { - if (!stale) { - setLastVisited(readLastVisitedWorktreeRecord(raw)) - } - }) for (const entry of allClientsRef.current) { if (entry.client.getState() === 'connected') { void fetchHomeHostWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => stale) @@ -144,32 +138,37 @@ export function useMobileHomeData() { return () => { stale = true focusedRef.current = false + setHomeFocused(false) } }, [router]) ) const sortedHosts = useMemo(() => sortHostsByLastConnected(hosts), [hosts]) const sortedHostCatalog = useMemo(() => sortHostsByLastConnected(hostCatalog), [hostCatalog]) - const resumeCard = useMemo( - () => - selectHomeResumeCard({ - hosts: sortedHosts, - hostStates: connections.hostStates, - worktreeInfo, - lastVisited, - cachedWorktrees: (hostId) => getCachedWorktrees(hostId) as HomeWorktreeSummary[] | null - }), - [sortedHosts, connections.hostStates, worktreeInfo, lastVisited] + // One clock for every agent count, so Feed, the Agents badge and each desktop agree. + const now = useNow(30_000, homeFocused) + const refetchHostAgents = useCallback((hostId: string) => { + const entry = allClientsRef.current.find((candidate) => candidate.hostId === hostId) + return entry?.client.getState() === 'connected' + ? fetchHomeHostWorktreeInfo(entry.client, hostId, setWorktreeInfo, () => false) + : Promise.resolve() + }, []) + const agentActivity = useAgentActivityWrites(connections.allClients, refetchHostAgents) + const { pendingActivity } = agentActivity + const agentList = useMemo( + () => ({ + hosts: sortedHosts, + hostStates: connections.hostStates, + worktreeInfo, + now, + pendingActivity + }), + [sortedHosts, connections.hostStates, worktreeInfo, now, pendingActivity] ) - const jumpBackInRows = useMemo( - () => - selectHomeJumpBackInRows({ - hosts: sortedHosts, - hostStates: connections.hostStates, - worktreeInfo, - resumeCard - }), - [sortedHosts, connections.hostStates, worktreeInfo, resumeCard] + const agentsNeedingYou = useMemo(() => selectAgentsNeedingYou(agentList), [agentList]) + const needsYouByHost = useMemo( + () => countAgentsNeedingYouByHost(agentsNeedingYou), + [agentsNeedingYou] ) const connectedHosts = useMemo( () => sortedHosts.filter((host) => connections.hostStates[host.id] === 'connected'), @@ -190,12 +189,15 @@ export function useMobileHomeData() { return { ...connections, accountsByHost, + applyAgentActivity: agentActivity.apply, + agentList, + agentsNeedingYou, connectedHosts, hostCatalog, hostCatalogLoaded, hostConnections, hostsConnecting, - jumpBackInRows, + needsYouByHost, router, setHostCatalog, sortedHostCatalog, diff --git a/mobile/src/home/use-mobile-home-host-connections.ts b/mobile/src/home/use-mobile-home-host-connections.ts index 17052ba6c3f..f29fbdbe557 100644 --- a/mobile/src/home/use-mobile-home-host-connections.ts +++ b/mobile/src/home/use-mobile-home-host-connections.ts @@ -14,7 +14,7 @@ import { fetchHomeHostWorktreeInfo, type HostWorktreeInfoSetter } from '../worktree/home-host-worktree-fetch' -import { withoutHomeAgentStates } from '../worktree/home-worktree-info' +import { withLastSeenHomeAgents } from '../worktree/home-worktree-info' import { fetchHomeHostStats, type HomeStatsSetter } from '../stats/home-stats-summary-read' import { readMobileHomeLastConnected, @@ -27,7 +27,9 @@ const HOME_WORKTREE_REFRESH_MIN_INTERVAL_MS = 3000 const WORKTREE_CHANGE_EVENTS: ReadonlySet = new Set([ 'sidebarInputsChanged', 'worktreesChanged', - 'reposChanged' + 'reposChanged', + // The desktop Agents list changed; worktree.ps carries its verdicts. + 'agentListChanged' ]) export type HomeAccountsSetter = ( @@ -107,7 +109,7 @@ function wireMobileHomeHostSubscriptions( // Agents keep moving while we're away; only the reconnect read may show their states again. setWorktreeInfo((previous) => { const current = previous[entry.hostId] - const next = current && withoutHomeAgentStates(current) + const next = current && withLastSeenHomeAgents(current) return next === current ? previous : { ...previous, [entry.hostId]: next } }) } diff --git a/mobile/src/host-screen/host-edit-navigation.test.ts b/mobile/src/host-screen/host-edit-navigation.test.ts deleted file mode 100644 index 29e143636c3..00000000000 --- a/mobile/src/host-screen/host-edit-navigation.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - navigateToMobileHostEdit, - type MobileHostEditNavigationState -} from './host-edit-navigation' - -function navigationHarness(initialState: MobileHostEditNavigationState) { - let stateListener = () => {} - let state = initialState - const unsubscribeState = vi.fn() - const navigation = { - addListener: vi.fn((_event: 'state', listener: () => void) => { - stateListener = listener - return unsubscribeState - }), - dispatch: vi.fn(), - getState: () => state - } - return { - navigation, - setState(nextState: MobileHostEditNavigationState) { - state = nextState - stateListener() - }, - unsubscribeState - } -} - -// Replacement targets the nested host stack, so committed fixtures must include it. -function committedHostState(hostIdParam: string): MobileHostEditNavigationState { - return { - index: 1, - routes: [ - { name: 'index' }, - { - name: 'h', - state: { - key: '/h', - index: 0, - routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId: hostIdParam } }] - } - } - ] - } -} - -describe('mobile host edit navigation', () => { - it('does not replace an unrelated host route', () => { - const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) - - navigateToMobileHostEdit(harness.navigation, { push: vi.fn(), replace: vi.fn() }, 'host-1') - harness.setState(committedHostState('host-2')) - - expect(harness.navigation.dispatch).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/host-screen/use-host-pending-view-changes.test.ts b/mobile/src/host-screen/use-host-pending-view-changes.test.ts index 4e1437288ab..29a393415cb 100644 --- a/mobile/src/host-screen/use-host-pending-view-changes.test.ts +++ b/mobile/src/host-screen/use-host-pending-view-changes.test.ts @@ -8,11 +8,9 @@ vi.mock('../../../src/shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUT import '../../../src/shared/rpc-contract/workspace-view-collapse-params' import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' import type { RpcResponse } from '../transport/rpc/rpc-wire-types' -import { INITIAL_MOBILE_VIEW } from '../worktree/workspace-view-settings' import { addPendingViewChange, reconcilePendingViewChanges, - withPendingViewChanges, type PendingViewChange } from './host-view-pending-changes' import { @@ -150,16 +148,6 @@ describe('pending changes over the desktop’s values', () => { collapsed }) - it('lay the desired values over the view, oldest first', () => { - const view = withPendingViewChanges(INITIAL_MOBILE_VIEW, [ - { opId: 1, sentAt: 0, kind: 'view', patch: { groupBy: 'none' }, payload: {} }, - collapse(2, true), - { opId: 3, sentAt: 0, kind: 'view', patch: { groupBy: 'pr-status' }, payload: {} } - ]) - expect(view.groupBy).toBe('pr-status') - expect(view.collapsedGroups).toEqual(['k']) - }) - it('keep only the latest intent for a section toggled twice', () => { const pending = addPendingViewChange([collapse(1, true)], collapse(2, false)) expect(pending.map((change) => change.opId)).toEqual([2]) diff --git a/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index d96869ea533..0e3e52d24b7 100644 --- a/mobile/src/i18n/en-runtime-required.json +++ b/mobile/src/i18n/en-runtime-required.json @@ -9,6 +9,18 @@ "messages_other": "{{count}} messages" } }, + "agents": { + "desktops": { + "agents_one": "{{count}} agent", + "agents_other": "{{count}} agents", + "needsYou_one": "{{count}} needs you", + "needsYou_other": "{{count}} need you" + }, + "list": { + "workers_one": "{{count}} worker", + "workers_other": "{{count}} workers" + } + }, "app": { "terminalSettings": { "restoreAfterMinutes_one": "After {{count}} minute", diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 895b87f3cef..a2da39a8e47 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -1411,12 +1411,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} aktiv", - "heading": "Agenten", - "showAll": "Alle {{count}} anzeigen", - "showFewer": "Weniger anzeigen" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Update-Hinweis für Orca {{version}} ausblenden", "title": "Orca {{version}} ist verfügbar", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 82349083240..9fad7a8ed7b 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -557,10 +557,6 @@ "desktops": { "pairDesktop": "Pair a desktop" }, - "jumpBackIn": { - "lastOpened": "Last opened", - "connectToOpen": "Connect {{desktop}} to open" - }, "sections": { "tasks": "Tasks", "tasksSubtitle": "Browse your issues and reviews" @@ -574,12 +570,6 @@ "hours": "{{hours}}h", "minutes": "{{minutes}}m" }, - "agents": { - "heading": "Agents", - "activeCount": "{{count}} active", - "showFewer": "Show fewer", - "showAll": "Show all {{count}}" - }, "automationsTab": { "newAutomation": "New automation", "lastStatus": "Last: {{status}}", @@ -598,7 +588,8 @@ "automations": "Automations", "feed": "Feed", "chooseDesktop": "{{desktop}}, choose another desktop", - "usage": "Usage" + "usage": "Usage", + "agents": "Agents" }, "usage": { "refresh": "Refresh usage", @@ -611,6 +602,10 @@ "active": "Active", "openAccountsHint": "Opens this desktop’s accounts", "emptyTitle": "No usage yet" + }, + "needsYou": { + "heading": "Needs you", + "seeAll": "See all agents" } }, "hooks": { @@ -900,7 +895,8 @@ "hours_other": "{{count}}h", "days_one": "{{count}}d", "days_other": "{{count}}d", - "done": "Done" + "done": "Done", + "permission": "Needs attention" }, "hostWorkspaceListStates": { "checkHost": "Check that your computer is awake and Orca is running", @@ -4755,5 +4751,83 @@ "renameUnconfirmed": "Not confirmed yet. Orca checks the name when {{host}} is back.", "saving": "Saving", "serverUnreachable": "Its server can't be reached." + }, + "agents": { + "list": { + "idleCount": "{{count}} idle", + "offlineTitle": "{{desktop}} is offline", + "offlineMessage": "Reconnect it to open this agent.", + "actions": "Actions for {{title}}", + "workers_one": "{{count}} worker", + "workers_other": "{{count}} workers", + "noMatches": "No agents match “{{query}}”", + "emptyTitle": "No agents running", + "pairDesktop": "Pair a desktop to see its agents here.", + "emptyBody": "Start an agent in any workspace and it shows up here.", + "unread": "Unread", + "noDesktopTitle": "No desktop connected", + "noDesktopBody": "Agents show up here once a desktop connects.", + "hideWorkers": "Hide {{workers}}", + "showWorkers": "Show {{workers}}" + }, + "actions": { + "offlineHint": "Its desktop is offline.", + "open": "Open", + "goToWorkspace": "Go to workspace", + "copyTitle": "Copy title", + "copied": "Copied", + "copyFailed": "Couldn’t copy the title", + "markRead": "Mark as read", + "markUnread": "Mark as unread", + "clear": "Clear from list" + }, + "groupBy": { + "status": "Status", + "workspace": "Workspace", + "project": "Project", + "agent": "Agent", + "desktop": "Desktop" + }, + "options": { + "groupBy": "Group by", + "showWorkers": "Show worker agents", + "open": "Agent list options", + "unreadOnly": "Unread only", + "markAllRead": "Mark all read", + "clearFinished": "Clear finished" + }, + "search": { + "toggle": "Search agents", + "placeholder": "Search agents" + }, + "desktops": { + "pickerTitle": "Show agents on", + "agents_one": "{{count}} agent", + "agents_other": "{{count}} agents", + "all": "All desktops", + "offline": "Offline", + "needsYou_one": "{{count}} needs you", + "needsYou_other": "{{count}} need you" + }, + "sections": { + "needsYou": "Needs you", + "working": "Working", + "done": "Done", + "offline": "Offline", + "offlineSeenAgo": "Offline · seen {{ago}} ago", + "offlineSeenJustNow": "Offline · seen just now", + "seenAgo": "Seen {{ago}} ago", + "seenJustNow": "Seen just now", + "clear": "Clear" + }, + "swipe": { + "read": "Read", + "unread": "Unread", + "clear": "Clear" + }, + "activity": { + "needsWindow": "Couldn’t update. Open Orca on {{desktop}}.", + "failed": "Couldn’t update the agent list." + } } } diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index f243326969a..615bc3008fa 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -1450,12 +1450,6 @@ } }, "home": { - "agents": { - "activeCount": "Activos: {{count}}", - "heading": "Agentes", - "showAll": "Mostrar todos ({{count}})", - "showFewer": "Mostrar menos" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Descartar la actualización de Orca {{version}}", "title": "Orca {{version}} está disponible", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index 1ca9a89435f..b4968d0c4b4 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -1450,12 +1450,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} en activité", - "heading": "Agents", - "showAll": "Tout afficher ({{count}})", - "showFewer": "Afficher moins" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Ignorer la mise à jour Orca {{version}}", "title": "Orca {{version}} est disponible", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index a355885573f..41b59f00545 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} 件がアクティブ", - "heading": "Agent", - "showAll": "{{count}} 件をすべて表示", - "showFewer": "折りたたむ" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Orca {{version}} の更新通知を閉じる", "title": "Orca {{version}} が利用可能です", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index 3839cc56e5a..7c34395812a 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "활성 {{count}}개", - "heading": "에이전트", - "showAll": "{{count}}개 모두 보기", - "showFewer": "접기" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Orca {{version}} 업데이트 알림 닫기", "title": "Orca {{version}} 업데이트 가능", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index f61c5108c01..fb83a84674d 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -1450,12 +1450,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} em atividade", - "heading": "Agentes", - "showAll": "Mostrar todos ({{count}})", - "showFewer": "Mostrar menos" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Descartar atualização do Orca {{version}}", "title": "Orca {{version}} está disponível", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 2361a23e865..9ced7c69b59 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -1489,12 +1489,6 @@ } }, "home": { - "agents": { - "activeCount": "Активных: {{count}}", - "heading": "Агенты", - "showAll": "Показать все ({{count}})", - "showFewer": "Свернуть" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Скрыть уведомление об обновлении Orca {{version}}", "title": "Доступна Orca {{version}}", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index 51d30ec5537..f103d17aec0 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -1411,12 +1411,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} etkin", - "heading": "Ajanlar", - "showAll": "Tümünü göster ({{count}})", - "showFewer": "Daha az göster" - }, "appUpdateCard": { "dismissAccessibilityLabel": "Orca {{version}} güncellemesini gizle", "title": "Orca {{version}} sürümü mevcut", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 552b77a5435..b41f7765fec 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} 個使用中", - "heading": "代理程式", - "showAll": "顯示全部 {{count}} 個", - "showFewer": "收合" - }, "appUpdateCard": { "dismissAccessibilityLabel": "關閉 Orca {{version}} 更新提示", "title": "Orca {{version}} 已推出", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 84c03919729..b99d10462d5 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -1407,12 +1407,6 @@ } }, "home": { - "agents": { - "activeCount": "{{count}} 个活跃", - "heading": "智能体", - "showAll": "显示全部 {{count}} 个", - "showFewer": "收起" - }, "appUpdateCard": { "dismissAccessibilityLabel": "关闭 Orca {{version}} 更新提示", "title": "Orca {{version}} 已可用", diff --git a/mobile/src/mobile-web-shell/bridge-terminal-output-backlog.test.ts b/mobile/src/mobile-web-shell/bridge-terminal-output-backlog.test.ts index 0a0d6847e6d..16925a5476a 100644 --- a/mobile/src/mobile-web-shell/bridge-terminal-output-backlog.test.ts +++ b/mobile/src/mobile-web-shell/bridge-terminal-output-backlog.test.ts @@ -135,30 +135,3 @@ describe('the cases the rulings name', () => { expect(bridge.frames().some((frame) => frame.type === 'end')).toBe(false) }) }) - -// Test the enforced half of the desktop snapshot budget: a serialized payload at budget crosses, and one over frame cap is refused. -describe('a snapshot payload at the budget the page asks for', () => { - function scrollbackPayload(payloadBytes: number): unknown { - const skeleton = JSON.stringify({ type: 'scrollback', streamId: 1, serialized: '' }).length - return { type: 'scrollback', streamId: 1, serialized: 'x'.repeat(payloadBytes - skeleton) } - } - - function post(payloadBytes: number): ReturnType { - const bridge = harness({ ready: true, terminalTimers: manualTimers() }) - bridge.host.receive( - clientFrame({ type: 'subscribe', id: ID, method: 'terminal.subscribe', params: {} }) - ) - const payload = scrollbackPayload(payloadBytes) - expect(JSON.stringify(payload)).toHaveLength(payloadBytes) - bridge.client.streams[0].emit(payload) - return bridge - } - - it('ends the stream on a payload the cap cannot hold, which is why the host trims', () => { - // A host-budgeted snapshot must never reach this refusal; the page cannot detect a silently omitted event (C0.3). - const bridge = post(BRIDGE_MAX_MESSAGE_BYTES) - expect(bridge.frames().filter((frame) => frame.type === 'end')).toEqual([ - { v: 1, type: 'end', id: ID, reason: 'overflow' } - ]) - }) -}) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts index 749ff857459..cc1176e49fc 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.test.ts @@ -27,20 +27,6 @@ afterEach(() => { }) describe('bridge client refusals and send failures', () => { - it('reports a frame its own reader will not take, and changes nothing', () => { - const page = createPageClient() - page.start() - page.deliverRaw('{ not json') - page.deliverRaw(JSON.stringify({ v: 99, type: 'state' })) - page.deliverRaw(`"${'z'.repeat(BRIDGE_MAX_MESSAGE_BYTES)}"`) - expect(page.diagnostics).toEqual([ - { kind: 'refused', refusal: 'malformed-json' }, - { kind: 'refused', refusal: 'unrecognised-message' }, - { kind: 'refused', refusal: 'oversized' } - ]) - expect(page.client.getState()).toBe('connected') - }) - it('settles the request a reply it could not read was answering, on the same turn', async () => { const page = createPageClient() page.start() diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts index 32deb95c0b9..160a2128909 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from 'vitest' -import { BRIDGE_MAX_MESSAGE_BYTES } from './bridge-caps' - import { BRIDGE_PROTOCOL_VERSION, readBridgeClientMessage, @@ -29,12 +27,6 @@ function client(fields: Record): Record { return { v: BRIDGE_PROTOCOL_VERSION, ...fields } } -describe('client messages', () => { - it('carries the frame refusal through rather than relabelling it', () => { - expect(readBridgeClientMessage('{')).toEqual({ ok: false, refusal: 'malformed-json' }) - }) -}) - describe('the readers bound their two directions differently', () => { const records = Array.from({ length: 5_000 }, (_, index) => ({ id: index, @@ -63,20 +55,6 @@ describe('the readers bound their two directions differently', () => { readClient(client({ type: 'request', id: ID, method: 'worktree.list', params: { records } })) ).toEqual({ ok: false, refusal: 'too-many-nodes' }) }) - - it('still refuses a host frame one byte over the frame cap', () => { - const envelope = (result: string) => - JSON.stringify({ - v: BRIDGE_PROTOCOL_VERSION, - type: 'reply', - id: ID, - payload: { ...SUCCESS_PAYLOAD, result } - }) - const overhead = new TextEncoder().encode(envelope('')).byteLength - const raw = envelope('x'.repeat(BRIDGE_MAX_MESSAGE_BYTES + 1 - overhead)) - expect(new TextEncoder().encode(raw).byteLength).toBe(BRIDGE_MAX_MESSAGE_BYTES + 1) - expect(readBridgeHostMessage(raw)).toEqual({ ok: false, refusal: 'oversized' }) - }) }) // Pathnames and returned navigation hrefs share one segment rule; disagreement would expose a path through notify. diff --git a/mobile/src/mobile-web-shell/bridge/use-native-verbs.test.tsx b/mobile/src/mobile-web-shell/bridge/use-native-verbs.test.tsx index 935fe32d82f..5939d383360 100644 --- a/mobile/src/mobile-web-shell/bridge/use-native-verbs.test.tsx +++ b/mobile/src/mobile-web-shell/bridge/use-native-verbs.test.tsx @@ -42,26 +42,6 @@ afterEach(() => { // The typed member must reject desktop methods too; widened callers could otherwise bypass the raw-port inventory’s call shapes. -// Preserve one typed refusal with a stable code; callers must not distinguish recovery actions by message text. -describe('a verb the shell refuses', () => { - it('names the grant when this side refused before sending', async () => { - const page = createPageClient() - page.deliver({ ...INIT, grants: { ...GRANTS, native: ['navigate'] } }) - act(() => { - create( - - - - ) - }) - const verbs = held.verbs - if (verbs === null) { - throw new Error('nothing mounted') - } - await expect(verbs.readClipboardText()).rejects.toMatchObject({ reason: 'ungranted' }) - }) -}) - describe('a code this page has never heard of', () => { it('floors to unreported rather than crossing verbatim', async () => { // Inject a newer-shell code directly; this host normalizes unknown codes before sending, so the pair cannot produce it itself. diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-agent-history-route.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-agent-history-route.test.tsx deleted file mode 100644 index 1b20fb81e04..00000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-agent-history-route.test.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import { createElement } from 'react' -import { act, create } from 'react-test-renderer' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -type RouteDependencies = { - routes: { pathname: string; params?: Record }[] - refusals: string[] - lifecycle: string[] - params: Record -} - -const dependencies = vi.hoisted((): RouteDependencies => ({ - routes: [], - refusals: [], - lifecycle: [], - params: {} -})) - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { getItem: async () => null, setItem: async () => {} } -})) - -vi.mock('react-native', () => ({ - StyleSheet: { create: (styles: unknown) => styles }, - View: 'View' -})) - -vi.mock('../transport/connection/host-client-hooks', () => ({ - useHostClient: () => ({ client: null, state: 'disconnected' }) -})) -vi.mock('../worktree/workspace-server', () => ({ - useWorkspaceServer: () => ({ routeHost: undefined, server: null }) -})) -vi.mock('expo-router', () => ({ useLocalSearchParams: () => dependencies.params })) - -vi.mock('./PageRouteUnavailableScreen', () => ({ - PageRouteUnavailableScreen: (props: { hostId: string }) => { - dependencies.refusals.push(props.hostId) - return null - } -})) - -vi.mock('./MobileWebShellScreen', async () => { - const React = await import('react') - return { - MobileWebShellScreen: (props: { - hostId: string - route: { pathname: string; params?: Record } - }) => { - dependencies.routes.push(props.route) - // Keep deps empty: pathname-driven effects would also run on prop updates and falsely look like remounts. - const mountedAs = React.useRef(props.route.pathname) - React.useEffect(() => { - const pathname = mountedAs.current - dependencies.lifecycle.push(`mount:${pathname}`) - return () => { - dependencies.lifecycle.push(`unmount:${pathname}`) - } - }, []) - return null - } - } -}) - -import MobileAgentSessionHistoryScreen from '../../app/h/[hostId]/agent-history/[worktreeId]' - -async function renderRoute(): Promise { - await act(async () => { - create(createElement(MobileAgentSessionHistoryScreen)) - }) -} - -describe('the agent-history route that hands off to the shell', () => { - beforeEach(() => { - dependencies.routes.length = 0 - dependencies.refusals.length = 0 - dependencies.lifecycle.length = 0 - dependencies.params = { hostId: 'host-1', worktreeId: 'wt-1', name: 'my worktree' } - }) - - // encodeURIComponent leaves dot segments intact; refuse them before constructing a route the bridge rejects. - - it('refuses a dot-segment worktree id too, which is the other segment', async () => { - dependencies.params = { hostId: 'host-1', worktreeId: '..', name: 'n' } - await renderRoute() - expect(dependencies.routes).toEqual([]) - expect(dependencies.refusals.at(-1)).toBe('host-1') - }) - - it('refuses when the route names no worktree, which the shell could not open', async () => { - dependencies.params = { hostId: 'host-1' } - await renderRoute() - expect(dependencies.routes).toEqual([]) - expect(dependencies.refusals.at(-1)).toBe('host-1') - }) - - // Remount on route change to dispose the bridge that captured the previous route’s grants. -}) diff --git a/mobile/src/navigation/use-back-claim.web.test.tsx b/mobile/src/navigation/use-back-claim.web.test.tsx deleted file mode 100644 index fd62fe7c043..00000000000 --- a/mobile/src/navigation/use-back-claim.web.test.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import { - createPageBackConsumers, - type PageBackConsumers -} from '../mobile-web-shell/bridge/page-back-consumers' - -type PageBackProbe = { - claims: boolean[] - unclaimed: Mock - consumers: PageBackConsumers | null -} - -// Build the real stack after imports, not inside vi.hoisted, so no fake duplicates the behavior under test. -const page = vi.hoisted((): PageBackProbe => ({ claims: [], unclaimed: vi.fn(), consumers: null })) - -vi.mock('../transport/connection/client-context.web', () => ({ - usePageBridgeClientIfPresent: () => - page.consumers === null ? null : { claimBack: (claim: () => boolean) => stack().claim(claim) } -})) - -import { useBackClaim } from './use-back-claim.web' - -function stack(): PageBackConsumers { - if (page.consumers === null) { - throw new Error('the page back stack was not built for this case') - } - return page.consumers -} - -function Screen({ claim }: { claim: (() => boolean) | null }): null { - useBackClaim(claim) - return null -} - -const trees: ReactTestRenderer[] = [] - -function render(claim: (() => boolean) | null): ReactTestRenderer { - let tree!: ReactTestRenderer - act(() => { - tree = create(createElement(Screen, { claim })) - }) - trees.push(tree) - return tree -} - -beforeEach(() => { - page.claims.length = 0 - page.unclaimed.mockClear() - page.consumers = createPageBackConsumers({ - publishClaim: (claimed) => page.claims.push(claimed), - onUnclaimed: page.unclaimed - }) -}) - -afterEach(() => { - act(() => { - for (const tree of trees.splice(0)) { - tree.unmount() - } - }) - page.consumers = null -}) - -// RN Web BackHandler is inert, so sheets must claim the shell’s key through the bridge. -describe('a page screen claiming the device Back key from the shell', () => { - // Shared drawers can mount without a page provider; no available shell means no claim, never a thrown render. - it('claims nothing, and does not throw, outside the page bridge', () => { - page.consumers = null - expect(() => render(() => true)).not.toThrow() - expect(page.claims).toEqual([]) - }) -}) diff --git a/mobile/src/new-workspace/NewWorkspacePageScreen.test.tsx b/mobile/src/new-workspace/NewWorkspacePageScreen.test.tsx deleted file mode 100644 index 4e655519554..00000000000 --- a/mobile/src/new-workspace/NewWorkspacePageScreen.test.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const handoff = vi.hoisted(() => ({ back: vi.fn(), replace: vi.fn() })) - -vi.mock('expo-router', () => ({ useLocalSearchParams: () => ({ hostId: 'laptop' }) })) -vi.mock('../navigation/route-handoff', () => ({ useRouteHandoff: () => handoff })) -vi.mock('../transport/connection/host-client-hooks', () => ({ - useHostClient: () => ({ client: null, state: 'connected' }) -})) -vi.mock('../components/host-protocol-gates-context', () => ({ - useHostProtocolGates: () => ({ hostCapabilities: ['cap'] }) -})) -vi.mock('./use-host-worktree-rows', () => ({ - useHostWorktreeRows: () => [{ path: '/repo/marlin', repoId: 'r1', branch: 'marlin' }] -})) -vi.mock('../platform/external-link', () => ({ openExternalLink: vi.fn() })) -vi.mock('../components/NewWorktreeModalController', () => ({ - NewWorktreeModalController: 'NewWorktreeModalController' -})) - -import { NewWorkspacePageScreen } from './NewWorkspacePageScreen' - -describe('the Create Workspace page', () => { - let renderer: ReactTestRenderer | null = null - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - vi.clearAllMocks() - }) - - async function render() { - await act(async () => { - renderer = create(createElement(NewWorkspacePageScreen)) - }) - return renderer!.root.find((node) => String(node.type) === 'NewWorktreeModalController') - } - - it("opens the new workspace's session in the overlay's place", async () => { - const drawer = await render() - - act(() => drawer.props.onCreated('wt-1', 'Hammerhead', 'No startup terminal', 'ssh:box')) - - expect(handoff.replace).toHaveBeenCalledWith( - '/h/laptop/session/wt-1?name=Hammerhead&created=1&warning=No+startup+terminal&executionHost=ssh%3Abox' - ) - }) -}) diff --git a/mobile/src/new-workspace/new-workspace-overlay-route.test.tsx b/mobile/src/new-workspace/new-workspace-overlay-route.test.tsx deleted file mode 100644 index 20516821058..00000000000 --- a/mobile/src/new-workspace/new-workspace-overlay-route.test.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' - -const router = vi.hoisted(() => ({ back: vi.fn(), push: vi.fn(), replace: vi.fn() })) -const params = vi.hoisted((): { current: Record } => ({ current: {} })) -const catalog = vi.hoisted((): { current: HostCatalogEntry[] } => ({ current: [] })) - -vi.mock('expo-router', () => ({ - useLocalSearchParams: () => params.current, - useRouter: () => router -})) -vi.mock('../transport/hosts/host-store', () => ({ - loadHostCatalog: async () => catalog.current -})) -vi.mock('../components/PickerModal', () => ({ PickerModal: 'PickerModal' })) -vi.mock('./NewWorkspaceOverlay', () => ({ NewWorkspaceOverlay: 'NewWorkspaceOverlay' })) - -import NewWorkspaceOverlayRoute from '../../app/new-workspace' -import { newWorkspaceOverlayHref } from './new-workspace-overlay-route' - -function entry(id: string, name: string): HostCatalogEntry { - const profile: HostProfile = { - id, - name, - endpoint: `ws://${id}.local:6768`, - deviceToken: `token-${id}`, - publicKeyB64: `key-${id}`, - lastConnected: 1 - } - const { deviceToken: _deviceToken, ...listed } = profile - return { ...listed, credentialStatus: 'ready', profile } -} - -describe("Home's New Workspace overlay", () => { - let renderer: ReactTestRenderer | null = null - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - vi.clearAllMocks() - }) - - async function open(hostIds: string[]) { - params.current = newWorkspaceOverlayHref(hostIds).params - await act(async () => { - renderer = create(createElement(NewWorkspaceOverlayRoute)) - }) - const root = renderer!.root - return { - overlayFor: () => - root.findAll((node) => String(node.type) === 'NewWorkspaceOverlay')[0]?.props.hostId, - picker: () => root.find((node) => String(node.type) === 'PickerModal') - } - } - - it("opens the only offered desktop's drawer without asking", async () => { - catalog.current = [entry('desk', 'Desk')] - const overlay = await open(['desk']) - - expect(overlay.overlayFor()).toBe('desk') - }) -}) diff --git a/mobile/src/notifications/push-dismissal-reconciliation.test.ts b/mobile/src/notifications/push-dismissal-reconciliation.test.ts deleted file mode 100644 index c85929997d1..00000000000 --- a/mobile/src/notifications/push-dismissal-reconciliation.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import * as Notifications from 'expo-notifications' -import { loadHostCatalog } from '../transport/hosts/host-store' -import { deriveHostFingerprint } from './push-host-fingerprint' -import { requestNotificationCatchup } from './push-dismissal-reconciliation' -vi.mock('../transport/hosts/host-store', () => ({ loadHostCatalog: vi.fn() })) -vi.mock('expo-notifications', () => ({ - getPresentedNotificationsAsync: vi.fn(), - dismissNotificationAsync: vi.fn() -})) -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { getItem: async () => null, setItem: async () => {} } -})) -const publicKeyB64 = Buffer.alloc(32, 1).toString('base64') -const hostFingerprint = deriveHostFingerprint(publicKeyB64) -const id = { - notificationId: 'old-alert', - notificationEpoch: 'previous-host-process', - notificationSeq: 12 -} -function presented(identifier: string, overrides = {}) { - return { request: { identifier, content: { data: { hostFingerprint, ...id, ...overrides } } } } -} -beforeEach(() => { - vi.clearAllMocks() - vi.mocked(loadHostCatalog).mockResolvedValue([{ id: 'host-a', publicKeyB64 }] as never) - vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ - presented('old'), - presented('new', { notificationSeq: 14 }), - presented('other', { hostFingerprint: 'other-host' }) - ] as never) - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) -}) - -it('keeps alerts when an old host omits reconciliation or the request fails', async () => { - for (const response of [{ ok: true, result: { notifications: [] } }, { ok: false }]) { - await requestNotificationCatchup( - { sendRequest: async () => response } as never, - 'host-a', - () => false - ) - } - expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled() -}) diff --git a/mobile/src/notifications/push-socket-dismissal.test.ts b/mobile/src/notifications/push-socket-dismissal.test.ts deleted file mode 100644 index 2c915f71c2b..00000000000 --- a/mobile/src/notifications/push-socket-dismissal.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { expect, it, vi } from 'vitest' -import * as Notifications from 'expo-notifications' -import { loadHostCatalog } from '../transport/hosts/host-store' -import { deriveHostFingerprint } from './push-host-fingerprint' -import { dismissHostPushNotification } from './push-socket-dismissal' -vi.mock('../transport/hosts/host-store', () => ({ loadHostCatalog: vi.fn() })) -vi.mock('expo-notifications', () => ({ - getPresentedNotificationsAsync: vi.fn(), - dismissNotificationAsync: vi.fn() -})) -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { getItem: async () => null, setItem: async () => undefined } -})) - -it('a socket dismissal cannot clear another desktop or a newer notification', async () => { - const publicKeyB64 = Buffer.alloc(32, 1).toString('base64') - vi.mocked(loadHostCatalog).mockResolvedValue([{ id: 'host-a', publicKeyB64 }] as never) - const hostFingerprint = deriveHostFingerprint(publicKeyB64) - const event = { - type: 'dismiss' as const, - notificationId: 'same', - notificationEpoch: 'epoch', - notificationSeq: 2 - } - const presented = (identifier: string, overrides: Record) => ({ - request: { identifier, content: { data: { hostFingerprint, ...event, ...overrides } } } - }) - vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ - presented('older', { notificationSeq: 1 }), - presented('newer', { notificationSeq: 3 }), - presented('other', { hostFingerprint: 'other-host' }), - presented('restarted', { notificationEpoch: 'new-epoch' }) - ] as never) - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - await dismissHostPushNotification(event, 'host-a') - expect(vi.mocked(Notifications.dismissNotificationAsync).mock.calls).toEqual([['older']]) -}) diff --git a/mobile/src/pairing/mobile-relay-physical-client.test.ts b/mobile/src/pairing/mobile-relay-physical-client.test.ts index cc5545b4951..8f46c64333b 100644 --- a/mobile/src/pairing/mobile-relay-physical-client.test.ts +++ b/mobile/src/pairing/mobile-relay-physical-client.test.ts @@ -104,21 +104,6 @@ describe('mobile relay physical pairing client', () => { await expect(status).rejects.toEqual(new RelayOuterError(4409)) }) - it('classifies an opaque close after transport error as 1006', async () => { - const socket = new FakeSocket() - const client = connectMobileRelayForPairing({ - relay, - deviceToken: 'device-token', - desktopPublicKeyB64: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', - createSocket: () => pairingWebSocket(socket) - }) - const status = client.sendRequest('status.get') - socket.onerror?.() - socket.onclose?.({ code: 0 }) - - await expect(status).rejects.toEqual(new RelayOuterError(1006)) - }) - it('settles after an error when the platform never emits close', async () => { vi.useFakeTimers() try { diff --git a/mobile/src/query/host-event-router.ts b/mobile/src/query/host-event-router.ts index 183abafd797..f26fb5f360a 100644 --- a/mobile/src/query/host-event-router.ts +++ b/mobile/src/query/host-event-router.ts @@ -1,4 +1,4 @@ -import { useEffect } from 'react' +import { useCallback, useEffect, useSyncExternalStore } from 'react' import { focusManager, useQueryClient, type Query, type QueryClient } from '@tanstack/react-query' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { @@ -18,23 +18,48 @@ function targetOf(query: Query): HostQueryKey[3] { return (query.queryKey as HostQueryKey)[3] } -const trailingReads = new WeakMap>() +// What to do once a read already out settles: read again, or only mark the answer stale. +type AfterRead = 'refetch' | 'stale' -function trailingReadsOf(queryClient: QueryClient): Set { - const existing = trailingReads.get(queryClient) +const afterReads = new WeakMap>() + +function afterReadsOf(queryClient: QueryClient): Map { + const existing = afterReads.get(queryClient) if (existing) { return existing } - const hashes = new Set() - trailingReads.set(queryClient, hashes) + const pending = new Map() + afterReads.set(queryClient, pending) // One cache listener per world, for as long as the world's client lives. queryClient.getQueryCache().subscribe(({ type, query }) => { - if (type === 'updated' && hashes.has(query.queryHash) && query.state.fetchStatus === 'idle') { - hashes.delete(query.queryHash) - refetchHostQueryAfterInFlight(queryClient, query) + const after = pending.get(query.queryHash) + if (type === 'updated' && after && query.state.fetchStatus === 'idle') { + pending.delete(query.queryHash) + if (after === 'refetch') { + refetchHostQueryAfterInFlight(queryClient, query) + } else { + void markStale(queryClient, query) + } } }) - return hashes + return pending +} + +function markStale(queryClient: QueryClient, query: Query): Promise { + return queryClient.invalidateQueries({ + queryKey: query.queryKey, + exact: true, + refetchType: 'none' + }) +} + +// A read already out may predate the change, and its answer would clear the mark; mark again once it lands. +function markStaleAfterInFlight(queryClient: QueryClient, query: Query): void { + void markStale(queryClient, query) + const pending = afterReadsOf(queryClient) + if (query.state.fetchStatus === 'fetching' && !pending.has(query.queryHash)) { + pending.set(query.queryHash, 'stale') + } } /** @@ -43,7 +68,7 @@ function trailingReadsOf(queryClient: QueryClient): Set { */ export function refetchHostQueryAfterInFlight(queryClient: QueryClient, query: Query): void { if (query.state.fetchStatus === 'fetching') { - trailingReadsOf(queryClient).add(query.queryHash) + afterReadsOf(queryClient).set(query.queryHash, 'refetch') return } void queryClient.refetchQueries( @@ -52,12 +77,28 @@ export function refetchHostQueryAfterInFlight(queryClient: QueryClient, query: Q ) } +type RouterHandle = { + stop: () => void + isReady: () => boolean + onReadyChange: (listener: () => void) => () => void +} + function startHostEventRouter( queryClient: QueryClient, hostId: string, client: RpcClient -): () => void { - // When the stream last said it was live; a replayed ready may have missed events since. +): RouterHandle { + const startedAt = Date.now() + // Whether the stream is live now, i.e. a change on the host would reach this router. + let ready = false + const readyListeners = new Set<() => void>() + const setReady = (next: boolean): void => { + if (next !== ready) { + ready = next + readyListeners.forEach((listener) => listener()) + } + } + // When the stream last said it was live (0: never); a replayed ready may have missed events since. let readyAt = 0 const floorTimers = new Map>() const signalledQueries = (matches: (signal: HostQuerySignal, query: Query) => boolean): Query[] => @@ -68,13 +109,11 @@ function startHostEventRouter( return signal !== undefined && matches(signal, query) } }) - const markStale = (query: Query): Promise => - queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true, refetchType: 'none' }) // Unobserved or hidden: stale only, so the next mount or foreground reads it. const readsNow = (query: Query): boolean => query.isActive() && focusManager.isFocused() const onChange = (query: Query): void => { - void markStale(query) + markStaleAfterInFlight(queryClient, query) if (!readsNow(query) || floorTimers.has(query.queryHash)) { return } @@ -97,10 +136,8 @@ function startHostEventRouter( ) } - const onReplayedReady = (missedSince: number): void => { - // After a reconnect, the connected edge already re-read every observed query; a replay with no reconnect (a path switch) did not. - const connectedAt = client.getLastConnectedAt() ?? 0 - const readSince = connectedAt > missedSince ? connectedAt : Infinity + // Reads again (or marks stale, when no one watches) every answer older than `readSince`. + const catchUp = (readSince: number): void => { for (const query of signalledQueries(() => true)) { if (query.state.fetchStatus === 'fetching' || query.state.dataUpdatedAt >= readSince) { continue @@ -108,22 +145,33 @@ function startHostEventRouter( if (readsNow(query)) { void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }) } else { - void markStale(query) + void markStale(queryClient, query) } } } + const onReplayedReady = (missedSince: number): void => { + // After a reconnect, the connected edge already re-read every observed query; a replay with no reconnect (a path switch) did not. + const connectedAt = client.getLastConnectedAt() ?? 0 + catchUp(connectedAt > missedSince ? connectedAt : Infinity) + } + const onEvent = (event: SharedClientEvent): void => { if (event.type === 'ready') { // Events are not queued while disconnected or between a stream's end and its reopen. if ('replayed' in event) { onReplayedReady(readyAt) + } else if (readyAt === 0) { + // Answers cached before this router started were read while nothing heard the host. + catchUp(startedAt) } readyAt = Date.now() + setReady(true) return } if (event.type === 'end' || event.type === 'error') { // The shared stream opens again by itself; its next ready re-reads what was missed. + setReady(false) return } const signalled: HostSignalEvent = event @@ -136,16 +184,24 @@ function startHostEventRouter( } const stopStream = subscribeSharedClientEvents(client, onEvent) - return () => { - stopStream() - for (const timer of floorTimers.values()) { - clearTimeout(timer) + return { + stop: () => { + stopStream() + for (const timer of floorTimers.values()) { + clearTimeout(timer) + } + floorTimers.clear() + readyListeners.clear() + }, + isReady: () => ready, + onReadyChange: (listener) => { + readyListeners.add(listener) + return () => readyListeners.delete(listener) } - floorTimers.clear() } } -type Router = { holders: number; stop: () => void } +type Router = { holders: number; handle: RouterHandle } const routers = new WeakMap>() @@ -154,7 +210,7 @@ function retainHostEventRouter( queryClient: QueryClient, hostId: string, client: RpcClient -): () => void { +): { handle: RouterHandle; release: () => void } { let byClient = routers.get(queryClient) if (!byClient) { byClient = new Map() @@ -163,25 +219,55 @@ function retainHostEventRouter( const clients = byClient let router = clients.get(client) if (!router) { - router = { holders: 0, stop: startHostEventRouter(queryClient, hostId, client) } + router = { holders: 0, handle: startHostEventRouter(queryClient, hostId, client) } clients.set(client, router) } const held = router held.holders += 1 - return () => { + const release = (): void => { held.holders -= 1 if (held.holders === 0) { - held.stop() + held.handle.stop() clients.delete(client) } } + return { handle: held.handle, release } } /** Keeps the host's event-signalled families (see HostQuery `signal`) fresh while a screen reads them. */ export function useHostEventRouter(hostId: string | undefined, client: RpcClient | null): void { const queryClient = useQueryClient() useEffect( - () => (client && hostId ? retainHostEventRouter(queryClient, hostId, client) : undefined), + () => + client && hostId ? retainHostEventRouter(queryClient, hostId, client).release : undefined, [queryClient, hostId, client] ) } + +/** + * Keeps the host's event router running, like useHostEventRouter, and says whether its event stream + * is live. Only while it is can a family hold its answer until an event marks it stale. + */ +export function useHostEventStreamReady( + hostId: string | undefined, + client: RpcClient | null +): boolean { + const queryClient = useQueryClient() + const subscribe = useCallback( + (onChange: () => void) => { + if (!client || !hostId) { + return () => {} + } + const { handle, release } = retainHostEventRouter(queryClient, hostId, client) + const stopListening = handle.onReadyChange(onChange) + return () => { + stopListening() + release() + } + }, + [queryClient, hostId, client] + ) + return useSyncExternalStore(subscribe, () => + client && hostId ? (routers.get(queryClient)?.get(client)?.handle.isReady() ?? false) : false + ) +} diff --git a/mobile/src/query/host-query.ts b/mobile/src/query/host-query.ts index 8eedacead2d..4d65785430e 100644 --- a/mobile/src/query/host-query.ts +++ b/mobile/src/query/host-query.ts @@ -34,7 +34,7 @@ export type HostQuery = { fetch?: HostQueryFetch staleTime?: StaleTimeFunction gcTime?: number - // Only for families the desktop sends no change signal for. + // Reads a stale answer on foreground: one with no change signal, or one an event marked while hidden. refetchOnWindowFocus?: boolean // For a screen that offers its own Retry, so a lost read is reported instead of sent again. retry?: false @@ -177,7 +177,13 @@ export function useHostQuery( host: { hostId: string; client: RpcClient | null }, target: HostQueryTarget, input: TInput, - options?: { enabled?: boolean; subscribed?: boolean; refetchInterval?: number | false } + options?: { + enabled?: boolean + subscribed?: boolean + refetchInterval?: number | false + // Replaces the family's own, e.g. once the host is known to signal every change. + staleTime?: number + } ): UseQueryResult { const { hostId, client } = host const enabled = client !== null && options?.enabled !== false @@ -194,6 +200,7 @@ export function useHostQuery( }, [query, client, hostId, keyHash, enabled]) return useQuery({ ...queryOptions, + ...(options?.staleTime === undefined ? {} : { staleTime: options.staleTime }), subscribed: options?.subscribed, refetchInterval: options?.refetchInterval }) diff --git a/mobile/src/query/settings-change-signal.ts b/mobile/src/query/settings-change-signal.ts new file mode 100644 index 00000000000..e99fc42c077 --- /dev/null +++ b/mobile/src/query/settings-change-signal.ts @@ -0,0 +1,35 @@ +import { SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' +import { useOptionalHostProtocolGates } from '../components/host-protocol-gates-context' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { useRouteRelaysCapability } from '../worktree/workspace-server-context' +import { useHostEventStreamReady } from './host-event-router' +import type { HostQuerySignal } from './host-query' + +/** + * Whether a settings family can hold its answer until a settingsChanged event marks it stale: the + * route's host publishes the event and this page's event stream from it is live. Otherwise (older + * hosts, a stream that ended, screens outside a host route) the family keeps its own rereads. + */ +export function useHostSettingsChangeSignal(hostId: string, client: RpcClient | null): boolean { + const hostCapabilities = useOptionalHostProtocolGates()?.hostCapabilities + const relayed = useRouteRelaysCapability(SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY) + const published = + hostCapabilities?.includes(SETTINGS_CHANGED_EVENT_RUNTIME_CAPABILITY) === true && relayed + const streamReady = useHostEventStreamReady( + published ? hostId : undefined, + published ? client : null + ) + return published && streamReady +} + +/** The signal of a family that reads only `keys` of the host's settings. */ +export function settingsSignal(keys: readonly string[]): HostQuerySignal { + return { + events: ['settingsChanged'], + // An event without a key list (malformed) could name anything. + matches: (event) => + event.type !== 'settingsChanged' || + !Array.isArray(event.keys) || + event.keys.some((key) => keys.includes(key)) + } +} diff --git a/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts b/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts index ae3c10c09cf..a4e86c7ec93 100644 --- a/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts +++ b/mobile/src/session/agent-launch/mobile-agent-launch-queries.ts @@ -9,6 +9,7 @@ import { type HostQueryTarget } from '../../query/host-query-key' import { hostReadClient } from '../../query/host-read-client' +import { useHostSettingsChangeSignal } from '../../query/settings-change-signal' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import { newTabSettingsRead } from './mobile-new-tab-settings-operations' import { @@ -75,16 +76,18 @@ export async function refreshDetectedAgents( const NO_INPUT = {} +// The launch reads the whole settings object, so any settingsChanged makes it stale. const newTabSettingsQuery = defineHostQuery({ family: 'settings.newTab', staleTime: 60_000, gcTime: 30 * 60_000, + signal: { events: ['settingsChanged'] }, fetch: async (client, _target, _input: typeof NO_INPUT) => ({ settings: newTabSettingsRead.interpret(await newTabSettingsRead.request(client))() }) }) -// Settings are read again on every sheet open; the cached ones paint meanwhile. +// A host without settingsChanged gets a reread on every sheet open; the cached ones paint meanwhile. export function reloadNewTabSettings( queryClient: QueryClient, hostId: string, @@ -101,6 +104,8 @@ type MobileAgentLaunchQueries = { settings: UseQueryResult<{ settings: unknown }> target: HostQueryTarget input: DetectionInput + // The host tells this page when settings change, so a sheet open need not read them again. + settingsSignalled: boolean } // One agent list per workspace and document, shared by the "+" sheet and the "Fix with" labels. @@ -130,11 +135,13 @@ export function useMobileAgentLaunchQueries(args: { enabled, subscribed: observed(detectedAgentsQuery.family, target, input) }) + const settingsSignalled = useHostSettingsChangeSignal(hostId, client) const settings = useHostQuery(newTabSettingsQuery, { hostId, client }, settingsTarget, NO_INPUT, { enabled, - subscribed: observed(newTabSettingsQuery.family, settingsTarget, NO_INPUT) + subscribed: observed(newTabSettingsQuery.family, settingsTarget, NO_INPUT), + staleTime: settingsSignalled ? Infinity : undefined }) - return { detection, settings, target, input } + return { detection, settings, target, input, settingsSignalled } } export function agentLaunchContextOf({ diff --git a/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts b/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts index 7a30d81b68b..639e76e1828 100644 --- a/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts +++ b/mobile/src/session/agent-launch/mobile-new-tab-agent-options.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - buildMobileNewTabAgentOptions, - orderMobileNewTabAgents -} from './mobile-new-tab-agent-options' +import { orderMobileNewTabAgents } from './mobile-new-tab-agent-options' describe('mobile new-tab agent options', () => { it('orders the enabled detected default first', () => { @@ -12,8 +9,4 @@ describe('mobile new-tab agent options', () => { 'claude' ]) }) - - it('does not show stale presets while detection is pending', () => { - expect(buildMobileNewTabAgentOptions({ defaultTuiAgent: 'codex' }, null)).toEqual([]) - }) }) diff --git a/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts b/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts index 24fb782b3ec..20636bce0fa 100644 --- a/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts +++ b/mobile/src/session/agent-launch/use-mobile-new-tab-agent-options.ts @@ -43,7 +43,7 @@ export function useMobileNewTabAgentOptions(args: { const { client, connState, hostId, open } = args const queryClient = useQueryClient() const connected = client !== null && connState === 'connected' - const { detection, settings, target, input } = useMobileAgentLaunchQueries({ + const { detection, settings, target, input, settingsSignalled } = useMobileAgentLaunchQueries({ hostId, client, worktreeId: args.worktreeId, @@ -58,7 +58,9 @@ export function useMobileNewTabAgentOptions(args: { if (!open || !client || connState !== 'connected') { return } - reloadNewTabSettings(queryClient, hostId, target.exec) + if (!settingsSignalled) { + reloadNewTabSettings(queryClient, hostId, target.exec) + } const queryKey = hostQueryKey(hostId, detectedAgentsQuery.family, target, input) const cached = queryClient.getQueryState(queryKey) const refreshed = refreshedThisConnection(client) @@ -92,7 +94,7 @@ export function useMobileNewTabAgentOptions(args: { refreshed.delete(targetKey) } }) - }, [client, connState, hostId, input, mountedAt, open, queryClient, target]) + }, [client, connState, hostId, input, mountedAt, open, queryClient, settingsSignalled, target]) const detected = detection.data const loadState: MobileNewTabAgentLoadState = !connected diff --git a/mobile/src/session/mobile-structured-queued-message-cards.test.ts b/mobile/src/session/mobile-structured-queued-message-cards.test.ts deleted file mode 100644 index 20c7058de34..00000000000 --- a/mobile/src/session/mobile-structured-queued-message-cards.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { agentSessionFailureFact } from '../../../src/shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../../src/shared/agent-session/failures/agent-session-failure-words' -import { - QUEUED_MESSAGE_PAUSED_SEND_FAILED, - type AgentSessionQueuedMessage -} from '../../../src/shared/agent-session/requests/agent-session-queued-message-wire' -import { queuedMessagesQueuePause } from '../../../src/shared/agent-session/view/structured-agent-session-queued-cards' -import type { AgentJournalSubmission } from '../../../src/shared/agent-session/journal/agent-session-journal-types' -import { mobileQueuedMessageCards } from './mobile-structured-queued-message-cards' - -function returnedAs(fact: Parameters[0]) { - const { reason, rejection } = agentSessionFailureWords(fact, { surface: 'rejection' }) - return { state: 'returned' as const, returnedReason: reason, returnedRejection: rejection } -} - -function draft(overrides: Partial & { messageId: string }) { - return { - position: 1, - body: { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: `body of ${overrides.messageId}` }] - }, - state: 'waiting' as const, - ...overrides - } -} - -describe('mobileQueuedMessageCards', () => { - it('finds waiting input for Resume past returned or failed cards', () => { - const resumable = (drafts: AgentSessionQueuedMessage[]) => - queuedMessagesQueuePause(mobileQueuedMessageCards(drafts, []), { reason: 'stopped' }) !== null - const returned = draft({ - messageId: 'r', - ...returnedAs(agentSessionFailureFact('hostRestarted')) - }) - const failed = draft({ - messageId: 'f', - paused: true, - pausedReason: QUEUED_MESSAGE_PAUSED_SEND_FAILED - }) - const waiting = draft({ messageId: 'w', position: 2 }) - expect(resumable([returned])).toBe(false) - expect(resumable([returned, waiting])).toBe(true) - expect(resumable([failed])).toBe(false) - expect(resumable([failed, waiting])).toBe(true) - expect(resumable([waiting, { ...returned, position: 3 }])).toBe(true) - }) - - it('hides a waiting card once its hand-off arrived, never a returned one', () => { - const cards = mobileQueuedMessageCards( - [ - draft({ messageId: 'returned', ...returnedAs(agentSessionFailureFact('hostRestarted')) }), - draft({ messageId: 'drained', position: 2 }), - draft({ messageId: 'waiting', position: 3 }) - ], - [handOff('returned', 'rejected'), handOff('drained', 'pending')] - ) - expect(cards.map((card) => card.messageId)).toEqual(['returned', 'waiting']) - }) - - it('shows a draft a Stop requeued beside its rejected hand-off', () => { - // Rejected hand-offs stay hidden in history; the requeued card is the only reachable copy of their text. - const cards = mobileQueuedMessageCards( - [ - draft({ messageId: 'requeued' }), - draft({ messageId: 'sending', position: 2 }), - draft({ messageId: 'sent', position: 3 }) - ], - [handOff('requeued', 'rejected'), handOff('sending', 'pending'), handOff('sent', 'accepted')] - ) - expect(cards.map((card) => card.messageId)).toEqual(['requeued']) - }) -}) - -function handOff( - queuedMessageId: string, - dispatchState: AgentJournalSubmission['dispatchState'] -): AgentJournalSubmission { - return { - clientMessageId: `${queuedMessageId}-handoff`, - queuedMessageId, - dispatchState, - fence: 1, - payloadFingerprint: 'fingerprint', - providerItemId: null, - reason: null, - submittedAt: 1, - resolvedAt: null - } -} diff --git a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts b/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts index f923bf96d8e..6e7ba0d0431 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts +++ b/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts @@ -80,20 +80,6 @@ describe('MobileNativeChatView: send and read failure banners', () => { expect(banners()).toHaveLength(1) }) - it('retires the previous route banner when a new send starts', async () => { - const onClearSendError = vi.fn() - await render({ - onSend: vi.fn().mockResolvedValue(false), - sendErrorMessage: 'Stop failed', - onClearSendError - }) - await pressSend() - - expect(onClearSendError).toHaveBeenCalledOnce() - expect(banners()).toHaveLength(1) - expect(bannerText()).toBe('Stop failed') - }) - it('retires the previous banner before sending and preserves the new delivery notice', async () => { const onClearSendError = vi.fn() await render({ diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts index 32b623f8481..e296b975b2c 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-image-attachment.test.ts @@ -85,34 +85,4 @@ describe('uploadMobileNativeChatImages', () => { 'uploaded:file:///c.jpg' ]) }) - - it('returns an empty array when the picker is cancelled and uploads nothing', async () => { - const client = clientWithResponses([]) - - const result = await uploadMobileNativeChatImages('library', { - client, - getConnectionId: async () => null, - pickImages: vi.fn().mockResolvedValue([]) - }) - - expect(result).toEqual([]) - expect(client.calls).toEqual([]) - }) - - it('falls back to an inline data uri for the preview when the picker omits a uri', async () => { - const client = clientWithResponses([methodNotFound('start'), ok('save', '/tmp/x.png')]) - - const result = await uploadMobileNativeChatImages('files', { - client, - getConnectionId: async () => null, - pickImages: vi.fn().mockResolvedValue([{ base64: 'BBBB' }]) - }) - - expect(result).toEqual([ - { - path: '/tmp/x.png', - previewUri: 'data:image/png;base64,BBBB' - } - ]) - }) }) diff --git a/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts b/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts index 48c20ffab96..05e017fb0e4 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-render-data.test.ts @@ -21,120 +21,7 @@ function user(id: string, text: string): NativeChatMessage { const fold = (messages: NativeChatMessage[]) => foldMobileNativeChatMessages(messages, 'claude') -function build( - messages: NativeChatMessage[], - streaming: string | null, - pending: Parameters[0]['pending'] -): NativeChatMessage[] { - return buildMobileNativeChatTransientData({ - folded: fold(messages), - streaming, - pending - }).data -} - describe('buildMobileNativeChatTransientData', () => { - it('places an idle send before the streaming reply it caused', () => { - const data = build([assistant('a1', 'Earlier answer')], 'Starting the tests', [ - { id: 'p1', text: 'Run the tests', sentAt: 100 } - ]) - expect(data.map((message) => message.id)).toEqual(['a1', 'p1', 'streaming']) - }) - - it('folds transcript image marker turns into image-ref blocks (desktop parity)', () => { - const data = build( - [ - user('u1', '[Image: source: /tmp/a.png]'), - user('u2', '[Image #1] look at this'), - assistant('a1', 'nice photo') - ], - null, - [] - ) - const merged = data.find((message) => message.role === 'user') - expect(merged?.blocks).toEqual([ - { type: 'image-ref', path: '/tmp/a.png' }, - { type: 'text', text: 'look at this' } - ]) - }) - - it('folds a trailing-marker image echo into one user bubble', () => { - const data = build( - [user('u1', '[Image: source: /tmp/a.png]'), user('u2', 'look at this[Image #1]')], - null, - [] - ) - - expect(data).toHaveLength(1) - expect(data[0]?.blocks).toEqual([ - { type: 'image-ref', path: '/tmp/a.png' }, - { type: 'text', text: 'look at this' } - ]) - }) - - it('leaves out an unrecognised provider event with no words, but keeps failures and sentences', () => { - const frameRow = ( - id: string, - kind: string, - text: string, - tone?: string - ): NativeChatMessage => ({ - id, - role: 'system', - timestamp: 0, - source: 'transcript', - blocks: [ - { - type: 'text', - text, - ...(tone ? { tone } : {}), - providerFrame: { - provider: 'codex', - kind, - payload: { head: '{}', byteLength: 2, digest: 'digest', truncated: false } - } - } - ] - }) - const folded = fold([ - frameRow('wordless', 'notification:future/event', 'codex · notification:future/event'), - frameRow( - 'failure', - 'notification:future/failure', - 'codex · notification:future/failure', - 'error' - ), - frameRow('sentence', 'notification:warning', 'Sandbox is degraded.'), - assistant('a1', 'done') - ]) - expect(folded.map((message) => message.id)).toEqual(['failure', 'sentence', 'a1']) - }) - - it('draws a turn’s subagents, each written as its own row, as one roster row', () => { - const own = (id: string): NativeChatMessage => ({ - id: `subagent:${id}`, - role: 'system', - blocks: [ - { type: 'text', text: `Kicked off subagent ${id}` }, - { type: 'subagent', id, label: id, state: 'working', groupId: 'turn-1' } - ], - timestamp: 0, - source: 'transcript' - }) - const folded = fold([user('u1', 'audit'), own('a'), assistant('a1', 'started'), own('b')]) - expect(folded.map((message) => message.id)).toEqual(['u1', 'subagent:a', 'a1']) - expect(folded[1]?.blocks).toEqual([ - { - type: 'subagent-group', - groupId: 'turn-1', - agents: [ - { id: 'a', label: 'a', state: 'working' }, - { id: 'b', label: 'b', state: 'working' } - ] - } - ]) - }) - it('keeps the phone-local image visible when the transcript replaces its optimistic echo', () => { const folded = fold([ user('source', '[Image: source: /tmp/a.png]'), @@ -164,14 +51,6 @@ describe('buildMobileNativeChatTransientData', () => { expect(result.data[0]?.blocks).toEqual([{ type: 'image-ref', url: 'file:///phone-photo.jpg' }]) }) - - it('keeps a queued follow-up after the current streaming reply', () => { - const data = build([user('u1', 'hi')], 'thinking out loud', [ - { id: 'p1', text: 'queued', pendingSend: 'queued' } - ]) - expect(data.map((message) => message.id)).toEqual(['u1', 'streaming', 'p1']) - expect(data[1].blocks).toEqual([{ type: 'text', text: 'thinking out loud' }]) - }) }) describe('foldMobileNativeChatMessages', () => { @@ -195,16 +74,6 @@ describe('foldMobileNativeChatMessages', () => { } } - // Read windows may begin after tool_use; leading orphan results must not become raw-output bubbles. - it('drops a leading tool result whose call is older than the read window', () => { - const folded = fold([ - toolResult('orphan', 'Exit code 1\norca-ide not found'), - assistant('a1', 'Falling back to the installed binary.') - ]) - - expect(folded.map((message) => message.id)).toEqual(['a1']) - }) - function planFrame(head: string): NativeChatMessage { return { id: 'plan', @@ -240,60 +109,6 @@ describe('foldMobileNativeChatMessages', () => { blocks: [{ type: 'tool-call', name: 'update_plan', state: 'completed' }] }) }) - - it('still folds a result whose call is inside the window', () => { - const folded = fold([ - assistant('a1', 'Checking which binary is on PATH.'), - toolCall('c1'), - toolResult('r1', 'orca-ide not found') - ]) - - expect(folded).toHaveLength(1) - expect(folded[0]?.blocks.map((block) => block.type)).toEqual([ - 'text', - 'tool-call', - 'tool-result' - ]) - }) - - it('keeps a mixed Claude tool result with a harness sidecar paired', () => { - const folded = fold([ - toolCall('c1'), - { - id: 'mixed', - role: 'user', - blocks: [ - { type: 'tool-result', output: 'important output' }, - { type: 'text', text: 'continue' } - ], - timestamp: 0, - source: 'transcript' - } - ]) - - expect(folded[0]?.blocks).toEqual([ - { type: 'tool-call', name: 'Bash', input: { command: 'command -v orca-ide' } }, - { type: 'tool-result', output: 'important output' } - ]) - }) - - it('draws a skill command the user ran as their message, as desktop does', () => { - const folded = fold([ - { - ...user( - 'd7306d00', - 'hello\n/hello\nKelvin' - ), - parentId: 'f615a2bf' - }, - { ...assistant('0d3481c0', 'Hello, Kelvin!'), parentId: 'fa9d5ee6' } - ]) - - expect(folded.map((message) => [message.role, message.blocks])).toEqual([ - ['user', [{ type: 'text', text: '/hello Kelvin' }]], - ['assistant', [{ type: 'text', text: 'Hello, Kelvin!' }]] - ]) - }) }) // Claude may consume queued commands without a user record; unmatched echoes must stay at their send position rather than trail every later turn. diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts index ef5a04f9c39..31f565395c6 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts @@ -164,7 +164,7 @@ describe('MobileNativeChatMessage status notices', () => { ]) }) - it.each(['without reset', 'with reset', 'from an old host'] as const)( + it.each(['with reset', 'from an old host'] as const)( 'draws an OpenCode usage warning %s', (source) => { const hasReset = source === 'with reset' @@ -221,12 +221,9 @@ describe('MobileNativeChatMessage status notices', () => { ) it.each([ - ['Claude', 'system', 'claude auth login'], ['Claude', 'managed', 'claude auth login'], ['Codex', 'system', 'codex login --device-auth'], - ['Codex', 'managed', null], - ['Grok', undefined, 'grok login --device-auth'], - ['Antigravity', undefined, null] + ['Codex', 'managed', null] ] as const)( 'offers %s (%s account) sign-in in a host terminal', (agentName, account, command) => { @@ -263,14 +260,6 @@ describe('MobileNativeChatMessage status notices', () => { 'Codex reported a safety review warning. View details.', 'Codex a signalé un avertissement de sécurité. Voir les détails.', colors.statusAmber - ], - [ - 'claude', - 'message:system:permission_denied', - 'error', - 'Claude denied permission. View details.', - 'Claude a refusé la permission. Voir les détails.', - colors.statusRed ] ] as const)( 'discloses the entire available %s notice without tool-output clipping or recovery', diff --git a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts b/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts index c57802607e6..b43cccdae12 100644 --- a/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts +++ b/mobile/src/session/native-chat/visual/mobile-native-chat-image-preview.test.ts @@ -3,21 +3,6 @@ import { describe, expect, it } from 'vitest' import { isRenderableImageUri } from './mobile-native-chat-image-preview' describe('isRenderableImageUri', () => { - it('accepts local previews and real URLs the device can load', () => { - for (const uri of [ - 'file:///var/mobile/a.jpg', - 'FILE:///var/mobile/a.jpg', - 'HTTPS://host/a.png', - 'data:image/png;base64,AAAA', - 'content://media/1', - 'blob:abc', - 'http://host/a.png', - 'https://host/a.png' - ]) { - expect(isRenderableImageUri(uri)).toBe(true) - } - }) - it('rejects bare host paths (not loadable on the device) and empty values', () => { for (const uri of [ '/tmp/orca-attach.png', diff --git a/mobile/src/session/tabs/active-session-tab.test.ts b/mobile/src/session/tabs/active-session-tab.test.ts index e1749467b33..a76e257be33 100644 --- a/mobile/src/session/tabs/active-session-tab.test.ts +++ b/mobile/src/session/tabs/active-session-tab.test.ts @@ -108,38 +108,4 @@ describe('resolveActiveSessionTab', () => { expect(result.activeTab?.id).toBe('agent') expect(result.clearPendingActiveSessionTabId).toBe(true) }) - - it('uses the snapshot when the device has no pick yet', () => { - const result = resolveActiveSessionTab( - [terminalTab('agent', false), browserTab('browser', true)], - { - pendingActiveSessionTabId: null, - selectedSessionTabId: null - } - ) - - expect(result.activeTab?.id).toBe('browser') - expect(result.selectionSource).toBe('snapshot') - }) - - it('opens the chat a create-worktree launch landed on, over the workspace shell', () => { - // A just-created route has no local pick; the host’s launch activation must open its chat. - const result = resolveActiveSessionTab( - [ - { id: 'shell', type: 'terminal', isActive: false }, - { id: 'agent-session:s-1', type: 'agent-session', isActive: true } - ], - { pendingActiveSessionTabId: null, selectedSessionTabId: null } - ) - - expect(result.activeTab?.id).toBe('agent-session:s-1') - expect(result.selectionSource).toBe('snapshot') - }) - - it('returns null for an empty snapshot', () => { - expect( - resolveActiveSessionTab([], { pendingActiveSessionTabId: null, selectedSessionTabId: 'x' }) - .activeTab - ).toBeNull() - }) }) diff --git a/mobile/src/session/tabs/mobile-tab-close-selection.test.ts b/mobile/src/session/tabs/mobile-tab-close-selection.test.ts index c90c1c79f48..bfd912b16a8 100644 --- a/mobile/src/session/tabs/mobile-tab-close-selection.test.ts +++ b/mobile/src/session/tabs/mobile-tab-close-selection.test.ts @@ -8,16 +8,6 @@ const tab = (id: string, isDirty?: boolean, isPinned?: boolean) => ({ }) describe('selectBulkCloseTabs', () => { - const tabs = [tab('a'), tab('b'), tab('c'), tab('d')] - - it('selects every tab except the anchor', () => { - expect(selectBulkCloseTabs(tabs, 'b').map((t) => t.id)).toEqual(['a', 'c', 'd']) - }) - - it('returns empty when the anchor is not in the list', () => { - expect(selectBulkCloseTabs(tabs, 'missing')).toEqual([]) - }) - it('skips dirty tabs so unsaved edits survive a bulk close', () => { const withDirty = [tab('a', true), tab('b'), tab('c', false), tab('d')] expect(selectBulkCloseTabs(withDirty, 'b').map((t) => t.id)).toEqual(['c', 'd']) diff --git a/mobile/src/session/tabs/pending-session-selection.test.ts b/mobile/src/session/tabs/pending-session-selection.test.ts index c54321e4963..f35fb3edf4c 100644 --- a/mobile/src/session/tabs/pending-session-selection.test.ts +++ b/mobile/src/session/tabs/pending-session-selection.test.ts @@ -3,11 +3,8 @@ import type { MobileSessionTab } from './mobile-session-tabs' import { isLaunchedSurfaceListed, launchedSelection, - pendingSelectionWantsHandle, resolveLaunchedSelection, withLaunchReply, - withoutPendingHandle, - withoutPendingTabId, withoutUnansweredLaunch, type PendingSessionSelection } from './pending-session-selection' @@ -115,39 +112,8 @@ describe("a launch's own reply and end", () => { }) }) -describe('the halves of a pick', () => { - const both: PendingSessionSelection = { kind: 'terminal', handle: 'term_1', tabId: 'tab-1' } - - it('drops one half and keeps the other', () => { - expect(withoutPendingTabId(both)).toEqual({ kind: 'terminal', handle: 'term_1', tabId: null }) - expect(withoutPendingHandle(both)).toEqual({ kind: 'tab', tabId: 'tab-1' }) - expect(withoutPendingHandle({ kind: 'terminal', handle: 'term_1', tabId: null })).toBeNull() - expect(withoutPendingTabId({ kind: 'tab', tabId: 'tab-1' })).toBeNull() - }) - - it('lets a just-launched terminal subscribe before its tab arrives', () => { - expect( - pendingSelectionWantsHandle(launchedSelection('l1', { handle: 'term_1' }), 'term_1') - ).toBe(true) - expect(pendingSelectionWantsHandle(launchedSelection('l1', { sessionId: 's' }), 'term_1')).toBe( - false - ) - }) -}) - describe('isLaunchedSurfaceListed', () => { - it('reads a listed terminal as a started agent', () => { - expect(isLaunchedSurfaceListed([reservedTerminalTab('term_1')], { pane: PANE })).toBe(true) - }) - it('does not read a tab the host showed before its agent existed as a start', () => { expect(isLaunchedSurfaceListed([reservedTerminalTab(null)], { pane: PANE })).toBe(false) }) - - it('still lands the selection on that tab, so the phone shows it at once', () => { - const resolved = resolveLaunchedSelection(launchedSelection('lock', { pane: PANE }, null), [ - reservedTerminalTab(null) - ]) - expect(resolved.landedTabId).toBe(`${PANE.tabId}::${PANE.leafId}`) - }) }) diff --git a/mobile/src/session/tabs/session-tab-snapshot-gate.test.ts b/mobile/src/session/tabs/session-tab-snapshot-gate.test.ts index 5d514f24480..157972bf843 100644 --- a/mobile/src/session/tabs/session-tab-snapshot-gate.test.ts +++ b/mobile/src/session/tabs/session-tab-snapshot-gate.test.ts @@ -2,19 +2,10 @@ import { describe, expect, it } from 'vitest' import { acceptSessionSnapshot, applyClosedTabTombstones, - confirmsMirroredTabSelection, type AppliedSnapshotMarker } from './session-tab-snapshot-gate' describe('acceptSessionSnapshot', () => { - it('accepts a newer version from the same publisher and advances the floor', () => { - const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 5 } - expect( - acceptSessionSnapshot({ publicationEpoch: 'renderer:a', snapshotVersion: 6 }, marker) - ).toBe(true) - expect(marker).toEqual({ epoch: 'renderer:a', version: 6 }) - }) - it('rejects a strictly older version from the same publisher without moving the floor', () => { const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 42 } expect( @@ -23,15 +14,6 @@ describe('acceptSessionSnapshot', () => { expect(marker).toEqual({ epoch: 'renderer:a', version: 42 }) }) - it('accepts an equal version (reprocess) so close tombstones can expire and clear', () => { - const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 42 } - // Equal cached versions still need reprocessing so close tombstones can expire. - expect( - acceptSessionSnapshot({ publicationEpoch: 'renderer:a', snapshotVersion: 42 }, marker) - ).toBe(true) - expect(marker).toEqual({ epoch: 'renderer:a', version: 42 }) - }) - it('accepts any version from a new publisher (epoch change) and resets the floor', () => { const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 99 } expect( @@ -39,35 +21,11 @@ describe('acceptSessionSnapshot', () => { ).toBe(true) expect(marker).toEqual({ epoch: 'headless:b', version: 1 }) }) - - it('treats a missing epoch as its own publisher key', () => { - const marker: AppliedSnapshotMarker = { epoch: null, version: -1 } - expect(acceptSessionSnapshot({ snapshotVersion: 5 }, marker)).toBe(true) - expect(acceptSessionSnapshot({ snapshotVersion: 4 }, marker)).toBe(false) - expect(marker).toEqual({ epoch: null, version: 5 }) - }) -}) - -describe('confirmsMirroredTabSelection', () => { - it('does not treat phone-local persistence as desktop focus confirmation', () => { - expect(confirmsMirroredTabSelection('mobile-local:abc')).toBe(false) - }) - - it('accepts renderer, headless, and legacy publications as confirmation', () => { - expect(confirmsMirroredTabSelection('renderer:abc')).toBe(true) - expect(confirmsMirroredTabSelection('headless:abc')).toBe(true) - expect(confirmsMirroredTabSelection()).toBe(true) - }) }) describe('applyClosedTabTombstones', () => { const tab = (id: string): { id: string } => ({ id }) - it('returns the tabs untouched when there are no tombstones', () => { - const tabs = [tab('a'), tab('b')] - expect(applyClosedTabTombstones(tabs, new Map(), 1000)).toBe(tabs) - }) - it('suppresses a tombstoned tab while it is still present and not expired', () => { const tombstones = new Map([['a', 5000]]) const result = applyClosedTabTombstones([tab('a'), tab('b')], tombstones, 1000) diff --git a/mobile/src/session/tabs/tab-strip-scroll.test.ts b/mobile/src/session/tabs/tab-strip-scroll.test.ts deleted file mode 100644 index e93ca8bbfb2..00000000000 --- a/mobile/src/session/tabs/tab-strip-scroll.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveTabStripEdgeHint, - resolveTabStripHiddenTabs, - resolveTabStripScrollOffset, - resolveTabStripTapOffset -} from './tab-strip-scroll' - -describe('resolveTabStripScrollOffset', () => { - it('keeps the offset when the active tab is already fully visible', () => { - expect( - resolveTabStripScrollOffset({ - tabX: 140, - tabWidth: 128, - viewportWidth: 360, - contentWidth: 800, - currentOffset: 100 - }) - ).toBe(100) - }) - - it('scrolls left to reveal a tab off the left edge', () => { - expect( - resolveTabStripScrollOffset({ - tabX: 50, - tabWidth: 128, - viewportWidth: 360, - contentWidth: 800, - currentOffset: 200, - margin: 12 - }) - ).toBe(38) - }) - - it('scrolls right to reveal a tab off the right edge', () => { - expect( - resolveTabStripScrollOffset({ - tabX: 640, - tabWidth: 128, - viewportWidth: 360, - contentWidth: 900, - currentOffset: 0, - margin: 12 - }) - ).toBe(420) - }) - - it('clamps the offset to the content bounds', () => { - expect( - resolveTabStripScrollOffset({ - tabX: 880, - tabWidth: 128, - viewportWidth: 360, - contentWidth: 900, - currentOffset: 0 - }) - ).toBe(540) - }) - - it('returns the current offset when the viewport has not been measured', () => { - expect( - resolveTabStripScrollOffset({ - tabX: 100, - tabWidth: 128, - viewportWidth: 0, - contentWidth: 0, - currentOffset: 150 - }) - ).toBe(150) - }) -}) - -const tabs = Array.from({ length: 10 }, (_, i) => ({ id: String(i) })) -const layouts = new Map(tabs.map((tab, i) => [tab.id, { x: i * 100, width: 100 }])) - -describe('resolveTabStripTapOffset', () => { - const tap = (tabId: string, currentOffset: number, viewportWidth = 300) => - resolveTabStripTapOffset({ - tabId, - tabs, - layouts, - viewportWidth, - contentWidth: 1000, - currentOffset - }) - - it('leaves the strip alone when the tapped tab is comfortably visible', () => { - expect(tap('1', 70)).toBe(70) - }) - - it('waits for layout instead of jumping', () => { - expect(tap('missing', 150)).toBe(150) - expect(tap('3', 150, 0)).toBe(150) - }) -}) - -describe('tab strip edge hints', () => { - it('marks each edge with the most urgent hidden tab, ignoring visible and finished ones', () => { - const hidden = resolveTabStripHiddenTabs({ layouts, viewportWidth: 300, currentOffset: 300 }) - const tabStates = new Map([ - ['0', 'working'], - ['1', 'done'], - ['4', 'blocked'], - ['8', 'working'], - ['9', 'waiting'] - ] as const) - expect(resolveTabStripEdgeHint(hidden.left, tabStates)).toBe('working') - expect(resolveTabStripEdgeHint(hidden.right, tabStates)).toBe('waiting') - expect(resolveTabStripEdgeHint(['1'], tabStates)).toBeNull() - }) -}) diff --git a/mobile/src/source-control/MobileSourceControlFileRows.tsx b/mobile/src/source-control/MobileSourceControlFileRows.tsx index 869ce8c328d..71e04ff4603 100644 --- a/mobile/src/source-control/MobileSourceControlFileRows.tsx +++ b/mobile/src/source-control/MobileSourceControlFileRows.tsx @@ -1,15 +1,6 @@ import type { ReactNode } from 'react' import { ActivityIndicator, Pressable, Text, View } from 'react-native' -import { Gesture, GestureDetector } from 'react-native-gesture-handler' -import Animated, { - Easing, - ReduceMotion, - useAnimatedStyle, - useSharedValue, - withTiming -} from 'react-native-reanimated' -import { SHEET_CURVE } from '../components/sheet-motion-values' -import { useDrawerReducedMotion } from '../components/bottom-drawer/bottom-drawer-constants' +import { SwipeRowActions } from '../components/SwipeRowActions' import { Minus, Plus, Undo2 } from 'lucide-react-native' import { colors } from '../theme/mobile-theme' import { STATUS_LABELS } from '../../../src/shared/git/status/git-status-labels' @@ -114,101 +105,6 @@ function FileRowBody({ ) } -// The width the Discard action uncovers; a swipe past half of it settles open. -const DISCARD_WIDTH = 84 -const SWIPE_SETTLE_MS = 250 -const DRAG_CLICK_WINDOW_MS = 400 - -/** Discard sits behind a left swipe and still asks first; it is also on the diff screen. */ -function SwipeToDiscard({ - available, - enabled, - label, - accessibilityLabel, - onDiscard, - children -}: { - /** Only discardable rows get the swipe; toggling it would remount the row. */ - available: boolean - enabled: boolean - label: string - accessibilityLabel: string - onDiscard: () => void - /** Gets a wrapper for the row's press: a tap on a swiped row closes it instead. */ - children: (guardPress: (onPress: () => void) => () => void) => ReactNode -}) { - useMobileColorScheme() - const reducedMotion = useDrawerReducedMotion() - const offset = useSharedValue(0) - const start = useSharedValue(0) - // When the last drag ended: on the web, releasing a mouse drag also clicks the row. - const dragEndedAt = useSharedValue(0) - // Built per render: a module-level easing would run before a test's Reanimated mock can serve it. - const settle = (to: number) => { - 'worklet' - return withTiming( - to, - reducedMotion - ? { duration: 0, reduceMotion: ReduceMotion.Never } - : { duration: SWIPE_SETTLE_MS, easing: Easing.bezier(...SHEET_CURVE) } - ) - } - // Horizontal only, so the list keeps scrolling under a vertical drag. - const pan = Gesture.Pan() - .enabled(enabled) - .activeOffsetX([-12, 12]) - .failOffsetY([-10, 10]) - .onBegin(() => { - start.value = offset.value - }) - .onUpdate((event) => { - offset.value = Math.min(0, Math.max(-DISCARD_WIDTH, start.value + event.translationX)) - }) - .onEnd(() => { - // oxlint-disable-next-line react/purity -- runs when the drag ends, never during render. - dragEndedAt.value = Date.now() - offset.value = settle(offset.value < -DISCARD_WIDTH / 2 ? -DISCARD_WIDTH : 0) - }) - // Web has no worklet plugin; mapper hooks need this explicit dependency list. - const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: offset.value }] }), [offset]) - // A tap on an open row closes it rather than opening the diff. - const guardPress = (onPress: () => void) => () => { - // The click a drag release produces belongs to the drag, not to the row. - if (Date.now() - dragEndedAt.value < DRAG_CLICK_WINDOW_MS) { - return - } - if (offset.value !== 0) { - offset.value = settle(0) - return - } - onPress() - } - if (!available) { - return children((onPress) => onPress) - } - return ( - - [styles.discardAction, pressed && styles.iconButtonPressed]} - disabled={!enabled} - onPress={() => { - offset.value = settle(0) - onDiscard() - }} - accessibilityRole="button" - accessibilityLabel={accessibilityLabel} - > - - {label} - - {/* pan-y keeps the page scrolling vertically over the row on the web. */} - - {children(guardPress)} - - - ) -} - export function ChangeFileRow({ item, state @@ -294,14 +190,23 @@ export function ChangeFileRow({ ) : null return ( - setDiscardTarget(item)} + trailing={ + item.canDiscard + ? { + label: t('sourceControl.fileRows.discard', 'Discard'), + accessibilityLabel: t('sourceControl.fileRows.discardFile', 'Discard {{path}}', { + path: item.path + }), + icon: Undo2, + background: colors.statusRed, + foreground: colors.onStatusRed, + onPress: () => setDiscardTarget(item) + } + : undefined + } > {(guardPress) => ( )} - + ) } diff --git a/mobile/src/source-control/mobile-pr-create-flow.test.ts b/mobile/src/source-control/mobile-pr-create-flow.test.ts index b0900906763..b9074db4d7d 100644 --- a/mobile/src/source-control/mobile-pr-create-flow.test.ts +++ b/mobile/src/source-control/mobile-pr-create-flow.test.ts @@ -46,46 +46,4 @@ describe('createMobilePr', () => { linkError: 'metadata failed' }) }) - - it('maps a host failure result to { ok:false }', async () => { - const client = clientWith([ok({ ok: false, code: 'validation', error: 'Push first' })]) - await expect( - createMobilePr(client, 'repo-1::/tmp/wt', { - provider: 'github', - base: 'main', - title: 'T', - body: '', - draft: false - }) - ).resolves.toEqual({ ok: false, error: 'Push first' }) - }) - - it('maps an RPC transport failure to { ok:false }', async () => { - const client = clientWith([fail('disconnected')]) - const result = await createMobilePr(client, 'repo-1::/tmp/wt', { - provider: 'github', - base: 'main', - title: 'T', - body: '', - draft: false - }) - expect(result).toEqual({ ok: false, error: 'disconnected' }) - }) - - it('normalizes a thrown sendRequest into { ok:false }', async () => { - const client = { - sendRequest: vi.fn(async () => { - throw new Error('socket hung up') - }) - } as unknown as Pick - await expect( - createMobilePr(client, 'repo-1::/tmp/wt', { - provider: 'github', - base: 'main', - title: 'T', - body: '', - draft: false - }) - ).resolves.toEqual({ ok: false, error: 'socket hung up' }) - }) }) diff --git a/mobile/src/source-control/mobile-review-route.test.ts b/mobile/src/source-control/mobile-review-route.test.ts deleted file mode 100644 index 30f392df29f..00000000000 --- a/mobile/src/source-control/mobile-review-route.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { buildMobileReviewFileRoute } from './mobile-review-route' - -function queryParams(route: string): URLSearchParams { - const query = route.split('?')[1] ?? '' - return new URLSearchParams(query) -} - -describe('buildMobileReviewFileRoute', () => { - it('carries the commit for a file opened from a commit', () => { - const params = queryParams( - buildMobileReviewFileRoute({ - hostId: 'host', - worktreeId: 'wt', - worktreeName: '', - filePath: 'a.ts', - area: 'commit', - commitOid: 'c0ffee0123456789abcdef0123456789abcdef01' - }) - ) - - expect(params.get('area')).toBe('commit') - expect(params.get('commit')).toBe('c0ffee0123456789abcdef0123456789abcdef01') - }) -}) diff --git a/mobile/src/source-control/mobile-source-control-list-styles.ts b/mobile/src/source-control/mobile-source-control-list-styles.ts index 6b43b3a73e7..2ee25cc000c 100644 --- a/mobile/src/source-control/mobile-source-control-list-styles.ts +++ b/mobile/src/source-control/mobile-source-control-list-styles.ts @@ -93,23 +93,6 @@ export const listStyles = themedStyleSheet(() => ({ alignItems: 'center', justifyContent: 'center' }, - // Behind the row's right end; the row slides left to uncover it. - discardAction: { - position: 'absolute', - top: 0, - right: 0, - bottom: 0, - width: 84, - alignItems: 'center', - justifyContent: 'center', - gap: 2, - backgroundColor: colors.statusRed - }, - discardActionText: { - color: colors.onStatusRed, - fontSize: typography.metaSize, - fontWeight: '600' - }, conflictActions: { flexDirection: 'row', flexWrap: 'wrap', diff --git a/mobile/src/source-control/mobile-source-control-settings-operations.ts b/mobile/src/source-control/mobile-source-control-settings-operations.ts index 1a4f2afa3ce..7bd2839f597 100644 --- a/mobile/src/source-control/mobile-source-control-settings-operations.ts +++ b/mobile/src/source-control/mobile-source-control-settings-operations.ts @@ -10,6 +10,14 @@ export type MobileSourceControlSettings = { diffShowWhitespace: boolean } +const SOURCE_CONTROL_SETTING = { + groupOrder: 'sourceControlGroupOrder', + compareAgainstUpstream: 'sourceControlCompareAgainstUpstream', + diffShowWhitespace: 'diffShowWhitespace' +} as const + +export const SOURCE_CONTROL_SETTINGS_KEYS: readonly string[] = Object.values(SOURCE_CONTROL_SETTING) + // Older hosts omit these settings; absence reads as desktop's defaults. const sourceControlSettingsReader: RpcCompatibleReader< unknown, @@ -22,9 +30,9 @@ const sourceControlSettingsReader: RpcCompatibleReader< compatible: true, variant: 'source-control-settings', value: { - groupOrder: normalizeSourceControlGroupOrder(field('sourceControlGroupOrder')), - compareAgainstUpstream: field('sourceControlCompareAgainstUpstream') === true, - diffShowWhitespace: field('diffShowWhitespace') === true + groupOrder: normalizeSourceControlGroupOrder(field(SOURCE_CONTROL_SETTING.groupOrder)), + compareAgainstUpstream: field(SOURCE_CONTROL_SETTING.compareAgainstUpstream) === true, + diffShowWhitespace: field(SOURCE_CONTROL_SETTING.diffShowWhitespace) === true }, salvage: { droppedPaths: [], droppedCount: 0 } } diff --git a/mobile/src/source-control/mobile-source-control-settings.ts b/mobile/src/source-control/mobile-source-control-settings.ts index b0bc9b6b326..4355ad1f9eb 100644 --- a/mobile/src/source-control/mobile-source-control-settings.ts +++ b/mobile/src/source-control/mobile-source-control-settings.ts @@ -4,7 +4,9 @@ import { DEFAULT_SOURCE_CONTROL_GROUP_ORDER } from '../../../src/shared/source-c import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' import { defineHostQuery, useHostQuery } from '../query/host-query' import { hostQueryKey } from '../query/host-query-key' +import { settingsSignal, useHostSettingsChangeSignal } from '../query/settings-change-signal' import { + SOURCE_CONTROL_SETTINGS_KEYS, sourceControlSettingsRead, type MobileSourceControlSettings } from './mobile-source-control-settings-operations' @@ -19,12 +21,13 @@ const DESKTOP_DEFAULTS: MobileSourceControlSettings = { const NO_INPUT = {} -// The desktop sends no settings change signal, so every mount and foreground rereads behind the cached copy. +// A host without settingsChanged gets a reread on every mount and foreground, behind the cached copy. const sourceControlSettingsQuery = defineHostQuery({ family: 'settings.sourceControl', staleTime: 0, refetchOnWindowFocus: true, gcTime: 30 * 60_000, + signal: settingsSignal(SOURCE_CONTROL_SETTINGS_KEYS), fetch: async ( client, _target, @@ -46,12 +49,13 @@ export function useMobileSourceControlSettings( ): { settings: MobileSourceControlSettings; reload: () => void } { const queryClient = useQueryClient() const exec = useWorkspaceExecutionHost() ?? 'local' + const signalled = useHostSettingsChangeSignal(hostId, client) const { data } = useHostQuery( sourceControlSettingsQuery, { hostId, client }, { exec }, NO_INPUT, - { enabled: connState === 'connected' } + { enabled: connState === 'connected', staleTime: signalled ? Infinity : undefined } ) const reload = useCallback(() => { void queryClient.invalidateQueries({ diff --git a/mobile/src/source-control/review/mobile-diff-comment-edit.test.ts b/mobile/src/source-control/review/mobile-diff-comment-edit.test.ts deleted file mode 100644 index f0670e5c34d..00000000000 --- a/mobile/src/source-control/review/mobile-diff-comment-edit.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { DiffComment } from '../../../../src/shared/diff-comment-types' -import { - clearSentMobileDiffComments, - countUnsentMobileDiffComments, - getUnsentMobileDiffComments, - markMobileDiffCommentsSent -} from './mobile-diff-comment-edit' - -function comment(overrides: Partial & Pick): DiffComment { - const { id, ...rest } = overrides - return { - id, - worktreeId: 'wt-1', - filePath: 'src/app.ts', - source: 'diff', - lineNumber: 4, - body: 'check this', - createdAt: 100, - side: 'modified', - ...rest - } -} - -describe('mobile diff comment editing', () => { - it('marks notes sent and excludes them from unsent counts', () => { - const comments = markMobileDiffCommentsSent( - [comment({ id: 'a' }), comment({ id: 'b' })], - new Set(['a']), - 250 - ) - - expect(comments[0]?.sentAt).toBe(250) - expect(countUnsentMobileDiffComments(comments)).toBe(1) - expect(getUnsentMobileDiffComments(comments)).toEqual([comment({ id: 'b' })]) - }) - - it('clears sent notes without removing unsent edits', () => { - expect( - clearSentMobileDiffComments([comment({ id: 'a', sentAt: 1 }), comment({ id: 'b' })]) - ).toEqual([comment({ id: 'b' })]) - }) -}) diff --git a/mobile/src/source-control/review/mobile-diff-review-positioning.test.ts b/mobile/src/source-control/review/mobile-diff-review-positioning.test.ts deleted file mode 100644 index fd23dfd4ece..00000000000 --- a/mobile/src/source-control/review/mobile-diff-review-positioning.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - createMobileDiffReviewFileKey, - filterMobileDiffReviewQueue, - type MobileDiffReviewQueueItem -} from './mobile-diff-review-queue' -import { findMobileDiffReviewInitialIndex } from './mobile-diff-review-positioning' - -function item( - filePath: string, - area: MobileDiffReviewQueueItem['area'], - oldPath?: string -): MobileDiffReviewQueueItem { - const scope = area === 'staged' || area === 'branch' ? area : 'unstaged' - return { - key: createMobileDiffReviewFileKey(scope, area, filePath, oldPath), - scope, - area, - filePath, - oldPath, - status: oldPath ? 'renamed' : area === 'untracked' ? 'untracked' : 'modified', - title: filePath, - subtitle: scope, - canStage: area === 'unstaged' || area === 'untracked', - canUnstage: area === 'staged', - canDiscard: area !== 'staged' && area !== 'branch', - isGeneratedOrLockFile: false, - diffIdentity: `diff:${filePath}`, - noteCount: 0, - unsentNoteCount: 0, - staleNoteCount: 0, - isReviewed: false, - changedSinceReview: false - } -} - -describe('mobile diff review positioning', () => { - it('selects an untracked file without changing the all-files filter', () => { - const queue = [ - item('a.ts', 'unstaged'), - item('new file.ts', 'untracked'), - item('b.ts', 'staged') - ] - const filtered = filterMobileDiffReviewQueue(queue, 'all') - - expect( - findMobileDiffReviewInitialIndex(filtered, { - filePath: 'new file.ts', - area: 'untracked' - }) - ).toBe(1) - expect(filtered).toHaveLength(3) - }) - - it('matches renamed files by oldPath through the queue key', () => { - const queue = [item('other.ts', 'branch'), item('new.ts', 'branch', 'old.ts')] - - expect( - findMobileDiffReviewInitialIndex(queue, { - filePath: 'old.ts', - area: 'branch' - }) - ).toBe(1) - }) - - it('falls back to the first file when the target is missing', () => { - const queue = [item('a.ts', 'unstaged'), item('b.ts', 'staged')] - - expect( - findMobileDiffReviewInitialIndex(queue, { - filePath: 'missing.ts', - area: 'unstaged' - }) - ).toBe(0) - }) -}) diff --git a/mobile/src/source-control/review/mobile-diff-review-state.test.ts b/mobile/src/source-control/review/mobile-diff-review-state.test.ts index de379b21d7f..e5a4fbdd4a3 100644 --- a/mobile/src/source-control/review/mobile-diff-review-state.test.ts +++ b/mobile/src/source-control/review/mobile-diff-review-state.test.ts @@ -1,9 +1,7 @@ import { describe, expect, it } from 'vitest' import { - clearMobileDiffReviewFileReviewed, completeMobileDiffReviewState, createMobileDiffReviewState, - isMobileDiffReviewFileReviewed, markMobileDiffReviewFileReviewed, mergeMobileDiffReviewState } from './mobile-diff-review-state' @@ -16,13 +14,6 @@ const descriptor = { } as const describe('mobile diff review state', () => { - it('marks files reviewed against the current diff identity', () => { - const state = markMobileDiffReviewFileReviewed(createMobileDiffReviewState(1), descriptor, 5) - - expect(isMobileDiffReviewFileReviewed(state.files[descriptor.key], 'd1')).toBe(true) - expect(isMobileDiffReviewFileReviewed(state.files[descriptor.key], 'd2')).toBe(false) - }) - it('invalidates reviewed state when refreshed identity changes', () => { const reviewed = markMobileDiffReviewFileReviewed(createMobileDiffReviewState(1), descriptor, 5) @@ -50,14 +41,4 @@ describe('mobile diff review state', () => { expect(merged.completedAt).toBe(6) expect(merged.files[descriptor.key]?.reviewedAt).toBe(5) }) - - it('clears reviewed state for manual unreview', () => { - const reviewed = markMobileDiffReviewFileReviewed(createMobileDiffReviewState(1), descriptor, 5) - - const unreviewed = clearMobileDiffReviewFileReviewed(reviewed, descriptor.key, 8) - - expect(unreviewed.files[descriptor.key]?.reviewedAt).toBeUndefined() - expect(unreviewed.files[descriptor.key]?.reviewDiffIdentity).toBeUndefined() - expect(unreviewed.updatedAt).toBe(8) - }) }) diff --git a/mobile/src/source-control/review/optimistic-write-sequence.test.ts b/mobile/src/source-control/review/optimistic-write-sequence.test.ts index 2c2991e97f9..68e619cf5ad 100644 --- a/mobile/src/source-control/review/optimistic-write-sequence.test.ts +++ b/mobile/src/source-control/review/optimistic-write-sequence.test.ts @@ -2,28 +2,6 @@ import { describe, expect, it } from 'vitest' import { createOptimisticField } from './optimistic-write-sequence' describe('OptimisticField — last-intent-wins', () => { - it('renders optimistic when set, else authoritative', () => { - const field = createOptimisticField() - expect(field.resolve(true)).toBe(true) - const seq = field.begin(false) - expect(field.resolve(true)).toBe(false) - field.settleSuccess(seq) - expect(field.resolve(true)).toBe(true) - }) - - it('two rapid writes A then B: A resolving after B must NOT win (B is latest)', () => { - const field = createOptimisticField() - const seqA = field.begin(true) - const seqB = field.begin(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleSuccess(seqA)).toBe(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleSuccess(seqB)).toBe(true) - expect(field.resolve(false)).toBe(false) - }) - it('reverts only the latest write on failure', () => { const field = createOptimisticField() const seqA = field.begin(true) diff --git a/mobile/src/source-control/review/use-mobile-pr-branch-context.test.ts b/mobile/src/source-control/review/use-mobile-pr-branch-context.test.ts index 036dca60ef0..54b763ad659 100644 --- a/mobile/src/source-control/review/use-mobile-pr-branch-context.test.ts +++ b/mobile/src/source-control/review/use-mobile-pr-branch-context.test.ts @@ -1,81 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { MobileGitBranchCompareResult } from '../mobile-branch-compare' -import type { MobileGitStatusResult } from '../mobile-git-status' -import { - deriveMobilePrBranchContext, - loadMobilePrBranchContext -} from './use-mobile-pr-branch-context' - -function status(overrides: Partial): MobileGitStatusResult { - return { - entries: [], - conflictOperation: 'unknown', - branch: undefined, - head: undefined, - upstreamStatus: undefined, - ...overrides - } -} - -function branchCompare(headOid: string | null): MobileGitBranchCompareResult { - return { - summary: { - baseRef: 'main', - baseOid: null, - compareRef: 'feature', - headOid, - mergeBase: null, - changedFiles: 0, - commitsAhead: undefined, - status: 'ready', - errorMessage: undefined - }, - entries: [] - } -} - -describe('deriveMobilePrBranchContext', () => { - it('uses status.head when present', () => { - const result = deriveMobilePrBranchContext( - status({ branch: 'feature', head: 'sha-status' }), - branchCompare('sha-compare') - ) - expect(result.headSha).toBe('sha-status') - expect(result.branch).toBe('feature') - }) - - it('falls back to branchCompare headOid when status.head is absent', () => { - const result = deriveMobilePrBranchContext( - status({ branch: 'feature', head: undefined }), - branchCompare('sha-compare') - ) - expect(result.headSha).toBe('sha-compare') - }) - - it('returns null headSha when both status.head and headOid are absent', () => { - const result = deriveMobilePrBranchContext( - status({ branch: 'feature', head: undefined }), - branchCompare(null) - ) - expect(result.headSha).toBeNull() - }) - - it('returns null headSha when branchCompare is missing entirely', () => { - const result = deriveMobilePrBranchContext(status({ branch: 'feature' }), null) - expect(result.headSha).toBeNull() - }) - - it('returns null branch when status.branch is absent', () => { - const result = deriveMobilePrBranchContext(status({ branch: undefined }), null) - expect(result.branch).toBeNull() - }) - - it('does not throw on null status and null branchCompare', () => { - expect(() => deriveMobilePrBranchContext(null, null)).not.toThrow() - const result = deriveMobilePrBranchContext(null, null) - expect(result).toEqual({ branch: null, headSha: null, status: null }) - }) -}) +import { loadMobilePrBranchContext } from './use-mobile-pr-branch-context' describe('loadMobilePrBranchContext', () => { it('keeps status and repo eligibility when branchCompare fails', async () => { diff --git a/mobile/src/source-control/use-mobile-commit-message-generation.test.ts b/mobile/src/source-control/use-mobile-commit-message-generation.test.ts index ceed203f7d3..6714b1255c7 100644 --- a/mobile/src/source-control/use-mobile-commit-message-generation.test.ts +++ b/mobile/src/source-control/use-mobile-commit-message-generation.test.ts @@ -135,26 +135,4 @@ describe('useMobileCommitMessageGeneration', () => { expect(view.message).toBe('current workspace') expect(view.generating).toBe(false) }) - - it('shows no error from a run that was stopped and then failed', async () => { - reply.cancel = () => Promise.reject(new Error('transport closed')) - const unhandled = vi.fn() - process.on('unhandledRejection', unhandled) - act(() => { - renderer = create(createElement(Harness)) - }) - let pending: Promise | undefined - act(() => { - pending = view.generate?.() - }) - act(() => view.cancel?.()) - await act(async () => { - reply.reject?.(new Error('transport closed')) - await pending - await new Promise((resolve) => setTimeout(resolve, 0)) - }) - process.off('unhandledRejection', unhandled) - expect(view.error).toBeNull() - expect(unhandled).not.toHaveBeenCalled() - }) }) diff --git a/mobile/src/stats/home-stats-total.test.ts b/mobile/src/stats/home-stats-total.test.ts index 076d64b8a76..daff818e1fa 100644 --- a/mobile/src/stats/home-stats-total.test.ts +++ b/mobile/src/stats/home-stats-total.test.ts @@ -1,10 +1,5 @@ import { describe, expect, it } from 'vitest' -import { translate } from '../i18n/mobile-i18n' -import { formatHomeAgentTime, totalHomeStats } from './home-stats-total' - -const MINUTE = 60_000 -const HOUR = 60 * MINUTE -const DAY = 24 * HOUR +import { totalHomeStats } from './home-stats-total' describe('totalHomeStats', () => { it('sums every desktop instead of letting the last reply win', () => { @@ -46,20 +41,3 @@ describe('totalHomeStats', () => { expect(total).toEqual({ totalAgentsSpawned: 10, totalPRsCreated: 3, totalAgentTimeMs: 60_000 }) }) }) - -describe('formatHomeAgentTime', () => { - it('shows whole days once there is a day, without the hours', () => { - expect(formatHomeAgentTime(139 * DAY + 7 * HOUR + 30 * MINUTE, translate)).toBe('139d') - expect(formatHomeAgentTime(DAY, translate)).toBe('1d') - }) - - it('shows whole hours under a day', () => { - expect(formatHomeAgentTime(7 * HOUR + 59 * MINUTE, translate)).toBe('7h') - expect(formatHomeAgentTime(DAY - 1, translate)).toBe('23h') - }) - - it('shows minutes under an hour', () => { - expect(formatHomeAgentTime(42 * MINUTE + 59_000, translate)).toBe('42m') - expect(formatHomeAgentTime(0, translate)).toBe('0m') - }) -}) diff --git a/mobile/src/tasks/agent-launch-request.test.ts b/mobile/src/tasks/agent-launch-request.test.ts deleted file mode 100644 index 8ba6e67601e..00000000000 --- a/mobile/src/tasks/agent-launch-request.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readAgentLaunchCreateOutcome } from './agent-launch-request' - -const FALLBACK_DETAIL = - "Your default is a structured chat session, but its chat runtime isn't installed on this host (install it from a new chat tab in Orca); started a terminal agent instead." - -describe('readAgentLaunchCreateOutcome', () => { - it('surfaces why a chat default started a terminal', () => { - const reply = { - outcome: { kind: 'terminal', handle: 'term_1' }, - worktreeId: 'repo::/w', - receipt: { - mode: 'terminal', - preferred: 'structured', - reason: 'chat_runtime_not_installed', - detail: FALLBACK_DETAIL - } - } - expect(readAgentLaunchCreateOutcome(reply)).toEqual({ - worktreeId: 'repo::/w', - warning: FALLBACK_DETAIL - }) - }) -}) diff --git a/mobile/src/tasks/mobile-task-search.test.ts b/mobile/src/tasks/mobile-task-search.test.ts deleted file mode 100644 index 56a7bb08430..00000000000 --- a/mobile/src/tasks/mobile-task-search.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('./mobile-tasks-dependencies', () => ({ colors: {} })) - -import { githubKindFromQuery, normalizeGitHubPreset } from './mobile-tasks-item-mapping' -import { scopeGitHubTaskSearch } from '../../../src/shared/work-items/task-github-search' -import { getTaskPresetQuery } from '../../../src/shared/work-items/task-preset-query' - -describe('mobile task search parity', () => { - it('lets an explicit issue query override a saved PR preset', () => { - for (const preset of ['prs', 'my-prs', 'review'] as const) { - expect(githubKindFromQuery('is:issue is:open', preset)).toBe('issues') - expect(githubKindFromQuery('is:"issue" is:open', preset)).toBe('issues') - expect(scopeGitHubTaskSearch('is:issue is:open', 'prs')).toBe('is:issue is:open') - } - }) - - it('preserves the pull-request alias while browsing issues', () => { - expect(scopeGitHubTaskSearch('is:pull-request is:open', 'issues')).toBe( - 'is:pull-request is:open' - ) - expect(githubKindFromQuery('is:pull-request is:open', 'issues')).toBe('prs') - }) - - it('opens the PR tab for draft and review searches', () => { - for (const query of ['is:draft', 'reviewed-by:@me', 'review-requested:@me', 'is:merged']) { - expect(githubKindFromQuery(query, 'issues')).toBe('prs') - expect(scopeGitHubTaskSearch(query, 'issues')).toBe(`is:pr ${query}`) - } - }) - - it('does not read scope qualifiers out of labels or quoted search text', () => { - expect(scopeGitHubTaskSearch('label:is:pr', 'issues')).toBe('is:issue label:is:pr') - expect(scopeGitHubTaskSearch('"is:pull-request"', 'issues')).toBe('is:issue "is:pull-request"') - expect(githubKindFromQuery('"is:pr"', 'issues')).toBe('issues') - expect(scopeGitHubTaskSearch('is:"pr"', 'issues')).toBe('is:"pr"') - }) - - it('uses the current split-tab fallback for a legacy all preset', () => { - const preset = normalizeGitHubPreset('all') - expect(preset).toBe('issues') - expect(getTaskPresetQuery(preset)).toBe('is:issue is:open') - }) -}) diff --git a/mobile/src/tasks/smart-source-paste-intent.test.ts b/mobile/src/tasks/smart-source-paste-intent.test.ts index 9b47ffc60f2..39c53a499b7 100644 --- a/mobile/src/tasks/smart-source-paste-intent.test.ts +++ b/mobile/src/tasks/smart-source-paste-intent.test.ts @@ -1,36 +1,7 @@ import { describe, expect, it } from 'vitest' -import { - deriveRepoSlug, - findRepoMatchingSlugForPaste, - resolvePasteIntent, - type PasteRepoCandidate -} from './smart-source-paste-intent' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { deriveRepoSlug, resolvePasteIntent } from './smart-source-paste-intent' describe('resolvePasteIntent', () => { - it('classifies a GitHub issue/PR URL as a github-link', () => { - expect(resolvePasteIntent('https://github.com/acme/widgets/pull/12')).toEqual({ - kind: 'github-link', - link: { slug: { owner: 'acme', repo: 'widgets', host: 'github.com' }, number: 12, type: 'pr' } - }) - }) - - it('classifies a bare #number as a github-number', () => { - expect(resolvePasteIntent('#42')).toEqual({ kind: 'github-number', number: 42 }) - }) - - it('classifies a GitLab MR URL as a gitlab-link', () => { - const intent = resolvePasteIntent('https://gitlab.com/group/proj/-/merge_requests/8') - expect(intent?.kind).toBe('gitlab-link') - if (intent?.kind === 'gitlab-link') { - expect(intent.link).toMatchObject({ number: 8, type: 'mr' }) - } - }) - - it('returns null for plain search text', () => { - expect(resolvePasteIntent('login bug')).toBeNull() - }) - it('rejects oversized paste intents before any exact lookup', () => { expect( resolvePasteIntent(`https://github.com/acme/widgets/issues/12/${'x'.repeat(2048)}`) @@ -39,13 +10,6 @@ describe('resolvePasteIntent', () => { }) describe('deriveRepoSlug', () => { - it('prefers the upstream identity', () => { - expect(deriveRepoSlug({ upstream: { owner: 'up', repo: 'stream' } })).toEqual({ - owner: 'up', - repo: 'stream' - }) - }) - it('preserves an Enterprise upstream host', () => { expect( deriveRepoSlug({ @@ -53,44 +17,4 @@ describe('deriveRepoSlug', () => { }) ).toEqual({ owner: 'up', repo: 'stream', host: 'github.corp.example' }) }) - - it('parses an SSH remote URL', () => { - expect( - deriveRepoSlug({ gitRemoteIdentity: { remoteUrl: 'git@github.com:acme/widgets.git' } }) - ).toEqual({ owner: 'acme', repo: 'widgets' }) - }) - - it('parses an HTTPS remote URL', () => { - expect( - deriveRepoSlug({ gitRemoteIdentity: { remoteUrl: 'https://github.com/acme/widgets' } }) - ).toEqual({ owner: 'acme', repo: 'widgets' }) - }) - - it('returns null when no slug can be derived', () => { - expect(deriveRepoSlug({})).toBeNull() - }) -}) - -describe('findRepoMatchingSlug', () => { - const repos: PasteRepoCandidate[] = [ - { id: 'a', displayName: 'A', slug: { owner: 'acme', repo: 'widgets' } }, - { id: 'b', displayName: 'B', slug: null } - ] - - it('caches a rejected optional repo slug probe as no match', async () => { - const client = { - sendRequest: async () => { - throw new Error('connection closed') - } - } as unknown as RpcClient - - await expect( - findRepoMatchingSlugForPaste( - client, - repos, - { owner: 'enterprise', repo: 'widgets' }, - new Map() - ) - ).resolves.toBeNull() - }) }) diff --git a/mobile/src/tasks/worktree-create-retry.test.ts b/mobile/src/tasks/worktree-create-retry.test.ts index 1db6b4f42f9..ab2cb0702af 100644 --- a/mobile/src/tasks/worktree-create-retry.test.ts +++ b/mobile/src/tasks/worktree-create-retry.test.ts @@ -1,118 +1,46 @@ import { describe, expect, it } from 'vitest' +import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import type { ConnectionState } from '../transport/connection/connection-state' - import { createWorktreeWithNameRetry } from './worktree-create-retry' -type Attempt = { method: string; params: Record } - -// Model both pending-frame rejection and leaving connected; replay waits on transport recovery. -function connectionController(): { - getState: () => ConnectionState - onStateChange: (listener: (state: ConnectionState) => void) => () => void - set: (next: ConnectionState) => void -} { - let state: ConnectionState = 'connected' - const listeners = new Set<(next: ConnectionState) => void>() - return { - getState: () => state, - onStateChange: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) - }, - set: (next) => { - state = next - for (const listener of listeners) { - listener(next) - } - } - } -} +type Attempt = { method: string; params: unknown } function scriptedClient( - outcomes: Array< - | { id: string; displayName?: string; warning?: string } - | { errorMessage: string } - // takesMs models how long the ambiguity took to SURFACE — a clean close is - // instant, a half-open socket waits out the liveness watchdog or the timeout. - // reconnectsAfterMs brings the transport back so the next replay can run. - | { throws: unknown; dropsConnection?: boolean; takesMs?: number; reconnectsAfterMs?: number } - >, - attempts: Attempt[], - connection?: ReturnType, - // Use actual inbound timestamps so freshness survives suspension; absent timestamps fall back to send time. - lastInboundAt?: number | (() => number) + outcomes: ({ id: string; displayName?: string; warning?: string } | { errorMessage: string })[], + attempts: Attempt[] ): RpcClient { let call = 0 - return { - getState: () => connection?.getState() ?? 'connected', - getLastInboundAt: () => - (typeof lastInboundAt === 'function' ? lastInboundAt() : lastInboundAt) ?? null, - onStateChange: (listener: (state: ConnectionState) => void) => - connection?.onStateChange(listener) ?? (() => {}), - sendRequest: async (method: string, params?: unknown) => { - attempts.push({ method, params: (params ?? {}) as Record }) - const outcome = outcomes[Math.min(call, outcomes.length - 1)]! - call += 1 - if ('throws' in outcome) { - if (outcome.takesMs !== undefined) { - await new Promise((resolve) => setTimeout(resolve, outcome.takesMs)) - } - if (outcome.dropsConnection) { - connection?.set('reconnecting') - if (outcome.reconnectsAfterMs !== undefined) { - setTimeout(() => connection?.set('connected'), outcome.reconnectsAfterMs) - } - } - throw outcome.throws - } - if ('errorMessage' in outcome) { - return { - id: '1', - ok: false, - error: { code: 'x', message: outcome.errorMessage }, - _meta: { runtimeId: 'r' } - } - } + const client = new FakeSession('connected') + client.sendRequest.mockImplementation(async (method: string, params?: unknown) => { + attempts.push({ method, params: params ?? {} }) + const outcome = outcomes[Math.min(call, outcomes.length - 1)]! + call += 1 + if ('errorMessage' in outcome) { return { id: '1', - ok: true, - result: { - worktree: { - id: outcome.id, - ...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {}) - }, - ...(outcome.warning !== undefined ? { warning: outcome.warning } : {}) - }, + ok: false, + error: { code: 'x', message: outcome.errorMessage }, _meta: { runtimeId: 'r' } } } - } as unknown as RpcClient + return { + id: '1', + ok: true, + result: { + worktree: { + id: outcome.id, + ...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {}) + }, + ...(outcome.warning !== undefined ? { warning: outcome.warning } : {}) + }, + _meta: { runtimeId: 'r' } + } + }) + return client } describe('createWorktreeWithNameRetry', () => { - // Creation can succeed after PTY spawn failure; warning is the only host explanation. - - // Unmarked errors are definite failures and must never enter ambiguous replay. - - it('uses the host-selected display name after a collision retry', async () => { - const attempts: Attempt[] = [] - const client = scriptedClient( - [{ errorMessage: 'already exists locally' }, { id: 'wt-host-name', displayName: 'topic-3' }], - attempts - ) - - await expect( - createWorktreeWithNameRetry({ - client, - baseName: 'topic', - buildParams: (name) => ({ repo: 'id:r', name }), - worktreeCreateIdempotency: false - }) - ).resolves.toEqual({ worktreeId: 'wt-host-name', name: 'topic-3' }) - }) - it('falls back to the client candidate when an older host omits displayName', async () => { const attempts: Attempt[] = [] const client = scriptedClient( @@ -129,8 +57,4 @@ describe('createWorktreeWithNameRetry', () => { }) ).resolves.toEqual({ worktreeId: 'wt-legacy', name: 'topic-2' }) }) - - // Delivery-unknown uses WeakSet object identity; wrapping the rejection would lose evidence that the host may have created. - - // Definite failures must not acquire delivery-unknown marks. }) diff --git a/mobile/src/terminal/session/agent-send-keyboard-dismissal.test.ts b/mobile/src/terminal/session/agent-send-keyboard-dismissal.test.ts deleted file mode 100644 index db18802de77..00000000000 --- a/mobile/src/terminal/session/agent-send-keyboard-dismissal.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - shouldDismissKeyboardAfterTerminalSend, - type AgentSendKeyboardDismissalTab -} from './agent-send-keyboard-dismissal' - -function terminalTab(overrides: Partial = {}) { - return { type: 'terminal', title: 'Terminal', ...overrides } -} - -describe('shouldDismissKeyboardAfterTerminalSend', () => { - it('dismisses for a live agent session', () => { - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ agentStatus: { agentType: 'claude' } }), - true - ) - ).toBe(true) - }) - - it('dismisses off launchAgent before the first agent-status update lands', () => { - expect( - shouldDismissKeyboardAfterTerminalSend(terminalTab({ launchAgent: 'codex' }), true) - ).toBe(true) - }) - - it('keeps the keyboard when an agent send is rejected', () => { - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ agentStatus: { agentType: 'claude' } }), - false - ) - ).toBe(false) - }) - - it('keeps the keyboard for a plain shell so back-to-back commands stay typeable', () => { - expect(shouldDismissKeyboardAfterTerminalSend(terminalTab(), true)).toBe(false) - expect(shouldDismissKeyboardAfterTerminalSend(terminalTab({ agentStatus: null }), true)).toBe( - false - ) - }) - - it('treats a blank agent label as no agent', () => { - expect( - shouldDismissKeyboardAfterTerminalSend(terminalTab({ agentStatus: { agentType: '' } }), true) - ).toBe(false) - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ agentStatus: { agentType: ' ' } }), - true - ) - ).toBe(false) - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ - agentStatus: { agentType: null }, - launchAgent: null - }), - true - ) - ).toBe(false) - }) - - it('falls through to launchAgent only when live status carries no agent', () => { - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ - agentStatus: { agentType: null }, - launchAgent: 'claude' - }), - true - ) - ).toBe(true) - }) - - it('never dismisses for non-terminal tabs or a missing tab', () => { - expect( - shouldDismissKeyboardAfterTerminalSend( - { - type: 'markdown', - title: 'README.md', - agentStatus: { agentType: 'claude' } - }, - true - ) - ).toBe(false) - expect(shouldDismissKeyboardAfterTerminalSend(null, true)).toBe(false) - expect(shouldDismissKeyboardAfterTerminalSend(undefined, true)).toBe(false) - }) - - it('does not authorize dismissal from unknown status or a display-only title', () => { - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ agentStatus: { agentType: 'unknown' } }), - true - ) - ).toBe(false) - expect( - shouldDismissKeyboardAfterTerminalSend(terminalTab({ title: '✦ Gemini CLI' }), true) - ).toBe(false) - }) - - it.each(['zsh', 'bash', 'pwsh'])( - 'keeps the keyboard when identity-only done status is stale under %s', - (title) => { - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ - title, - agentStatus: { agentType: 'claude', state: 'done' }, - launchAgent: 'claude' - }), - true - ) - ).toBe(false) - } - ) - - it('still dismisses for a completed agent under a non-shell title', () => { - expect( - shouldDismissKeyboardAfterTerminalSend( - terminalTab({ - title: 'Terminal', - agentStatus: { agentType: 'claude', state: 'done' } - }), - true - ) - ).toBe(true) - }) -}) diff --git a/mobile/src/terminal/session/initial-session-terminal.test.ts b/mobile/src/terminal/session/initial-session-terminal.test.ts deleted file mode 100644 index cb30c8ff75c..00000000000 --- a/mobile/src/terminal/session/initial-session-terminal.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - shouldAutoCreateInitialSessionTerminal, - type InitialSessionTerminalAutoCreateInput -} from './initial-session-terminal' - -function baseInput( - overrides: Partial = {} -): InitialSessionTerminalAutoCreateInput { - return { - newlyCreatedWorkspace: true, - connected: true, - tabsLoaded: true, - visibleTabCount: 0, - hasActiveTerminalHandle: false, - createInFlight: false, - sawSessionTabs: false, - autoCreatedForWorktree: false, - ...overrides - } -} - -describe('shouldAutoCreateInitialSessionTerminal', () => { - it('creates the first terminal for a workspace that hydrates with nothing', () => { - expect(shouldAutoCreateInitialSessionTerminal(baseInput())).toBe(true) - }) - - it('does not re-create once this route has shown session tabs', () => { - expect(shouldAutoCreateInitialSessionTerminal(baseInput({ sawSessionTabs: true }))).toBe(false) - }) - - it('does not create from stale empty state while switching ordinary workspace routes', () => { - expect( - shouldAutoCreateInitialSessionTerminal( - baseInput({ - newlyCreatedWorkspace: false, - tabsLoaded: true, - visibleTabCount: 0 - }) - ) - ).toBe(false) - }) - - it('stays armed while an empty workspace is still loading', () => { - expect(shouldAutoCreateInitialSessionTerminal(baseInput({ tabsLoaded: false }))).toBe(false) - }) - - it('waits for the host connection', () => { - expect(shouldAutoCreateInitialSessionTerminal(baseInput({ connected: false }))).toBe(false) - }) - - it('defers to a lagging snapshot that still has a streaming terminal', () => { - expect( - shouldAutoCreateInitialSessionTerminal(baseInput({ hasActiveTerminalHandle: true })) - ).toBe(false) - }) - - it('does not stack a second create on an in-flight one', () => { - expect(shouldAutoCreateInitialSessionTerminal(baseInput({ createInFlight: true }))).toBe(false) - }) - - it('fires at most once per workspace on this route', () => { - expect( - shouldAutoCreateInitialSessionTerminal(baseInput({ autoCreatedForWorktree: true })) - ).toBe(false) - }) - - it('does not fire while tabs are visible', () => { - expect(shouldAutoCreateInitialSessionTerminal(baseInput({ visibleTabCount: 2 }))).toBe(false) - }) -}) diff --git a/mobile/src/terminal/session/mobile-terminal-diagnostics.test.ts b/mobile/src/terminal/session/mobile-terminal-diagnostics.test.ts deleted file mode 100644 index 51f389c6010..00000000000 --- a/mobile/src/terminal/session/mobile-terminal-diagnostics.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getMobileTerminalDiagnosticErrorName } from './mobile-terminal-diagnostics' - -describe('mobile terminal diagnostics', () => { - it('reports thrown error types without copying potentially sensitive messages', () => { - expect(getMobileTerminalDiagnosticErrorName(new TypeError('/private/worktree failed'))).toBe( - 'TypeError' - ) - expect(getMobileTerminalDiagnosticErrorName('raw failure')).toBe('string') - }) -}) diff --git a/mobile/src/terminal/session/mobile-terminal-records.test.ts b/mobile/src/terminal/session/mobile-terminal-records.test.ts index 1af453d0703..d5d663d307e 100644 --- a/mobile/src/terminal/session/mobile-terminal-records.test.ts +++ b/mobile/src/terminal/session/mobile-terminal-records.test.ts @@ -1,12 +1,8 @@ import { describe, expect, it } from 'vitest' import { getTerminalRecordsFromSessionTabs, - hasConnectedTerminalAbsentFromSessionTabs, mergeTerminalListWithKnownRecords, mergeTerminalRecordsByCurrentOrder, - mobileSessionTabsEqual, - mobileTerminalThemesEqual, - terminalRecordsEqual, type MobileTerminalSessionTab, type TerminalRecord } from './mobile-terminal-records' @@ -28,16 +24,6 @@ const darkTheme = { } describe('mobile terminal records', () => { - it('detects additional theme fields from a newer host', () => { - const withNewField = { - ...darkTheme, - theme: { ...darkTheme.theme, futureAccent: '#ff00ff' } - } - - expect(mobileTerminalThemesEqual(darkTheme, withNewField)).toBe(false) - expect(mobileTerminalThemesEqual(withNewField, { ...withNewField })).toBe(true) - }) - it('keeps the known theme when a session-tab snapshot omits it', () => { const known: TerminalRecord[] = [ { handle: 'pty-1', title: 'Old title', terminalTheme: darkTheme, isActive: false } @@ -74,23 +60,6 @@ describe('mobile terminal records', () => { } }) - it('treats a host pane identity change as a terminal record change', () => { - const record: TerminalRecord = { handle: 'pty-1', title: 'Terminal', isActive: true } - - expect( - terminalRecordsEqual( - [{ ...record, agentIdentity: 'claude' }], - [{ ...record, agentIdentity: 'cursor' }] - ) - ).toBe(false) - expect( - terminalRecordsEqual( - [{ ...record, agentIdentity: 'cursor' }], - [{ ...record, agentIdentity: 'cursor' }] - ) - ).toBe(true) - }) - it('keeps session-tab terminal themes when terminal.list omits them', () => { const terminalList: TerminalRecord[] = [ { handle: 'pty-1', title: 'Terminal', isActive: true }, @@ -127,124 +96,6 @@ describe('mobile terminal records', () => { ]) }) - it('ignores pending terminal tabs without a handle', () => { - expect( - getTerminalRecordsFromSessionTabs([ - { - type: 'terminal', - id: 'pending', - title: 'Terminal', - terminal: null, - terminalTheme: lightTheme, - isActive: true - } - ]) - ).toEqual([]) - }) - - it('treats a launch draft appearing or retracting as a session-tab change', () => { - const base: MobileTerminalSessionTab = { - type: 'terminal', - id: 'term-1::leaf-1', - parentTabId: 'term-1', - leafId: 'leaf-1', - title: 'Claude', - status: 'ready', - terminal: 'pty-1', - isActive: true - } - const seeded: MobileTerminalSessionTab = { - ...base, - launchDraft: 'https://github.com/o/r/issues/12', - launchDraftCreatedAt: 1 - } - - expect(mobileSessionTabsEqual([base], [seeded])).toBe(false) - expect(mobileSessionTabsEqual([seeded], [base])).toBe(false) - expect(mobileSessionTabsEqual([seeded], [{ ...seeded }])).toBe(true) - expect(mobileSessionTabsEqual([seeded], [{ ...seeded, launchDraftCreatedAt: 2 }])).toBe(false) - }) - - it('treats a browser load failure appearing or changing as a session-tab change', () => { - const url = 'http://localhost:3000/' - const page: Parameters[0][number] = { - type: 'browser', - id: 'browser-1', - url, - loading: false - } - const refused = { - ...page, - loadError: { code: -102, description: 'ERR_CONNECTION_REFUSED', validatedUrl: url } - } - expect(mobileSessionTabsEqual([page], [refused])).toBe(false) - expect( - mobileSessionTabsEqual([refused], [{ ...refused, loadError: { ...refused.loadError } }]) - ).toBe(true) - expect( - mobileSessionTabsEqual( - [refused], - [{ ...refused, loadError: { ...refused.loadError, code: -105 } }] - ) - ).toBe(false) - }) - - it('treats terminal agent-status changes as session-tab changes', () => { - const base: MobileTerminalSessionTab = { - type: 'terminal', - id: 'term-1::leaf-1', - parentTabId: 'term-1', - leafId: 'leaf-1', - title: 'Claude', - status: 'ready', - terminal: 'pty-1', - isActive: true, - agentStatus: { - state: 'working', - prompt: '', - updatedAt: 1, - stateStartedAt: 1, - paneKey: 'term-1:leaf-1', - terminalHandle: 'pty-1', - stateHistory: [] - } - } - - expect( - mobileSessionTabsEqual( - [base], - [ - { - ...base, - agentStatus: { - ...base.agentStatus!, - state: 'blocked' as const, - updatedAt: 2, - stateStartedAt: 2 - } - } - ] - ) - ).toBe(false) - }) - - it('treats structured agent-session identity changes as session-tab changes', () => { - const base = { - type: 'agent-session' as const, - id: 'agent-tab-1', - title: 'Codex', - sessionId: 'session-1', - agent: 'codex', - isActive: true - } - - expect(mobileSessionTabsEqual([base], [{ ...base }])).toBe(true) - expect(mobileSessionTabsEqual([base], [{ ...base, sessionId: 'session-2' }])).toBe(false) - expect( - mobileSessionTabsEqual([base], [{ ...base, chatStatus: { state: 'working', updatedAt: 1 } }]) - ).toBe(false) - }) - const record = (over: Partial & { handle: string }): TerminalRecord => ({ title: 'Terminal', terminalTheme: undefined, @@ -259,43 +110,6 @@ describe('mobile terminal records', () => { isActive: false }) - it('reports a connected terminal the tab snapshot dropped', () => { - const held = [ - record({ handle: 'pty-1', connected: true }), - record({ handle: 'pty-2', connected: true }) - ] - - expect(hasConnectedTerminalAbsentFromSessionTabs(held, [terminalTab('pty-1')])).toBe(true) - }) - - it('ignores parked handles that tabs never carry', () => { - const parked = [ - record({ handle: 'pty-1', connected: false }), - record({ handle: 'pty-2', connected: false }) - ] - - // Parked leaves legitimately lack tabs; counting them as missing live PTYs would force fast polling forever. - expect(hasConnectedTerminalAbsentFromSessionTabs(parked, [])).toBe(false) - }) - - it('ignores orphaned PTYs, which have no leaf and so never appear as a tab', () => { - const orphan = [record({ handle: 'pty-1', connected: true, orphaned: true })] - - expect(hasConnectedTerminalAbsentFromSessionTabs(orphan, [])).toBe(false) - }) - - it('ignores a host that omits connected rather than assuming liveness', () => { - expect(hasConnectedTerminalAbsentFromSessionTabs([record({ handle: 'pty-1' })], [])).toBe(false) - }) - - it('clears once the snapshot covers every connected terminal', () => { - const held = [record({ handle: 'pty-1', connected: true })] - - expect( - hasConnectedTerminalAbsentFromSessionTabs(held, [terminalTab('pty-1'), terminalTab('pty-2')]) - ).toBe(false) - }) - it('keeps the merge additive so absence only schedules the sweep', () => { const held = [ record({ handle: 'pty-1', connected: true }), diff --git a/mobile/src/terminal/session/mobile-terminal-viewport-resubscribe.test.ts b/mobile/src/terminal/session/mobile-terminal-viewport-resubscribe.test.ts deleted file mode 100644 index 674a38151af..00000000000 --- a/mobile/src/terminal/session/mobile-terminal-viewport-resubscribe.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - readTerminalViewportDims, - resolveTerminalViewportResubscribe, - shouldResubscribeAfterViewportMeasure -} from './mobile-terminal-viewport-resubscribe' - -const PHONE = { cols: 40, rows: 50 } - -describe('readTerminalViewportDims', () => { - it('accepts only usable numeric host dimensions', () => { - expect(readTerminalViewportDims({ cols: 40, rows: 50 })).toEqual({ - hostCols: 40, - hostRows: 50 - }) - expect(readTerminalViewportDims({ cols: Number.NaN, rows: 0 })).toEqual({ - hostCols: null, - hostRows: null - }) - }) -}) - -describe('resolveTerminalViewportResubscribe', () => { - it('holds on absent host dims instead of resubscribing (STA-3337 regression)', () => { - for (const [hostCols, hostRows] of [ - [null, null], - [80, null], - [null, 24] - ] as const) { - expect( - resolveTerminalViewportResubscribe({ - hostCols, - hostRows, - viewportMeasured: true, - viewport: PHONE, - attempts: 0 - }) - ).toEqual({ kind: 'hold' }) - } - }) - - it('converges when host dims match the measured viewport', () => { - expect( - resolveTerminalViewportResubscribe({ - hostCols: PHONE.cols, - hostRows: PHONE.rows, - viewportMeasured: true, - viewport: PHONE, - attempts: 2 - }) - ).toEqual({ kind: 'converged' }) - }) - - it('accepts desktop dims in desktop mode instead of treating them as a failed fit (#28487)', () => { - expect( - resolveTerminalViewportResubscribe({ - hostCols: 150, - hostRows: 40, - viewportMeasured: true, - viewport: PHONE, - attempts: 0, - displayMode: 'desktop' - }) - ).toEqual({ kind: 'converged' }) - }) -}) - -describe('shouldResubscribeAfterViewportMeasure', () => { - it('always resubscribes when the viewport was never measured (server must learn it)', () => { - expect( - shouldResubscribeAfterViewportMeasure({ - hostCols: PHONE.cols, - hostRows: PHONE.rows, - measured: PHONE, - viewportWasMeasured: false - }) - ).toBe(true) - }) - - it('skips the resubscribe when the fresh measure already matches the host', () => { - expect( - shouldResubscribeAfterViewportMeasure({ - hostCols: PHONE.cols, - hostRows: PHONE.rows, - measured: PHONE, - viewportWasMeasured: true - }) - ).toBe(false) - }) - - it('resubscribes when the host still disagrees with the fresh measure', () => { - expect( - shouldResubscribeAfterViewportMeasure({ - hostCols: 80, - hostRows: 24, - measured: PHONE, - viewportWasMeasured: true - }) - ).toBe(true) - }) -}) diff --git a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts b/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts index e41c3e74fdf..82b0e0590ab 100644 --- a/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts +++ b/mobile/src/terminal/terminal-live-accessory-raw-send.test.ts @@ -26,16 +26,6 @@ const BASE_ARGS = { } as const describe('terminal live accessory raw send', () => { - it('drops the bytes instead of sending while disconnected', async () => { - const { client, sendRequest } = captureClient() - - await expect( - sendTerminalLiveAccessoryRawBytes({ ...BASE_ARGS, client, connState: 'reconnecting' }) - ).resolves.toBe(false) - - expect(sendRequest).not.toHaveBeenCalled() - }) - it('drops the bytes when the terminal selection went stale mid-flush', async () => { const { client, sendRequest } = captureClient() diff --git a/mobile/src/theme/mobile-theme-contrast.test.ts b/mobile/src/theme/mobile-theme-contrast.test.ts deleted file mode 100644 index f1a9d94325a..00000000000 --- a/mobile/src/theme/mobile-theme-contrast.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { paletteForScheme } from './mobile-theme' - -function channelLuminance(channel: number): number { - const value = channel / 255 - return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4 -} - -function relativeLuminance(hex: string): number { - const red = Number.parseInt(hex.slice(1, 3), 16) - const green = Number.parseInt(hex.slice(3, 5), 16) - const blue = Number.parseInt(hex.slice(5, 7), 16) - return ( - 0.2126 * channelLuminance(red) + - 0.7152 * channelLuminance(green) + - 0.0722 * channelLuminance(blue) - ) -} - -function contrastRatio(foreground: string, background: string): number { - const lighter = Math.max(relativeLuminance(foreground), relativeLuminance(background)) - const darker = Math.min(relativeLuminance(foreground), relativeLuminance(background)) - return (lighter + 0.05) / (darker + 0.05) -} - -describe.each(['dark', 'light'] as const)('mobile text contrast (%s)', (scheme) => { - const colors = paletteForScheme(scheme) - - // Dark textMuted is desktop's --chat-foreground-faint (4.33:1 on bgRaised), so only page surfaces are held to 4.5. - it('keeps muted text readable on page and panel surfaces', () => { - for (const surface of [colors.bgBase, colors.bgPanel]) { - expect(contrastRatio(colors.textMuted, surface)).toBeGreaterThanOrEqual(4.5) - } - }) - - // WCAG 1.4.11: the edge is what marks a field, so it holds 3:1 on every surface fields sit on, and so does focus. - it('keeps a text field identifiable on the screen, a sheet and a sheet group', () => { - const surfaces = [ - colors.bgBase, - colors.bgPanel, - colors.sheetSurface, - colors.sheetGroup, - colors.composerSurface - ] - for (const surface of surfaces) { - expect(contrastRatio(colors.inputBorder, surface)).toBeGreaterThanOrEqual(3) - expect(contrastRatio(colors.accentBlue, surface)).toBeGreaterThanOrEqual(3) - } - expect(contrastRatio(colors.textMuted, colors.composerSurface)).toBeGreaterThanOrEqual(4.5) - }) - - // WCAG 1.4.11: the create button is an icon-only disc, so its glyph and its edge each hold 3:1. - it('keeps the floating create button and its glyph visible on the page', () => { - expect(contrastRatio(colors.createActionFill, colors.bgBase)).toBeGreaterThanOrEqual(3) - expect( - contrastRatio(colors.onCreateActionFill, colors.createActionFill) - ).toBeGreaterThanOrEqual(3) - }) - - it('keeps your own message readable on its bubble', () => { - expect( - contrastRatio(colors.chatForegroundStrong, colors.chatUserSurface) - ).toBeGreaterThanOrEqual(4.5) - }) -}) diff --git a/mobile/src/transport/hosts/home-host-auto-connect.test.ts b/mobile/src/transport/hosts/home-host-auto-connect.test.ts deleted file mode 100644 index 448c78bde82..00000000000 --- a/mobile/src/transport/hosts/home-host-auto-connect.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { HostProfile } from './host-profile' -import { selectHomeAutoConnectHostIds } from './home-host-auto-connect' - -function host(id: string, lastConnected: number, credentials = true): HostProfile { - return { - id, - name: id, - endpoint: `ws://${id}`, - deviceToken: credentials ? `token-${id}` : '', - publicKeyB64: credentials ? `key-${id}` : '', - lastConnected - } -} - -describe('home host auto-connect', () => { - it('limits startup connections to the most recently used credentialed hosts', () => { - const hosts = [ - host('old', 1), - host('newest', 5), - host('second', 4), - host('third', 3), - host('fourth', 2), - host('missing-credentials', 6, false), - { ...host('missing-token', 7), deviceToken: '' }, - { ...host('missing-key', 8), publicKeyB64: '' } - ] - - expect(selectHomeAutoConnectHostIds(hosts)).toEqual(['newest', 'second', 'third']) - }) - - it('does not mutate the host card order', () => { - const hosts = [host('old', 1), host('new', 2)] - - selectHomeAutoConnectHostIds(hosts) - - expect(hosts.map((item) => item.id)).toEqual(['old', 'new']) - }) -}) diff --git a/mobile/src/transport/hosts/host-credential-cleanup.test.ts b/mobile/src/transport/hosts/host-credential-cleanup.test.ts deleted file mode 100644 index 61b3dd98a07..00000000000 --- a/mobile/src/transport/hosts/host-credential-cleanup.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import AsyncStorage from '@react-native-async-storage/async-storage' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - loadPendingHostCredentialCleanup, - loadPendingHostCredentialCleanupIds, - recordHostCredentialCleanupIntent, - resetHostCredentialCleanupForTests -} from './host-credential-cleanup' - -const asyncStorageMock = vi.hoisted(() => ({ - getItem: vi.fn(), - setItem: vi.fn() -})) - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: asyncStorageMock -})) - -const PENDING_STORAGE_KEY = 'orca:pending-host-credential-cleanups' -let storedPendingIds: string[] -let readShouldFail = false - -describe('host credential cleanup', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.clearAllMocks() - resetHostCredentialCleanupForTests() - storedPendingIds = [] - readShouldFail = false - asyncStorageMock.getItem.mockImplementation(async (key: string) => { - if (key !== PENDING_STORAGE_KEY) { - return null - } - if (readShouldFail) { - throw new Error('async storage unavailable') - } - return JSON.stringify(storedPendingIds) - }) - asyncStorageMock.setItem.mockImplementation(async (key: string, raw: string) => { - if (key === PENDING_STORAGE_KEY) { - storedPendingIds = JSON.parse(raw) as string[] - } - }) - }) - - afterEach(() => { - vi.useRealTimers() - resetHostCredentialCleanupForTests() - }) - - it('records cleanup intent without starting native deletion', async () => { - await recordHostCredentialCleanupIntent('host-1') - - await expect(loadPendingHostCredentialCleanupIds()).resolves.toEqual(['host-1']) - }) - - it('reports storageUnreadable when the durable queue cannot be read', async () => { - storedPendingIds = ['host-a'] - - readShouldFail = true - await expect(loadPendingHostCredentialCleanup()).resolves.toEqual({ - ids: [], - storageUnreadable: true - }) - }) - - it('soft-loads empty when pending-cleanup storage is malformed', async () => { - vi.mocked(AsyncStorage.getItem).mockResolvedValue('{') - - await expect(loadPendingHostCredentialCleanupIds()).resolves.toEqual([]) - await expect(loadPendingHostCredentialCleanup()).resolves.toEqual({ - ids: [], - storageUnreadable: true - }) - }) -}) diff --git a/mobile/src/transport/hosts/host-descriptor-store.test.ts b/mobile/src/transport/hosts/host-descriptor-store.test.ts deleted file mode 100644 index dee4e26bc25..00000000000 --- a/mobile/src/transport/hosts/host-descriptor-store.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - recordHostDescriptor, - resetHostDescriptorStoreForTests, - useHostDescriptor -} from './host-descriptor-store' - -describe('host descriptor store', () => { - let renderer: ReactTestRenderer | null = null - const seen: Record[]> = {} - - function Row({ hostId }: { hostId: string }): null { - const descriptor = useHostDescriptor(hostId) - ;(seen[hostId] ??= []).push(descriptor) - return null - } - - beforeEach(() => { - resetHostDescriptorStoreForTests() - for (const hostId of Object.keys(seen)) { - delete seen[hostId] - } - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - }) - - it('publishes the latest reply, including one that omitted both fields', async () => { - await act(async () => { - renderer = create(createElement(Row, { hostId: 'host-1' })) - }) - await act(async () => { - recordHostDescriptor('host-1', { machineName: 'Old', platform: 'win32' }) - }) - expect(seen['host-1']?.at(-1)).toEqual({ machineName: 'Old', platform: 'win32' }) - - await act(async () => { - recordHostDescriptor('host-1', { machineName: null, platform: null }) - }) - expect(seen['host-1']?.at(-1)).toEqual({ machineName: null, platform: null }) - }) -}) diff --git a/mobile/src/transport/hosts/host-endpoint-edit.test.ts b/mobile/src/transport/hosts/host-endpoint-edit.test.ts index 79838479d83..9608ca495fe 100644 --- a/mobile/src/transport/hosts/host-endpoint-edit.test.ts +++ b/mobile/src/transport/hosts/host-endpoint-edit.test.ts @@ -3,18 +3,6 @@ import { describe, expect, it } from 'vitest' import { resolveHostEndpointEdit } from './host-endpoint-edit' describe('resolveHostEndpointEdit', () => { - it.each([ - ['wss://old.example.com', 'new.example.com', 'wss://new.example.com:443'], - ['wss://old.example.com:8443', 'new.example.com', 'wss://new.example.com:8443'], - ['ws://old.local', 'new.local', 'ws://new.local:6768'], - ['ws://old.local:80', 'new.local', 'ws://new.local:80'], - ['wss://[2001:db8::1]', '[2001:db8::2]', 'wss://[2001:db8::2]:443'] - ])('uses the current endpoint semantics for an address edit', (stored, input, expected) => { - const edit = resolveHostEndpointEdit(stored, input) - - expect(edit).toEqual({ kind: 'changed', endpoint: expected }) - }) - it.each([ ['ws://192.168.1.10:6768', 'wss://tunnel.example.com', 'wss://tunnel.example.com:443'], ['wss://old.example.com:8443', ' WSS://tunnel.example.com ', 'wss://tunnel.example.com:443'], diff --git a/mobile/src/transport/hosts/host-endpoint.test.ts b/mobile/src/transport/hosts/host-endpoint.test.ts index 9ba9b43f2db..997286e0981 100644 --- a/mobile/src/transport/hosts/host-endpoint.test.ts +++ b/mobile/src/transport/hosts/host-endpoint.test.ts @@ -2,27 +2,6 @@ import { describe, expect, it } from 'vitest' import { displayHostEndpoint, normalizeHostEndpoint } from './host-endpoint' describe('normalizeHostEndpoint', () => { - it('accepts bare host:port', () => { - expect(normalizeHostEndpoint('192.168.1.10:6768')).toEqual({ - ok: true, - endpoint: 'ws://192.168.1.10:6768' - }) - }) - - it('uses fallbackPort when the user omits the port', () => { - expect(normalizeHostEndpoint('mac-mini.local', { fallbackPort: '7777' })).toEqual({ - ok: true, - endpoint: 'ws://mac-mini.local:7777' - }) - }) - - it('fills missing port on scheme URLs from fallbackPort', () => { - expect(normalizeHostEndpoint('ws://192.168.1.10', { fallbackPort: '9000' })).toEqual({ - ok: true, - endpoint: 'ws://192.168.1.10:9000' - }) - }) - it('preserves explicit ws :80 and wss :443 instead of rewriting to fallback', () => { expect(normalizeHostEndpoint('ws://192.168.1.10:80', { fallbackPort: '6768' })).toEqual({ ok: true, @@ -36,31 +15,6 @@ describe('normalizeHostEndpoint', () => { expect(displayHostEndpoint('wss://desk.example:443')).toBe('desk.example:443') }) - it('trims whitespace', () => { - expect(normalizeHostEndpoint(' 10.0.0.2:6768 ')).toEqual({ - ok: true, - endpoint: 'ws://10.0.0.2:6768' - }) - }) - - it('accepts bracketed IPv6 with port', () => { - expect(normalizeHostEndpoint('[fd7a:115c:a1e0::1]:6768')).toEqual({ - ok: true, - endpoint: 'ws://[fd7a:115c:a1e0::1]:6768' - }) - }) - - it('keeps ordinary DNS names that contain numeric labels', () => { - expect(normalizeHostEndpoint('desk123.local:6768')).toEqual({ - ok: true, - endpoint: 'ws://desk123.local:6768' - }) - expect(normalizeHostEndpoint('ws://123.example:6768')).toEqual({ - ok: true, - endpoint: 'ws://123.example:6768' - }) - }) - it('preserves wss when re-normalizing bare host:port via fallbackScheme', () => { expect( normalizeHostEndpoint('desk.example:8443', { fallbackScheme: 'wss', fallbackPort: '8443' }) diff --git a/mobile/src/transport/hosts/host-name-identity.test.ts b/mobile/src/transport/hosts/host-name-identity.test.ts index 6ecb42569e2..f175b608414 100644 --- a/mobile/src/transport/hosts/host-name-identity.test.ts +++ b/mobile/src/transport/hosts/host-name-identity.test.ts @@ -85,12 +85,6 @@ describe('host name identity', () => { } describe('legacy classification', () => { - it('treats a typed legacy name as a phone override and a generated one as none', async () => { - const hosts = await loadHosts() - expect(hosts.find(({ id }) => id === GENERATED_HOST.id)?.personalName).toBeUndefined() - expect(hosts.find(({ id }) => id === TYPED_HOST.id)?.personalName).toBe('Windows-Low Spec') - }) - it('does not re-classify an adopted machine name once identity fields exist', async () => { // A record the descriptor writer already touched: non-generated name, no override. storedHostsRaw = JSON.stringify([ @@ -126,27 +120,6 @@ describe('host name identity', () => { }) describe('updateHostDescriptor', () => { - it('adopts a reported machine name as the display name of an unoverridden host', async () => { - await updateHostDescriptor(GENERATED_HOST.id, { - machineName: 'm4airs-Air', - platform: 'darwin' - }) - expect(stored().find(({ id }) => id === GENERATED_HOST.id)).toMatchObject({ - name: 'm4airs-Air', - lastKnownMachineName: 'm4airs-Air', - lastKnownHostPlatform: 'darwin' - }) - }) - - it('records the descriptor under an override without touching the display name', async () => { - await updateHostDescriptor(TYPED_HOST.id, { machineName: 'm4airs-Air', platform: 'darwin' }) - expect(stored().find(({ id }) => id === TYPED_HOST.id)).toMatchObject({ - name: 'Windows-Low Spec', - personalName: 'Windows-Low Spec', - lastKnownMachineName: 'm4airs-Air' - }) - }) - it('clears a stale machine name when a live host stops reporting one', async () => { await updateHostDescriptor(GENERATED_HOST.id, { machineName: 'm4airs-Air', @@ -157,13 +130,6 @@ describe('host name identity', () => { expect(record?.lastKnownMachineName).toBeUndefined() expect(record?.name).toBe('m4airs-Air') }) - - it('swallows unreadable storage instead of surfacing an error', async () => { - storedHostsRaw = '{' - await expect( - updateHostDescriptor(GENERATED_HOST.id, { machineName: 'm4airs-Air', platform: 'darwin' }) - ).resolves.toBeUndefined() - }) }) describe('re-pair', () => { @@ -186,22 +152,6 @@ describe('host name identity', () => { }) }) - it('re-resolves an adopted name after a re-pair that offered the stored one', async () => { - await updateHostDescriptor(GENERATED_HOST.id, { - machineName: 'm4airs-Air', - platform: 'darwin' - }) - await savePairedHost({ - id: GENERATED_HOST.id, - name: 'Host 1', - endpoint: GENERATED_HOST.endpoint, - deviceToken: 'fresh-token', - publicKeyB64: GENERATED_HOST.publicKeyB64, - lastConnected: 99 - }) - expect(stored().find(({ id }) => id === GENERATED_HOST.id)?.name).toBe('m4airs-Air') - }) - it('does not roll back identity changed since a connection took its profile snapshot', async () => { await updateHostDescriptor(TYPED_HOST.id, { machineName: 'Studio', platform: 'darwin' }) // Use a connection-held snapshot to prove saves cannot roll back later identity changes. @@ -220,14 +170,6 @@ describe('host name identity', () => { }) describe('phone override edit', () => { - it('sets the override and the display name together', async () => { - await updateHostNameAndEndpoint(GENERATED_HOST.id, { personalName: 'Basement Rig' }) - expect(stored().find(({ id }) => id === GENERATED_HOST.id)).toMatchObject({ - name: 'Basement Rig', - personalName: 'Basement Rig' - }) - }) - it('clearing the override returns to the desktop-reported name', async () => { await updateHostDescriptor(TYPED_HOST.id, { machineName: 'm4airs-Air', platform: 'darwin' }) await updateHostNameAndEndpoint(TYPED_HOST.id, { personalName: null }) diff --git a/mobile/src/transport/hosts/host-names.test.ts b/mobile/src/transport/hosts/host-names.test.ts deleted file mode 100644 index ffa608638b7..00000000000 --- a/mobile/src/transport/hosts/host-names.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getNextHostNameFromHosts } from './host-names' - -describe('getNextHostNameFromHosts', () => { - it('increments the largest numbered default host name', () => { - expect( - getNextHostNameFromHosts([ - { name: 'Host 2' }, - { name: 'Custom workstation' }, - { name: 'Host 99 extra' }, - { name: 'My Host 100' }, - { name: 'Host 7' }, - { name: 'Host 3' } - ]) - ).toBe('Host 8') - }) - - it('handles 130,000 host names', () => { - const hosts = Array.from({ length: 130_000 }, (_, index) => ({ - name: `Host ${index + 1}` - })) - - expect(getNextHostNameFromHosts(hosts)).toBe('Host 130001') - }) -}) diff --git a/mobile/src/worktree/agent-row-display.ts b/mobile/src/worktree/agent-row-display.ts index 164c4699422..5969f45afc0 100644 --- a/mobile/src/worktree/agent-row-display.ts +++ b/mobile/src/worktree/agent-row-display.ts @@ -3,20 +3,11 @@ import { isAgentStatusFresh } from '../../../src/shared/agent-status/contracts/a import { agentVerdictDisplayMark } from '../../../src/shared/agent-status/lifecycle/agent-main-agent-verdict' import { resolveDecayedAgentRowState } from '../../../src/shared/agent-status/presentation/agent-row-decay-state' import { getAgentRowPrimaryText } from '../../../src/shared/agent-status/presentation/agent-row-primary-text' +import type { AgentListStatus } from '../../../src/shared/agent-status/presentation/agent-list-status' import { translate } from '../i18n/mobile-i18n' -// Mirror desktop AgentStateDot vocabulary. -export type AgentDotState = - | 'working' - | 'monitoring' - | 'blocked' - | 'waiting' - | 'done' - | 'idle' - | 'unverifiable' - | 'interrupted' - | 'failed' - | 'unconfirmed' +// Desktop AgentStateDot's vocabulary. +export type AgentDotState = AgentListStatus // A session tab's AgentStatusEntry leaves `interrupted` optional; worktree rows always send it. type AgentRowVerdictSource = Pick & { @@ -69,6 +60,8 @@ export function agentStateLabel(state: AgentDotState): string { return translate('worktree.agentRowDisplay.idle', 'Idle') case 'unverifiable': return translate('worktree.agentRowDisplay.unverifiable', 'No recent update') + case 'permission': + return translate('worktree.agentRowDisplay.permission', 'Needs attention') } } diff --git a/mobile/src/worktree/home-host-worktree-fetch.ts b/mobile/src/worktree/home-host-worktree-fetch.ts index ac17d70c8a4..783f3376b67 100644 --- a/mobile/src/worktree/home-host-worktree-fetch.ts +++ b/mobile/src/worktree/home-host-worktree-fetch.ts @@ -3,11 +3,11 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract' import '../transport/connection/stable-logical-rpc-client' import { isLogicalClientCutoverError } from '../transport/connection/logical-client-cutover-error' import { + homeAgentEntries, markHomeWorktreeCatalogUnavailable, type HomeWorktreeSummary, type HostWorktreeInfo } from './home-worktree-info' -import { selectHomeAttentionWorktrees } from './home-jump-back-in' import { pickResumeWorktree } from './resume-worktree' import { isWorktreeActive } from './workspace-list-sections' import { WorktreeCatalogSnapshotClient } from './worktree-catalog-snapshot-client' @@ -59,7 +59,7 @@ export function fetchHomeHostWorktreeInfo( markUnavailable() return } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the rows stay opaque because three screens project a row differently. Home reads `status`, `sidebarStatus` and the resume pick through their own guards, plus the host-typed `agents` that name Jump back in rows, and the `worktree-home-catalog` golden records the row it is given as `{worktreeId, displayName, repo, status}`. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the rows stay opaque because three screens project a row differently. Home reads `status`, `sidebarStatus` and the resume pick through their own guards, plus the host-typed `agents` the Agents list shows, and the `worktree-home-catalog` golden records the row it is given as `{worktreeId, displayName, repo, status}`. const worktrees = rows as HomeWorktreeSummary[] setCachedWorktrees(hostId, worktrees, { proven: true }) // Count what the list shows: archived rows are hidden, and active is the sleeping filter's rule. @@ -73,7 +73,7 @@ export function fetchHomeHostWorktreeInfo( totalWorktrees: listed.length, activeCount: listed.filter(isWorktreeActive).length, lastActiveWorktree: lastActive, - attention: selectHomeAttentionWorktrees(listed), + agents: homeAgentEntries(listed), countsProvenAt: Date.now() } })) diff --git a/mobile/src/worktree/home-jump-back-in.test.ts b/mobile/src/worktree/home-jump-back-in.test.ts deleted file mode 100644 index 1b83a5269a4..00000000000 --- a/mobile/src/worktree/home-jump-back-in.test.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { selectHomeAttentionWorktrees, selectHomeJumpBackInRows } from './home-jump-back-in' -import type { HomeWorktreeSummary, HostWorktreeInfo } from './home-worktree-info' - -const NOW = 1_000_000_000 - -function row(id: string, fields: Partial): HomeWorktreeSummary { - return { - worktreeId: id, - repo: 'orca', - branch: id, - displayName: id, - liveTerminalCount: 1, - ...fields - } -} - -function agent(paneKey: string, fields: Partial): RuntimeWorktreeAgentRow { - return { - paneKey, - parentPaneKey: null, - state: 'working', - agentType: 'claude', - prompt: '', - taskTitle: null, - displayName: null, - lastAssistantMessage: null, - toolName: null, - toolInput: null, - interrupted: false, - stateStartedAt: NOW, - updatedAt: NOW, - ...fields - } -} - -function info(hostId: string, rows: HomeWorktreeSummary[]): HostWorktreeInfo { - return { - hostId, - totalWorktrees: rows.length, - activeCount: 0, - lastActiveWorktree: null, - attention: selectHomeAttentionWorktrees(rows), - countsProvenAt: NOW - } -} - -describe('home jump back in', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('puts agents waiting on the user first, then unseen finished work, then running work', () => { - const rows = selectHomeAttentionWorktrees([ - row('running', { sidebarStatus: 'working', lastOutputAt: NOW }), - row('finished-seen', { sidebarStatus: 'done', unread: false }), - row('finished-unseen', { sidebarStatus: 'done', unread: true, lastOutputAt: NOW - 5 }), - row('blocked', { sidebarStatus: 'permission', lastOutputAt: NOW - 10 }), - row('archived', { sidebarStatus: 'permission', isArchived: true }), - row('idle', { status: 'inactive', hasHostSidebarActivity: false }) - ]) - expect(rows.map((worktree) => worktree.worktreeId)).toEqual([ - 'blocked', - 'finished-unseen', - 'running' - ]) - }) - - it('claims no agent state for a desktop that is offline or whose last read failed', () => { - const blocked = [row('blocked', { sidebarStatus: 'permission' })] - const rows = selectHomeJumpBackInRows({ - hosts: [{ id: 'live' }, { id: 'offline' }, { id: 'failed' }], - hostStates: { live: 'connected', offline: 'disconnected', failed: 'connected' }, - worktreeInfo: { - live: info('live', blocked), - offline: info('offline', blocked), - failed: { ...info('failed', blocked), catalogUnavailable: true } - }, - resumeCard: null - }) - expect(rows.map((entry) => entry.hostId)).toEqual(['live']) - }) - - it('adds the last-opened workspace after the agents, unless it is already listed', () => { - const resumeWorktree = row('resume', {}) - const base = { - hosts: [{ id: 'host' }], - hostStates: { host: 'connected' as const } - } - const appended = selectHomeJumpBackInRows({ - ...base, - worktreeInfo: { host: info('host', [row('blocked', { sidebarStatus: 'permission' })]) }, - resumeCard: { hostId: 'host', worktree: resumeWorktree, actionable: true } - }) - expect(appended.map((entry) => [entry.worktree.worktreeId, entry.lastOpened])).toEqual([ - ['blocked', false], - ['resume', true] - ]) - - const deduped = selectHomeJumpBackInRows({ - ...base, - worktreeInfo: { host: info('host', [row('resume', { sidebarStatus: 'working' })]) }, - resumeCard: { hostId: 'host', worktree: resumeWorktree, actionable: true } - }) - expect(deduped.map((entry) => [entry.worktree.worktreeId, entry.lastOpened])).toEqual([ - ['resume', false] - ]) - }) - - it('names a row after the newest live top-level conversation in the dot state, else none', () => { - vi.useFakeTimers({ now: NOW }) - const rows = selectHomeAttentionWorktrees([ - row('blocked', { - sidebarStatus: 'permission', - agents: [ - agent('older', { - state: 'waiting', - conversationName: 'Older question', - updatedAt: NOW - 9 - }), - agent('newer', { state: 'blocked', conversationName: 'Fix login', updatedAt: NOW - 5 }), - agent('running', { state: 'working', conversationName: 'Refactor', updatedAt: NOW }), - agent('worker', { - parentPaneKey: 'running', - state: 'waiting', - conversationName: 'Worker', - updatedAt: NOW - }) - ] - }), - row('unnamed', { - sidebarStatus: 'working', - agents: [agent('a', { state: 'working' })] - }), - row('stale', { - sidebarStatus: 'working', - agents: [ - agent('s', { - state: 'working', - conversationName: 'Old task', - updatedAt: NOW - 31 * 60_000 - }) - ] - }), - row('old-host', { sidebarStatus: 'done', unread: true }) - ]) - expect( - rows.map((worktree) => [worktree.worktreeId, worktree.conversationName, worktree.paneKey]) - ).toEqual([ - ['blocked', 'Fix login', 'newer'], - ['old-host', undefined, undefined], - ['unnamed', undefined, undefined], - ['stale', undefined, undefined] - ]) - }) -}) diff --git a/mobile/src/worktree/home-jump-back-in.ts b/mobile/src/worktree/home-jump-back-in.ts deleted file mode 100644 index 446d6baaa17..00000000000 --- a/mobile/src/worktree/home-jump-back-in.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { isAgentStatusFresh } from '../../../src/shared/agent-status/contracts/agent-status-freshness' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { - applyAgentPaneActivityFlags, - createAgentPaneActivityFlags, - rankWorktreeStatus, - type WorktreeStatus -} from '../../../src/shared/worktree-status-rollup' -import type { ConnectionState } from '../transport/connection/connection-state' -import type { HomeResumeCard } from './home-resume-card' -import type { - HomeAttentionWorktree, - HomeWorktreeSummary, - HostWorktreeInfo -} from './home-worktree-info' -import { buildAgentRowLineageTree } from './agent-row-lineage' -import { getWorktreeDotStatus } from './workspace-list-ordering' - -// Feed shows the first few and "Show all" the rest; the bound keeps a busy desktop's list small. -const ATTENTION_ROWS_PER_HOST = 25 -const ATTENTION_ROWS_SHOWN = 25 - -/** Agents blocked on the user: they rank first, badge the Feed tab and are counted per desktop. */ -export function homeAgentNeedsYou(dotStatus: WorktreeStatus): boolean { - return dotStatus === 'permission' || dotStatus === 'failed' -} - -// Lower comes first: agents blocked on the user, then finished work they haven't seen, then running work. -function attentionRank(dotStatus: WorktreeStatus, unread: boolean): number | null { - if (homeAgentNeedsYou(dotStatus)) { - return 0 - } - if (dotStatus === 'done' && unread) { - return 1 - } - if (dotStatus === 'working' || dotStatus === 'monitoring') { - return 2 - } - return null -} - -function byRankThenRecent( - a: { rank: number; lastOutputAt?: number }, - b: { rank: number; lastOutputAt?: number } -): number { - return a.rank - b.rank || (b.lastOutputAt ?? 0) - (a.lastOutputAt ?? 0) -} - -function agentDotStatus(agent: RuntimeWorktreeAgentRow): WorktreeStatus { - const flags = createAgentPaneActivityFlags() - applyAgentPaneActivityFlags(flags, agent) - return rankWorktreeStatus('inactive', flags) -} - -// The newest top-level agent the host counted in the dot's state names the row; a nameless one keeps the workspace title. -function conversationBehindDot( - agents: readonly RuntimeWorktreeAgentRow[] | undefined, - dotStatus: WorktreeStatus, - now: number -): Pick { - let newest: RuntimeWorktreeAgentRow | undefined - for (const agent of buildAgentRowLineageTree(agents ?? []).rootRows) { - if ( - isAgentStatusFresh(agent, now) && - agentDotStatus(agent) === dotStatus && - (!newest || agent.updatedAt > newest.updatedAt) - ) { - newest = agent - } - } - const conversationName = newest?.conversationName?.trim() - return newest && conversationName ? { conversationName, paneKey: newest.paneKey } : {} -} - -/** The rows of one desktop's list that "Jump back in" may show, using the workspace list's dot status. */ -export function selectHomeAttentionWorktrees( - rows: readonly HomeWorktreeSummary[] -): HomeAttentionWorktree[] { - const now = Date.now() - const ranked: (HomeAttentionWorktree & Pick & { rank: number })[] = - [] - for (const row of rows) { - if (row.isArchived === true) { - continue - } - const dotStatus = getWorktreeDotStatus(row) - const rank = attentionRank(dotStatus, row.unread === true) - if (rank === null) { - continue - } - ranked.push({ - rank, - dotStatus, - worktreeId: row.worktreeId, - repo: row.repo, - branch: row.branch, - displayName: row.displayName, - lastOutputAt: typeof row.lastOutputAt === 'number' ? row.lastOutputAt : undefined, - workingMode: row.workingMode, - agents: row.agents - }) - } - return ranked - .sort(byRankThenRecent) - .slice(0, ATTENTION_ROWS_PER_HOST) - .map(({ rank: _rank, agents, ...worktree }) => ({ - ...worktree, - ...conversationBehindDot(agents, worktree.dotStatus, now) - })) -} - -export type HomeJumpBackInRow = Readonly<{ - hostId: string - worktree: HomeAttentionWorktree - /** The resume target rather than an agent that needs the user. */ - lastOpened: boolean - actionable: boolean -}> - -export function selectHomeJumpBackInRows(input: { - hosts: readonly { id: string }[] - hostStates: Readonly> - worktreeInfo: Readonly> - resumeCard: HomeResumeCard | null -}): HomeJumpBackInRow[] { - const candidates: (HomeJumpBackInRow & { rank: number; lastOutputAt?: number })[] = [] - for (const host of input.hosts) { - const info = input.worktreeInfo[host.id] - // Agent states are shown only from a connected desktop's list read this session. - if (input.hostStates[host.id] !== 'connected' || !info?.attention || info.catalogUnavailable) { - continue - } - for (const worktree of info.attention) { - candidates.push({ - hostId: host.id, - worktree, - lastOpened: false, - actionable: true, - rank: attentionRank(worktree.dotStatus, true) ?? 2, - lastOutputAt: worktree.lastOutputAt - }) - } - } - const rows: HomeJumpBackInRow[] = candidates - .sort(byRankThenRecent) - .slice(0, ATTENTION_ROWS_SHOWN) - .map(({ rank: _rank, lastOutputAt: _lastOutputAt, ...row }) => row) - const resume = input.resumeCard - if ( - resume && - !rows.some( - (row) => - row.hostId === resume.hostId && row.worktree.worktreeId === resume.worktree.worktreeId - ) - ) { - rows.push({ - hostId: resume.hostId, - worktree: { - worktreeId: resume.worktree.worktreeId, - repo: resume.worktree.repo, - branch: resume.worktree.branch, - displayName: resume.worktree.displayName, - lastOutputAt: resume.worktree.lastOutputAt, - dotStatus: 'inactive' - }, - lastOpened: true, - actionable: resume.actionable - }) - } - return rows -} diff --git a/mobile/src/worktree/home-resume-card.test.ts b/mobile/src/worktree/home-resume-card.test.ts deleted file mode 100644 index 65f9bd4c7bf..00000000000 --- a/mobile/src/worktree/home-resume-card.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - isResumeTargetConfirmedMissing, - selectHomeResumeCard, - type HomeResumeCardInput -} from './home-resume-card' -import type { HomeWorktreeSummary, HostWorktreeInfo } from './home-worktree-info' - -function worktree(worktreeId: string): HomeWorktreeSummary { - return { - worktreeId, - repo: 'orca', - branch: 'main', - displayName: worktreeId, - liveTerminalCount: 0 - } -} - -function info(hostId: string, lastActive: HomeWorktreeSummary | null): HostWorktreeInfo { - return { hostId, totalWorktrees: 1, activeCount: 0, lastActiveWorktree: lastActive } -} - -function input(overrides: Partial = {}): HomeResumeCardInput { - return { - hosts: [{ id: 'host-1' }], - hostStates: {}, - worktreeInfo: { 'host-1': info('host-1', worktree('repo::/tmp/wt')) }, - lastVisited: null, - cachedWorktrees: () => null, - ...overrides - } -} - -describe('home resume card', () => { - it('reserves the slot from snapshot data while the host is still connecting', () => { - const connecting = selectHomeResumeCard(input({ hostStates: { 'host-1': 'connecting' } })) - - expect(connecting).toEqual({ - hostId: 'host-1', - worktree: worktree('repo::/tmp/wt'), - actionable: false - }) - }) - - it('keeps the same card in place once the host connects, only enabling it', () => { - const before = selectHomeResumeCard(input({ hostStates: { 'host-1': 'connecting' } })) - const after = selectHomeResumeCard(input({ hostStates: { 'host-1': 'connected' } })) - - expect(after?.hostId).toBe(before?.hostId) - expect(after?.worktree.worktreeId).toBe(before?.worktree.worktreeId) - expect(after?.actionable).toBe(true) - }) - - it('leaves Tasks first when no host has resume history at all', () => { - expect( - selectHomeResumeCard(input({ worktreeInfo: { 'host-1': info('host-1', null) } })) - ).toBeNull() - }) - - it('prefers the worktree last opened on this device, enabled with its host', () => { - const visited = worktree('repo::/tmp/visited') - const fromLastVisited = (state: 'connecting' | 'connected') => - selectHomeResumeCard( - input({ - hostStates: { 'host-1': state }, - lastVisited: { hostId: 'host-1', worktreeId: visited.worktreeId }, - cachedWorktrees: (hostId) => (hostId === 'host-1' ? [visited] : null) - }) - ) - - expect(fromLastVisited('connecting')).toEqual({ - hostId: 'host-1', - worktree: visited, - actionable: false - }) - expect(fromLastVisited('connected')?.actionable).toBe(true) - }) - - it('prefers a connected host over an unconnected one holding older snapshot data', () => { - const card = selectHomeResumeCard( - input({ - hosts: [{ id: 'host-1' }, { id: 'host-2' }], - hostStates: { 'host-1': 'connecting', 'host-2': 'connected' }, - worktreeInfo: { - 'host-1': info('host-1', worktree('repo::/tmp/one')), - 'host-2': info('host-2', worktree('repo::/tmp/two')) - } - }) - ) - - expect(card).toEqual({ - hostId: 'host-2', - worktree: worktree('repo::/tmp/two'), - actionable: true - }) - }) - - it('gives a connected host precedence over an offline last-visited worktree', () => { - const visited = worktree('repo::/tmp/visited') - const card = selectHomeResumeCard( - input({ - hosts: [{ id: 'host-1' }, { id: 'host-2' }], - hostStates: { 'host-1': 'disconnected', 'host-2': 'connected' }, - worktreeInfo: { 'host-2': info('host-2', worktree('repo::/tmp/two')) }, - lastVisited: { hostId: 'host-1', worktreeId: visited.worktreeId }, - cachedWorktrees: (hostId) => (hostId === 'host-1' ? [visited] : null) - }) - ) - - expect(card).toEqual({ - hostId: 'host-2', - worktree: worktree('repo::/tmp/two'), - actionable: true - }) - }) -}) - -// A persisted Resume target may have been deleted while offline; require host evidence before confirming it missing (F7). -describe('isResumeTargetConfirmedMissing', () => { - const card = { - hostId: 'host-1', - worktree: worktree('repo::/tmp/wt'), - actionable: true - } as const - - it('confirms a target the host listed without', () => { - expect(isResumeTargetConfirmedMissing(card, [{ worktreeId: 'repo::/tmp/other' }])).toBe(true) - }) - - it('clears a target present in the listing', () => { - expect( - isResumeTargetConfirmedMissing(card, [ - { worktreeId: 'repo::/tmp/other' }, - { worktreeId: 'repo::/tmp/wt' } - ]) - ).toBe(false) - }) - - // An unproven catalog cannot establish deletion. - it('never confirms without a proven catalog', () => { - expect(isResumeTargetConfirmedMissing(card, null)).toBe(false) - }) - - it('confirms the target when the host proves it has no workspaces at all', () => { - expect(isResumeTargetConfirmedMissing(card, [])).toBe(true) - }) - - it('exempts synthetic routes the catalog can never list', () => { - const folder = { ...card, worktree: worktree('folder:/Users/x/dir') } - const floating = { ...card, worktree: worktree('global-floating-terminal') } - - expect(isResumeTargetConfirmedMissing(folder, [])).toBe(false) - expect(isResumeTargetConfirmedMissing(floating, [])).toBe(false) - }) -}) diff --git a/mobile/src/worktree/home-resume-card.ts b/mobile/src/worktree/home-resume-card.ts deleted file mode 100644 index e89c5254353..00000000000 --- a/mobile/src/worktree/home-resume-card.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { isSyntheticWorkspaceRoute } from '../session/synthetic-workspace-route' -import type { ConnectionState } from '../transport/connection/connection-state' -import type { HomeWorktreeSummary, HostWorktreeInfo } from './home-worktree-info' - -// Reserve Resume’s slot from persisted history before connection so Tasks cannot move under the user’s thumb. - -export type HomeResumeCard = Readonly<{ - hostId: string - worktree: HomeWorktreeSummary - actionable: boolean -}> - -export type HomeResumeCardInput = Readonly<{ - /** Home's sorted hosts — order decides which snapshot wins when several have history. */ - hosts: readonly { id: string }[] - hostStates: Readonly> - worktreeInfo: Readonly> - lastVisited: Readonly<{ hostId: string; worktreeId: string }> | null - cachedWorktrees: (hostId: string) => HomeWorktreeSummary[] | null -}> - -function lastVisitedCard({ - lastVisited, - cachedWorktrees, - hostStates -}: HomeResumeCardInput): HomeResumeCard | null { - if (!lastVisited) { - return null - } - const match = cachedWorktrees(lastVisited.hostId)?.find( - (worktree) => worktree.worktreeId === lastVisited.worktreeId - ) - if (!match) { - return null - } - return { - hostId: lastVisited.hostId, - worktree: match, - actionable: hostStates[lastVisited.hostId] === 'connected' - } -} - -function hostHistoryCard( - { hosts, hostStates, worktreeInfo }: HomeResumeCardInput, - connectedOnly: boolean -): HomeResumeCard | null { - for (const host of hosts) { - const worktree = worktreeInfo[host.id]?.lastActiveWorktree - if (!worktree) { - continue - } - const actionable = hostStates[host.id] === 'connected' - if (actionable || !connectedOnly) { - return { hostId: host.id, worktree, actionable } - } - } - return null -} - -// Only a proven catalog can establish deletion; cold/loading snapshots leave navigation to the session’s later check. -export function isResumeTargetConfirmedMissing( - card: Readonly<{ worktree: Readonly<{ worktreeId: string }> }>, - provenWorktrees: readonly unknown[] | null -): boolean { - if (!provenWorktrees || isSyntheticWorkspaceRoute(card.worktree.worktreeId)) { - return false - } - return !provenWorktrees.some( - (worktree) => - typeof worktree === 'object' && - worktree !== null && - 'worktreeId' in worktree && - worktree.worktreeId === card.worktree.worktreeId - ) -} - -export function selectHomeResumeCard(input: HomeResumeCardInput): HomeResumeCard | null { - const visited = lastVisitedCard(input) - if (visited?.actionable) { - return visited - } - const connected = hostHistoryCard(input, true) - if (connected) { - return connected - } - return visited ?? hostHistoryCard(input, false) -} diff --git a/mobile/src/worktree/home-worktree-info.ts b/mobile/src/worktree/home-worktree-info.ts index e0630913958..d030f7b8471 100644 --- a/mobile/src/worktree/home-worktree-info.ts +++ b/mobile/src/worktree/home-worktree-info.ts @@ -1,6 +1,5 @@ import type { AgentWorkingMode } from '../../../src/shared/agent-status/contracts/agent-status-types' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import type { WorktreeStatus } from '../../../src/shared/worktree-status-rollup' export type HomeWorktreeSummary = { worktreeId: string @@ -19,23 +18,24 @@ export type HomeWorktreeSummary = { agents?: RuntimeWorktreeAgentRow[] } -/** A workspace whose agents Home surfaces under "Jump back in", with the list's dot status. */ -export type HomeAttentionWorktree = Pick< - HomeWorktreeSummary, - 'worktreeId' | 'repo' | 'branch' | 'displayName' | 'lastOutputAt' | 'workingMode' -> & { - dotStatus: WorktreeStatus - /** The conversation behind the dot and its pane; older hosts send no names. */ - conversationName?: string - paneKey?: string -} +/** One agent on a desktop, with the workspace it runs in. */ +export type HomeAgentEntry = Readonly<{ + worktreeId: string + workspaceName: string + repo: string + branch: string + agent: RuntimeWorktreeAgentRow +}> export type HostWorktreeInfo = { hostId: string totalWorktrees: number activeCount: number lastActiveWorktree: HomeWorktreeSummary | null - attention?: HomeAttentionWorktree[] + /** Every agent from this connection's latest list read. */ + agents?: HomeAgentEntry[] + /** The agents of a read the connection has since lost: what they were, not what they are. */ + lastSeenAgents?: HomeAgentEntry[] catalogUnavailable?: boolean // The counts are the last proven ones, kept across a failed refresh. staleCounts?: boolean @@ -43,15 +43,38 @@ export type HostWorktreeInfo = { countsProvenAt?: number } -/** Agent states are live facts; a saved copy or a dropped connection can't vouch for them. */ +export function homeAgentEntries(worktrees: readonly HomeWorktreeSummary[]): HomeAgentEntry[] { + return worktrees.flatMap((worktree) => + Array.isArray(worktree.agents) + ? worktree.agents.map((agent) => ({ + worktreeId: worktree.worktreeId, + workspaceName: worktree.displayName || worktree.repo, + repo: worktree.repo, + branch: worktree.branch, + agent + })) + : [] + ) +} + +/** Agent states are live facts; a saved copy can't vouch for them, even as last seen. */ export function withoutHomeAgentStates(info: HostWorktreeInfo): HostWorktreeInfo { - if (!info.attention) { + if (!info.agents && !info.lastSeenAgents) { return info } - const { attention: _attention, ...rest } = info + const { agents: _agents, lastSeenAgents: _lastSeenAgents, ...rest } = info return rest } +/** A dropped connection keeps its agents only as last seen; the reconnect read makes them live again. */ +export function withLastSeenHomeAgents(info: HostWorktreeInfo): HostWorktreeInfo { + if (!info.agents) { + return info + } + const { agents, ...rest } = info + return { ...rest, lastSeenAgents: agents } +} + export function markHomeWorktreeCatalogUnavailable( current: HostWorktreeInfo | undefined, hostId: string diff --git a/src/cli/handlers/environment.ts b/src/cli/handlers/environment.ts index 4d3383bf352..cea32095c3b 100644 --- a/src/cli/handlers/environment.ts +++ b/src/cli/handlers/environment.ts @@ -24,7 +24,7 @@ import { import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection' import { redactRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import { addEnvironmentFromPairingCode, removeEnvironment, diff --git a/src/cli/handlers/managed-server.ts b/src/cli/handlers/managed-server.ts index 7011b8c59c4..579239d02ea 100644 --- a/src/cli/handlers/managed-server.ts +++ b/src/cli/handlers/managed-server.ts @@ -9,7 +9,7 @@ import type { } from '../../shared/orcad-managed-runtime' import { ORCAD_RECOVERY_CHANGED_STATE_CODE } from '../../shared/orcad-managed-runtime' import { MANAGED_SERVER_RUNTIME_CAPABILITY } from '../../shared/protocol-version' -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import type { CommandHandler, HandlerContext } from '../dispatch' import { getRequiredStringFlag } from '../flags' import { printResult } from '../format' diff --git a/src/main/acp/protocol/acp-session-call.ts b/src/main/acp/protocol/acp-session-call.ts index b1b3eb4fe20..3057ddd33e6 100644 --- a/src/main/acp/protocol/acp-session-call.ts +++ b/src/main/acp/protocol/acp-session-call.ts @@ -6,7 +6,6 @@ import { } from '../transport/acp-errors' import type { AcpJsonRpcPeer } from '../transport/acp-json-rpc-peer' -import { acpStepBound } from '../transport/acp-peer-limits' export function callAcpSession( peer: AcpJsonRpcPeer, @@ -17,7 +16,7 @@ export function callAcpSession( received?: (response: T) => void ): Promise { return peer.request(method, params, { - ...acpStepBound(method), + timeoutMs: null, settle: (response) => { if ('error' in response) { const error = response.error diff --git a/src/main/acp/protocol/acp-session-lifecycle.test.ts b/src/main/acp/protocol/acp-session-lifecycle.test.ts index c80e9733378..e83e321f4ec 100644 --- a/src/main/acp/protocol/acp-session-lifecycle.test.ts +++ b/src/main/acp/protocol/acp-session-lifecycle.test.ts @@ -101,6 +101,44 @@ describe('ACP caller-owned waits', () => { await expect(pending).resolves.toEqual({ stopReason: 'end_turn' }) }) + it.each([ + { kind: 'new', expected: { kind: 'new', sessionId: 'session-1' } }, + { kind: 'load', expected: { kind: 'load', sessionId: 'saved-session' } }, + { kind: 'resume', expected: { kind: 'resume', sessionId: 'saved-session' } } + ] as const)( + 'opens a slow $kind session on its real answers, regardless of the peer default', + async ({ kind, expected }) => { + vi.useFakeTimers() + const { agent, runtime } = fixture({ peer: { requestTimeoutMs: 20 } }) + agent.on('initialize', (frame) => { + setTimeout( + () => + agent.reply(frame, { + protocolVersion: 1, + agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } } + }), + 75_000 + ) + }) + agent.on(`session/${kind}`, (frame) => { + setTimeout( + () => agent.reply(frame, kind === 'new' ? { sessionId: 'session-1' } : {}), + 310_000 + ) + }) + const started = expect( + runtime.start({ + ...startOptions, + ...(kind === 'new' ? {} : { sessionId: 'saved-session', resumePreference: kind }) + }) + ).resolves.toMatchObject(expected) + await vi.advanceTimersByTimeAsync(385_000) + await started + agent.on('session/prompt', (frame) => agent.reply(frame, { stopReason: 'end_turn' })) + await expect(runtime.prompt([...prompt])).resolves.toEqual({ stopReason: 'end_turn' }) + } + ) + it('keeps a handler answer that finishes saving after its owner withdraws requests', async () => { const withdrawal = new AbortController() const planEntered = deferred() diff --git a/src/main/acp/transport/acp-peer-limits.ts b/src/main/acp/transport/acp-peer-limits.ts index e148bff6019..29b555721cc 100644 --- a/src/main/acp/transport/acp-peer-limits.ts +++ b/src/main/acp/transport/acp-peer-limits.ts @@ -40,16 +40,3 @@ export function requestTimeout(value: number | null | undefined): number | null } return value } - -// Bound startup steps separately; prompts remain unbounded. -const ACP_START_STEP_TIMEOUT_MS: Readonly>> = { - initialize: 60_000, - 'session/new': 300_000, - 'session/load': 300_000, - 'session/resume': 300_000, - 'session/fork': 300_000 -} - -export function acpStepBound(method: string): { timeoutMs: number | null } { - return { timeoutMs: ACP_START_STEP_TIMEOUT_MS[method] ?? null } -} diff --git a/src/main/ssh/ssh-agent-hook-interrupt-reconciliation.ts b/src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts similarity index 87% rename from src/main/ssh/ssh-agent-hook-interrupt-reconciliation.ts rename to src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts index adecea62738..6413152e5af 100644 --- a/src/main/ssh/ssh-agent-hook-interrupt-reconciliation.ts +++ b/src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts @@ -1,5 +1,5 @@ -import type { AgentHookServer } from '../agent-hooks/server' -import type { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import type { AgentHookServer } from './server' +import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' import { AGENT_HOOK_INFER_INTERRUPT_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-interrupt-reconciliation' /** A host revision proves this relay supports the command; older relays keep the legacy path. */ diff --git a/src/main/agent-hooks/wsl-guest-plugin-install.test.ts b/src/main/agent-hooks/wsl-guest-plugin-install.test.ts index 9f0ab1ef078..3d6fdf68d1c 100644 --- a/src/main/agent-hooks/wsl-guest-plugin-install.test.ts +++ b/src/main/agent-hooks/wsl-guest-plugin-install.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' -import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' function fakeMux( request: () => Promise, diff --git a/src/main/agent-hooks/wsl-guest-plugin-install.ts b/src/main/agent-hooks/wsl-guest-plugin-install.ts index 65a6187cecb..a9da7757ace 100644 --- a/src/main/agent-hooks/wsl-guest-plugin-install.ts +++ b/src/main/agent-hooks/wsl-guest-plugin-install.ts @@ -1,4 +1,4 @@ -import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' import { isRecord } from '../../shared/agent-status/child-work/agent-status-child-work-value-guards' import { selectOpenCodePluginSources } from './opencode-plugin-settings' diff --git a/src/main/agent-hooks/wsl-hook-fs-adapter.ts b/src/main/agent-hooks/wsl-hook-fs-adapter.ts index 9966adc0d39..103c91aeb55 100644 --- a/src/main/agent-hooks/wsl-hook-fs-adapter.ts +++ b/src/main/agent-hooks/wsl-hook-fs-adapter.ts @@ -7,7 +7,7 @@ import { readManagedHookDetectionResult, type ManagedHookDetectionSettings } from './managed-hook-detection-commands' -import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' import { WSL_HOOK_FS_METHODS, type WslFsResult } from '../../shared/wsl-hook-relay-contract' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' diff --git a/src/main/agent-hooks/wsl-hook-relay-deps.ts b/src/main/agent-hooks/wsl-hook-relay-deps.ts index 8d4a0ff741d..9a5f21fcce6 100644 --- a/src/main/agent-hooks/wsl-hook-relay-deps.ts +++ b/src/main/agent-hooks/wsl-hook-relay-deps.ts @@ -1,5 +1,5 @@ import { CLAUDE_AGENT_VIEW_MOD_SOURCE } from '../claude/agent-view/agent-view-mod-source' -import { bindRemoteClaudeInterruptReconciliation } from '../ssh/ssh-agent-hook-interrupt-reconciliation' +import { bindRemoteClaudeInterruptReconciliation } from './ssh-agent-hook-interrupt-reconciliation' import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' diff --git a/src/main/agent-hooks/wsl-hook-relay-guest-install.ts b/src/main/agent-hooks/wsl-hook-relay-guest-install.ts index b41aa9b9e08..8240e4b1876 100644 --- a/src/main/agent-hooks/wsl-hook-relay-guest-install.ts +++ b/src/main/agent-hooks/wsl-hook-relay-guest-install.ts @@ -1,9 +1,14 @@ +import { + WSL_HOOK_FS_METHODS, + wslHookRelayEndpointFilePath +} from '../../shared/wsl-hook-relay-contract' +import type { WslRelayDistroState } from './wsl-hook-relay-state' import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' import type { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' import { installWslGuestHooks } from './wsl-hook-fs-adapter' import { REINSTALL_MIN_INTERVAL_MS, type WslHookRelayManagerDeps } from './wsl-hook-relay-deps' -import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' import { openCodePluginSettingsKey } from './opencode-plugin-settings' import type { PluginSources } from '../../wsl-guest/plugin-overlay' @@ -164,3 +169,28 @@ export async function maybeRerunWslRelayGuestInstall( } } } + +export async function installWslRelayGuestFromHome( + deps: GuestInstallDeps, + state: WslRelayDistroState, + mux: SshChannelMultiplexer, + instanceKey: string +): Promise { + const homeResult = (await mux.request(WSL_HOOK_FS_METHODS.home)) as { + ok?: boolean + home?: string + portFallback?: boolean + boundPort?: number + } + if (homeResult?.ok !== true || typeof homeResult.home !== 'string') { + throw new Error(`relay for '${state.distro}' returned no home dir`) + } + if (homeResult.portFallback === true) { + deps.warn( + `[agent-hooks] WSL hook relay (${state.distro}): preferred port occupied in guest; bound ${homeResult.boundPort ?? 'unknown'} (endpoint-file re-coordination)` + ) + } + state.guestHome = homeResult.home + state.guestEndpointFilePath = wslHookRelayEndpointFilePath(homeResult.home, instanceKey) + await runWslRelayGuestInstall(deps, state, mux, homeResult.home) +} diff --git a/src/main/agent-hooks/wsl-hook-relay-launch.ts b/src/main/agent-hooks/wsl-hook-relay-launch.ts index 428d595afa9..93a65618f8f 100644 --- a/src/main/agent-hooks/wsl-hook-relay-launch.ts +++ b/src/main/agent-hooks/wsl-hook-relay-launch.ts @@ -2,11 +2,11 @@ import type { PipedChildProcess } from '@orca/process-host/process-spec' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { spawnProcess } from '@orca/process-host' -import { relayBundleCandidates } from '../ssh/relay-bundle-paths' +import { relayBundleCandidates } from '../wsl/execution/relay-bundle-paths' import { withWslGuestLauncherRevision } from '../wsl/execution/wsl-guest-launcher-revision' import { orcadPosixNodeRuntimeGlobs } from '../managed-server/install/orcad-node-runtime-globs' -import type { MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' import { MAX_STARTUP_BUFFER_BYTES, type waitForWslRelaySentinel, diff --git a/src/main/agent-hooks/wsl-hook-relay-link.ts b/src/main/agent-hooks/wsl-hook-relay-link.ts index e09057cd0d0..2212d4e776f 100644 --- a/src/main/agent-hooks/wsl-hook-relay-link.ts +++ b/src/main/agent-hooks/wsl-hook-relay-link.ts @@ -1,6 +1,6 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' import { AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_PANE_ROOT_METHOD diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts index 16dc0c95898..1622fad6e1a 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts +++ b/src/main/agent-hooks/wsl-hook-relay-manager.test.ts @@ -6,7 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { RelayDispatcher } from '../../wsl-guest/dispatcher' import { registerWslHookFsHandlers } from '../../wsl-guest/wsl-hook-fs-bridge' -import { SshChannelMultiplexer, type MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' import { createWslHookSftpAdapter, installWslGuestHooks } from './wsl-hook-fs-adapter' import { installRemoteManagedAgentHooks, diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.ts b/src/main/agent-hooks/wsl-hook-relay-manager.ts index 98dc4e81cb0..112baed1ec8 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.ts +++ b/src/main/agent-hooks/wsl-hook-relay-manager.ts @@ -1,6 +1,6 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { - runWslRelayGuestInstall, + installWslRelayGuestFromHome, maybeRerunWslRelayGuestInstall } from './wsl-hook-relay-guest-install' import { buildWslRelaySpawnEnv, launchWslRelayWithInstall } from './wsl-hook-relay-launch' @@ -17,13 +17,10 @@ import { import { wireWslRelayLink } from './wsl-hook-relay-link' import type { WslRelayRecovery } from './wsl-hook-relay-recovery' import { wslHookRelayStateKey } from './wsl-hook-relay-state-key' -import { SshChannelMultiplexer, type MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' import { AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { - sanitizeWslHookInstanceKey, - WSL_HOOK_FS_METHODS, - wslHookRelayEndpointFilePath -} from '../../shared/wsl-hook-relay-contract' +import { sanitizeWslHookInstanceKey } from '../../shared/wsl-hook-relay-contract' import { recordManagedWslCodexHome, wslRuntimeHomePathsEqual @@ -260,23 +257,7 @@ export class WslHookRelayManager { }) } }) - const homeResult = (await mux.request(WSL_HOOK_FS_METHODS.home)) as { - ok?: boolean - home?: string - portFallback?: boolean - boundPort?: number - } - if (homeResult?.ok !== true || typeof homeResult.home !== 'string') { - throw new Error(`relay for '${state.distro}' returned no home dir`) - } - if (homeResult.portFallback === true) { - this.deps.warn( - `[agent-hooks] WSL hook relay (${state.distro}): preferred port occupied in guest; bound ${homeResult.boundPort ?? 'unknown'} (endpoint-file re-coordination)` - ) - } - state.guestHome = homeResult.home - state.guestEndpointFilePath = wslHookRelayEndpointFilePath(homeResult.home, instanceKey) - await runWslRelayGuestInstall(this.deps, state, mux, homeResult.home) + await installWslRelayGuestFromHome(this.deps, state, mux, instanceKey) if (state.phase === 'failed' || state.mux !== mux) { return } diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts b/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts index 07bb6ff429c..ab57642fd8f 100644 --- a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts +++ b/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { afterEach, describe, expect, it, vi } from 'vitest' -import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/remote-exec/remote-frame-protocol' +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/protocol/relay-handshake' import { MAX_STARTUP_BUFFER_BYTES, waitForWslRelaySentinel, diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.ts b/src/main/agent-hooks/wsl-hook-relay-sentinel.ts index c1f30958d4a..f70b5725281 100644 --- a/src/main/agent-hooks/wsl-hook-relay-sentinel.ts +++ b/src/main/agent-hooks/wsl-hook-relay-sentinel.ts @@ -1,7 +1,7 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/remote-exec/remote-frame-protocol' -import type { MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/protocol/relay-handshake' +import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' export const MAX_STARTUP_BUFFER_BYTES = 64 * 1024 diff --git a/src/main/agent-hooks/wsl-hook-relay-state.ts b/src/main/agent-hooks/wsl-hook-relay-state.ts index 93e6cc47825..3fc4bbbe268 100644 --- a/src/main/agent-hooks/wsl-hook-relay-state.ts +++ b/src/main/agent-hooks/wsl-hook-relay-state.ts @@ -1,4 +1,4 @@ -import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' export type WslRelayDistroState = { distro: string diff --git a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts b/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts index 6d5ec0e714e..bf93187c45e 100644 --- a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts +++ b/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts @@ -9,7 +9,7 @@ import { PluginOverlayManager } from '../../wsl-guest/plugin-overlay' import { createInstallPluginsHandler } from '../../wsl-guest/wsl-install-plugins-handler' import { WslHookRelayManager } from './wsl-hook-relay-manager' import { REINSTALL_MIN_INTERVAL_MS } from './wsl-hook-relay-deps' -import type { MultiplexerTransport } from '../ssh/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, diff --git a/src/main/agent-hooks/wsl-opencode-settings.test.ts b/src/main/agent-hooks/wsl-opencode-settings.test.ts index 006197316eb..227cd891012 100644 --- a/src/main/agent-hooks/wsl-opencode-settings.test.ts +++ b/src/main/agent-hooks/wsl-opencode-settings.test.ts @@ -6,7 +6,7 @@ import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' import { RelayDispatcher } from '../../wsl-guest/dispatcher' import { PluginOverlayManager } from '../../wsl-guest/plugin-overlay' import { createInstallPluginsHandler } from '../../wsl-guest/wsl-install-plugins-handler' -import { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' +import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' import { diff --git a/src/main/ai-vault-search/session-search-retention-delete.test.ts b/src/main/ai-vault-search/session-search-retention-delete.test.ts index 2cf168ad3a5..8397e5d0e60 100644 --- a/src/main/ai-vault-search/session-search-retention-delete.test.ts +++ b/src/main/ai-vault-search/session-search-retention-delete.test.ts @@ -1,9 +1,6 @@ import { expect, it } from 'vitest' import type SyncDatabase from '../sqlite/sync-database' -import { - deleteExpiredSearchFiles, - RETENTION_DELETE_ROWS_PER_STEP -} from './session-search-retention-delete' +import { deleteExpiredSearchFiles } from './session-search-retention-delete' import { openSessionSearchIndexFile } from './session-search-index-test-fixture' import { SessionSearchStore } from './session-search-store' @@ -44,34 +41,6 @@ function count(db: SyncDatabase, table: string): number { return (db.prepare(`SELECT count(*) AS n FROM ${table}`).get() as { n: number }).n } -it('hides an expiring session at once, then reclaims its rows in bounded steps', async () => { - const index = await openSessionSearchIndexFile('ss-retention-yield') - seed(index.db, 1, 1025, 1) - seed(index.db, 2, 1, 200) - let previous = 1025 - const steps: number[] = [] - try { - await deleteExpiredSearchFiles( - index.db, - 100, - () => false, - async () => { - const left = count(index.db, 'messages WHERE session_row_id=1') - steps.push(previous - left) - previous = left - // Expired sessions must be invisible before any message batch is reclaimed. - expect(visibleSessionIds(index.db)).toEqual(['2']) - } - ) - // The file transaction yields before the first message-deletion batch. - expect(steps).toEqual([0, RETENTION_DELETE_ROWS_PER_STEP, 256, 256, 256, 1]) - expect(count(index.db, 'messages_fts')).toBe(1) - expect(count(index.db, 'sessions')).toBe(1) - } finally { - await index.close() - } -}) - it('finishes an interrupted deletion after reopening', async () => { const index = await openSessionSearchIndexFile('ss-retention-resume') let store = new SessionSearchStore(index.path) diff --git a/src/main/ai-vault-search/session-search-retention-delete.ts b/src/main/ai-vault-search/session-search-retention-delete.ts index 4956b5d1bfd..09222aa16a5 100644 --- a/src/main/ai-vault-search/session-search-retention-delete.ts +++ b/src/main/ai-vault-search/session-search-retention-delete.ts @@ -5,6 +5,8 @@ import { deleteSearchMessages } from './session-search-message-rows' export const RETENTION_DELETE_ROWS_PER_STEP = 256 // Reclaim freed pages incrementally to avoid a long vacuum after the purge. const RECLAIM_PAGES_PER_STEP = 2000 +// FTS merges free pages constantly and later writes reuse them; moving them each drain only churns the file. +const RECLAIM_FREE_PAGE_SHARE = 0.25 /** Hide expired sessions atomically, then reclaim their unreachable messages in bounded transactions. */ export async function deleteExpiredSearchFiles( @@ -64,12 +66,19 @@ export async function drainOrphanedMessages( db.exec('ROLLBACK') throw error } - db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) + reclaimFreePages(db) if (deleted < RETENTION_DELETE_ROWS_PER_STEP) { orphan = (nextOrphan.get() as { session_row_id: number } | undefined)?.session_row_id } await yieldStep() } // removeFile may free pages even when this drain has no orphaned messages. - db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) + reclaimFreePages(db) +} + +function reclaimFreePages(db: SyncDatabase): void { + const free = Number(db.pragma('freelist_count', { simple: true })) + if (free > Number(db.pragma('page_count', { simple: true })) * RECLAIM_FREE_PAGE_SHARE) { + db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) + } } diff --git a/src/main/ai-vault-search/session-search-schema.ts b/src/main/ai-vault-search/session-search-schema.ts index 4c5aa58acaf..5c8ec720068 100644 --- a/src/main/ai-vault-search/session-search-schema.ts +++ b/src/main/ai-vault-search/session-search-schema.ts @@ -79,6 +79,8 @@ export function openSessionSearchDatabase(path: string): SyncDatabase { 'index_incarnation', randomUUID() ) + // Each small commit adds an FTS segment; wider merges mean fewer levels rewriting it (#36666). + db.prepare("INSERT INTO messages_fts(messages_fts, rank) VALUES ('automerge', 8)").run() // Older Cursor rows omitted the file-time fallback; repair metadata without rereading transcripts. db.exec(` UPDATE sessions SET updated_at = ( diff --git a/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts b/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts index 2ad999b40fa..facf7c026e0 100644 --- a/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts +++ b/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts @@ -28,6 +28,36 @@ export function isClaudeProjectDirInScope( return false } +// Claude Code names a longer encoded path's bucket `-`; older versions kept the full name. +const CLAUDE_BUCKET_NAME_MAX_LENGTH = 200 + +/** Bucket-name prefixes for a scope, including the 200-character cut Claude Code makes for long paths. */ +export function claudeProjectBucketScopePrefixes(pathValue: string): string[] { + return encodeClaudeProjectPaths(pathValue).flatMap((encoded) => + encoded.length > CLAUDE_BUCKET_NAME_MAX_LENGTH + ? [encoded, encoded.slice(0, CLAUDE_BUCKET_NAME_MAX_LENGTH)] + : [encoded] + ) +} + +/** Like isClaudeProjectDirInScope, but a root (`-`, `C--`) keeps its separator, so it prefixes every bucket. */ +export function isClaudeProjectBucketInScope( + projectDirName: string, + scopePrefixes: ReadonlySet +): boolean { + for (const prefix of scopePrefixes) { + const isRoot = prefix === '-' || /^[A-Za-z]--$/.test(prefix) + if ( + isRoot + ? projectDirName.startsWith(prefix) + : isClaudeProjectDirInScope(projectDirName, [prefix]) + ) { + return true + } + } + return false +} + /** Transcripts sit in project buckets (depth 0); `/` folders below hold only subagent and tool output. */ export function isClaudeProjectBucketDirectory(_name: string, depth: number): boolean { return depth === 0 diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts b/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts index 16b01743099..b21d69cf8b6 100644 --- a/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts +++ b/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts @@ -33,7 +33,9 @@ vi.mock('../../../../native-chat/wsl-transcript-running-admission', () => ({ vi.mock('../../../../node-runtime/pinned-runtime-materializer', () => ({ materializeNodeRuntimeArchive: mocks.download })) -vi.mock('../../../../ssh/relay-bundle-paths', () => ({ relayBundleCandidates: mocks.bundles })) +vi.mock('../../../../wsl/execution/relay-bundle-paths', () => ({ + relayBundleCandidates: mocks.bundles +})) const home = String.raw`\\wsl.localhost\Ubuntu\home\ada` const success = (stdout: string) => ({ stdout, stderr: '', code: 0, timedOut: false }) diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.ts b/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.ts index 321467ebcf4..1ee40f4475c 100644 --- a/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.ts +++ b/src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.ts @@ -7,7 +7,7 @@ import type { ServerTarget } from '../../../../../shared/node-runtime-pin' import { OPENCODE_SQLITE_READER_FILENAME } from '../../../../../shared/remote-bundle-artifacts' import { parseWslUncPath, toWindowsWslUncPath } from '../../../../../shared/wsl-paths' import { NODE_SQLITE_READER_API_SOURCE } from '../../../../sqlite/node-sqlite-reader-api' -import { relayBundleCandidates } from '../../../../ssh/relay-bundle-paths' +import { relayBundleCandidates } from '../../../../wsl/execution/relay-bundle-paths' import { materializeNodeRuntimeArchive } from '../../../../node-runtime/pinned-runtime-materializer' import { probeLinuxLibc } from '../../../../node-runtime/linux-libc-probe' import { @@ -16,8 +16,8 @@ import { posixNodeRuntimeExecutable, probeRemoteNodeRuntimeCommand } from '../../../../managed-server/install/orcad-remote-node-runtime' -import { REMOTE_NODE_RUNTIME_READY } from '../../../../ssh/orcad-remote-node-runtime-report' -import { getRemoteHostPlatform } from '../../../../ssh/ssh-remote-platform' +import { REMOTE_NODE_RUNTIME_READY } from '../../../../managed-server/install/orcad-remote-node-runtime-report' +import { getRemoteHostPlatform } from '../../../../ssh/remote-host/ssh-remote-platform' import { runWslProcess, type WslSpec } from '../../../../wsl/execution/wsl-runner' import { describeWslProcessFailure } from '../../../../wsl/execution/wsl-process-failure' import { admitWslTranscriptPath } from '../../../../native-chat/wsl-transcript-running-admission' diff --git a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts index 0d514b81bd3..7a743a0b37b 100644 --- a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts +++ b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts @@ -122,15 +122,22 @@ async function writeSharedRootTranscripts(sessionsDir: string): Promise { describe('scanAiVaultSessions with overlapping Pi and OMP roots', () => { const sameFolder = (sessionsDir: string): string => sessionsDir + const parentFolder = (sessionsDir: string): string => join(sessionsDir, '..') it.each([ { layout: 'the same folder', piRoot: sameFolder, scope: {} }, // PI_CODING_AGENT_DIR=: Pi walks , OMP walks /sessions. - { layout: 'a parent folder', piRoot: (dir: string) => join(dir, '..'), scope: {} }, + { layout: 'a parent folder', piRoot: parentFolder, scope: {} }, // A one-row cap sends the rest through scope recovery: Pi's buckets and OMP's walk. { layout: 'the same folder for a workspace', piRoot: sameFolder, scope: { scopePaths: ['/repo/app'], limit: 1 } + }, + // Scope recovery reads Pi's cwd buckets, which sit under the agent folder's sessions/. + { + layout: 'a parent folder for a workspace', + piRoot: parentFolder, + scope: { scopePaths: ['/repo/app'], limit: 1 } } ])('lists each transcript once under its writer when Pi scans $layout', async (testCase) => { const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-pi-omp-shared-')) diff --git a/src/main/ai-vault/session-cwd-bucket-layouts.ts b/src/main/ai-vault/session-cwd-bucket-layouts.ts index cb4e2de2fb6..2579edf2175 100644 --- a/src/main/ai-vault/session-cwd-bucket-layouts.ts +++ b/src/main/ai-vault/session-cwd-bucket-layouts.ts @@ -1,19 +1,22 @@ +import { basename, join } from 'node:path' import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' import { - encodeClaudeProjectPaths, - isClaudeProjectDirInScope + claudeProjectBucketScopePrefixes, + isClaudeProjectBucketInScope } from './scanners/claude/claude-project-dir-encoding' export type CwdBucketLayout = { agent: Extract encodeScopePrefixes: (scopePath: string) => string[] isDirInScope: (dirName: string, prefixes: ReadonlySet) => boolean + /** Folders whose children are cwd buckets; defaults to the root itself. */ + bucketDirs?: (rootDir: string) => string[] } export const CLAUDE_CWD_BUCKET_LAYOUT: CwdBucketLayout = { agent: 'claude', - encodeScopePrefixes: encodeClaudeProjectPaths, - isDirInScope: isClaudeProjectDirInScope + encodeScopePrefixes: claudeProjectBucketScopePrefixes, + isDirInScope: isClaudeProjectBucketInScope } // Omit Pi's closing -- so the prefix also matches nested working directories. @@ -24,6 +27,9 @@ function encodePiSessionDirPrefix(pathValue: string): string { export const PI_CWD_BUCKET_LAYOUT: CwdBucketLayout = { agent: 'pi', + // PI_CODING_AGENT_DIR= makes Pi's root the agent folder, whose buckets sit under sessions/. + bucketDirs: (rootDir) => + basename(rootDir) === 'sessions' ? [rootDir] : [rootDir, join(rootDir, 'sessions')], encodeScopePrefixes: (pathValue) => { const raw = encodePiSessionDirPrefix(pathValue) const composed = encodePiSessionDirPrefix(pathValue.normalize('NFC')) diff --git a/src/main/ai-vault/session-scanner-discovery.ts b/src/main/ai-vault/session-scanner-discovery.ts index e9e76c42f2e..e789b0903b9 100644 --- a/src/main/ai-vault/session-scanner-discovery.ts +++ b/src/main/ai-vault/session-scanner-discovery.ts @@ -246,11 +246,12 @@ async function observeSessionSidecar( sizeBytes: fileStat.size } } catch (error) { - return isMissingSidecarError(error) ? 'none' : 'unknown' + return isMissingTranscriptPathError(error) ? 'none' : 'unknown' } } -function isMissingSidecarError(error: unknown): boolean { +/** A missing file or folder is absence, not a refusal; WSL gate errors are always refusals. */ +export function isMissingTranscriptPathError(error: unknown): boolean { if (error instanceof WslTranscriptFsError) { return false } @@ -295,7 +296,7 @@ export async function forEachSessionFile( // Propagate gate refusal so stalled distros are not reported as empty trees. if ( error instanceof WslTranscriptFsError || - (options.strictErrors && !isMissingSidecarError(error)) + (options.strictErrors && !isMissingTranscriptPathError(error)) ) { throw error } diff --git a/src/main/ai-vault/session-scanner-scope-discovery.ts b/src/main/ai-vault/session-scanner-scope-discovery.ts index 7cbfefc2850..bcbd59b8b4b 100644 --- a/src/main/ai-vault/session-scanner-scope-discovery.ts +++ b/src/main/ai-vault/session-scanner-scope-discovery.ts @@ -5,16 +5,16 @@ import { wslGatedReaddir, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' -import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import type { createAiVaultScopeCwdMatcher } from '../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' import type { CwdBucketLayout } from './session-cwd-bucket-layouts' import type { AiVaultAgent, AiVaultScanIssue } from '../../shared/ai-vault/contracts/ai-vault-types' -import { parseWslUncPath } from '../../shared/wsl-paths' +import { parseWslUncPath, toWindowsWslUncPathSpellings } from '../../shared/wsl-paths' import { throwIfAiVaultScanCancelled } from './ai-vault-scan-cancellation' import { yieldToEventLoop } from '../../shared/event-loop-yield' import type { FileWithMtime } from './session-scanner-types' import { extractString, parseJsonObject } from './session-scanner-values' import { scanIssueTextFromError } from './session-scan-issues' +import { isMissingTranscriptPathError } from './session-scanner-discovery' // Limit representative probing when a bucket contains transcripts without cwd records. const REPRESENTATIVE_CWD_LINE_LIMIT = 200 @@ -30,14 +30,14 @@ export function resetProjectDirCwdCacheForTests(): void { projectDirCwdCache.clear() } -// Report WSL refusal so an unreachable root is not mistaken for an empty one. +// Report refusals (WSL, permissions) so an unreadable folder or transcript is not mistaken for an empty one. export function recordRefusal( issues: IssueSink, path: string, error: unknown, agent: AiVaultAgent ): void { - if (error instanceof WslTranscriptFsError) { + if (!isMissingTranscriptPathError(error)) { issues({ agent, path, ...scanIssueTextFromError(error) }) } } @@ -76,16 +76,20 @@ export function cwdBucketScopePrefixes( for (const scopePath of scopePaths) { for (const candidate of scopePathCandidates(scopePath)) { for (const prefix of layout.encodeScopePrefixes(candidate)) { - prefixes.add(prefix) + prefixes.add(prefix.toLowerCase()) } } } return prefixes } +// A WSL share has two UNC spellings, and a transcript may record either one. function scopePathCandidates(scopePath: string): string[] { - const wslScopePath = parseWslUncPath(scopePath) - return wslScopePath ? [scopePath, wslScopePath.linuxPath] : [scopePath] + const wsl = parseWslUncPath(scopePath) + if (!wsl) { + return [scopePath] + } + return [scopePath, wsl.linuxPath, ...toWindowsWslUncPathSpellings(wsl.linuxPath, wsl.distro)] } export async function listProjectDirs( @@ -106,8 +110,12 @@ export async function listProjectDirs( recordRefusal(issues, rootDir, err, layout.agent) return [] } + // Case-folded: Windows cwds differ in case, and each bucket's cwd is still checked afterwards. return entries - .filter((entry) => entry.isDirectory() && layout.isDirInScope(entry.name, scopeProjectPrefixes)) + .filter( + (entry) => + entry.isDirectory() && layout.isDirInScope(entry.name.toLowerCase(), scopeProjectPrefixes) + ) .map((entry) => join(rootDir, entry.name)) } diff --git a/src/main/ai-vault/session-scanner-scope-inventory.ts b/src/main/ai-vault/session-scanner-scope-inventory.ts index 170cf35f924..c0408671123 100644 --- a/src/main/ai-vault/session-scanner-scope-inventory.ts +++ b/src/main/ai-vault/session-scanner-scope-inventory.ts @@ -66,7 +66,7 @@ export async function inventoryCwdBucketFiles( const prefixes = cwdBucketScopePrefixes(layout, args.scopePaths) const inScope = createAiVaultScopeCwdMatcher(args.scopePaths) let index = 0 - for (const rootDir of args.rootDirs) { + for (const rootDir of args.rootDirs.flatMap(layout.bucketDirs ?? ((dir) => [dir]))) { throwIfAiVaultScanCancelled(args.signal) let close: () => void = () => undefined try { diff --git a/src/main/ai-vault/session-scanner-scope.test.ts b/src/main/ai-vault/session-scanner-scope.test.ts index 39f4b2faa17..0af9cfc9b68 100644 --- a/src/main/ai-vault/session-scanner-scope.test.ts +++ b/src/main/ai-vault/session-scanner-scope.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, mkdir, rm, utimes, writeFile } from 'node:fs/promises' +import { chmod, mkdtemp, mkdir, rm, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -37,6 +37,30 @@ function scopedScanOptions(claudeProjectsDir: string, extra: Partial { + await writeClaudeSession({ + claudeRoot, + ...old, + sessionId: 'old-in-scope', + iso: '2026-01-01T00:00:00.000Z' + }) + for (let index = 0; index < 4; index++) { + await writeClaudeSession({ + claudeRoot, + dirName: `-other-${index}`, + sessionId: `recent-${index}`, + cwd: `/other/${index}`, + iso: `2026-06-2${index}T00:00:00.000Z` + }) + } +} + +const LONG_PATH = `/repo/${'nested-folder/'.repeat(16)}app` + async function writeClaudeSession(args: { claudeRoot: string dirName: string @@ -140,4 +164,63 @@ describe('scanAiVaultSessions scope inclusion', () => { expect(result.sessions.map((session) => session.sessionId)).not.toContain('old-wsl-in-scope') }) + + it.each([ + { layout: 'a drive root', scopePath: 'C:\\', dirName: 'C--repo', cwd: 'C:\\repo' }, + { + layout: 'a Windows path in another case', + scopePath: 'c:\\users\\ada\\repo', + dirName: 'C--Users-Ada-repo', + cwd: 'C:\\Users\\Ada\\repo' + }, + { + layout: 'the other WSL share spelling', + scopePath: '\\\\wsl.localhost\\Ubuntu\\home\\ada\\repo', + dirName: '--wsl--Ubuntu-home-ada-repo', + cwd: '\\\\wsl$\\Ubuntu\\home\\ada\\repo' + }, + { + // Claude Code names a bucket over 200 characters `-`. + layout: 'a long path', + scopePath: LONG_PATH, + dirName: `${LONG_PATH.replace(/[^a-zA-Z0-9]/g, '-').slice(0, 200)}-1a2b3c`, + cwd: LONG_PATH + } + ])('finds older in-scope Claude sessions for $layout', async ({ scopePath, dirName, cwd }) => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-scope-')) + tempRoots.push(root) + const claudeRoot = join(root, 'claude-projects') + await writeOldClaudeSessionBehindRecentOnes(claudeRoot, { dirName, cwd }) + + const result = await scanAiVaultSessions( + scopedScanOptions(claudeRoot, { limit: 2, scopePaths: [scopePath] }) + ) + + expect(result.sessions.map((session) => session.sessionId)).toContain('old-in-scope') + }) + + // chmod cannot lock out root, and Windows ignores the mode bits. + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'reports an unreadable in-scope folder instead of listing it as empty', + async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-scope-')) + tempRoots.push(root) + const claudeRoot = join(root, 'claude-projects') + await writeOldClaudeSessionBehindRecentOnes(claudeRoot, { + dirName: '-repo-app', + cwd: '/repo/app' + }) + const bucket = join(claudeRoot, '-repo-app') + await chmod(bucket, 0o000) + try { + const result = await scanAiVaultSessions( + scopedScanOptions(claudeRoot, { limit: 2, scopePaths: ['/repo/app'] }) + ) + + expect(result.issues.map((issue) => issue.path)).toContain(bucket) + } finally { + await chmod(bucket, 0o755) + } + } + ) }) diff --git a/src/main/automations/external-automation-owner-guard.ts b/src/main/automations/external-automation-owner-guard.ts index e608e341fbf..6f05d314bf3 100644 --- a/src/main/automations/external-automation-owner-guard.ts +++ b/src/main/automations/external-automation-owner-guard.ts @@ -20,7 +20,7 @@ import type { SshTarget } from '../../shared/ssh-types' import { isManagedOrcadSshTarget, isRuntimeOwnedSshTarget -} from '../ssh/connection/ssh-connection-store' +} from '../ssh/targets/ssh-target-runtime-ownership' /** Include hidden registrations so the guard can reject them before comparing generations. */ export type DesktopSshTargetRegistry = { diff --git a/src/main/automations/orcad-fenced-automation.ts b/src/main/automations/orcad-fenced-automation.ts index 8792dd6182d..e5f5262726c 100644 --- a/src/main/automations/orcad-fenced-automation.ts +++ b/src/main/automations/orcad-fenced-automation.ts @@ -2,9 +2,9 @@ import { getAppEnvironment } from '../../shared/app-environment' import type { Automation } from '../../shared/automations/automation-definition' import type { SshTarget } from '../../shared/ssh-types' import type { Store } from '../persistence/loading-store/store' -import { isManagedOrcadSshTarget } from '../ssh/connection/ssh-connection-store' +import { isManagedOrcadSshTarget } from '../ssh/targets/ssh-target-runtime-ownership' import { moveProjectToManagedHostFirst } from '../../shared/managed-orcad-ssh-owner' -import { listOrcadMigrationCutoverChainForTarget } from '../ssh/orcad-migration-cutover-journal' +import { listOrcadMigrationCutoverChainForTarget } from '../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' export const ORCAD_FENCED_AUTOMATION = "This automation now runs on its SSH host's Orca server." diff --git a/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts b/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts index 0b384b038ee..756629b0d6f 100644 --- a/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts +++ b/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts @@ -16,7 +16,7 @@ export const resolveBrowserNetworkExecutionRoute: BrowserNetworkExecutionRouteRe } const [{ getSshConnectionManager }, authority, sshRoute] = await Promise.all([ import('../../../ssh/targets/ssh-target-registry'), - import('../../../ssh/ssh-provider-authority'), + import('../../../ssh/connection/authority/ssh-provider-authority'), import('./ssh-browser-network-execution-route') ]) const connectionManager = getSshConnectionManager() diff --git a/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts b/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts index 386cc91b4ac..2c8602d54bb 100644 --- a/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts +++ b/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts @@ -6,11 +6,11 @@ import type { BrowserNetworkTunnelOpen } from '../../../../shared/browser-networ import { loadHostProxyEnvironment, readSshHostProxyEnvironment -} from '../../../ssh/ssh-host-proxy-environment' +} from '../../../ssh/remote-host/ssh-host-proxy-environment' import { startSystemSshDynamicForwardProcess, type SystemSshDynamicForwardProcess -} from '../../../ssh/system-transport/system-ssh-dynamic-forward-process' +} from '../../../ssh/system-transport/forwarding/system-ssh-dynamic-forward-process' import { BrowserNetworkDeferredSocket } from './browser-network-deferred-socket' import { browserNetworkExecutionHostKey, diff --git a/src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.ts b/src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.ts index 9313f921f63..e59318e28be 100644 --- a/src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.ts +++ b/src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.ts @@ -1,7 +1,7 @@ import { spawnProcess } from '@orca/process-host' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' -import { relayBundleCandidates } from '../../../ssh/relay-bundle-paths' +import { relayBundleCandidates } from '../../../wsl/execution/relay-bundle-paths' import { withWslGuestLauncherRevision } from '../../../wsl/execution/wsl-guest-launcher-revision' import { orcadPosixNodeRuntimeGlobs } from '../../../managed-server/install/orcad-node-runtime-globs' import { diff --git a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts b/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts index 49cc3633ed3..63c995ca7e7 100644 --- a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts +++ b/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts @@ -165,7 +165,7 @@ const routesByTargetId = new Map() async function defaultDependencies(): Promise { const [{ resolveBrowserNetworkExecutionRoute }, authority] = await Promise.all([ import('../../network/execution-routes/browser-network-execution-route-dispatch'), - import('../../../ssh/ssh-provider-authority') + import('../../../ssh/connection/authority/ssh-provider-authority') ]) return { resolveExecutionRoute: resolveBrowserNetworkExecutionRoute, diff --git a/src/main/claude-accounts/claude-profile-wsl-router.ts b/src/main/claude-accounts/claude-profile-wsl-router.ts index ba662e5879d..7def9cf8475 100644 --- a/src/main/claude-accounts/claude-profile-wsl-router.ts +++ b/src/main/claude-accounts/claude-profile-wsl-router.ts @@ -11,7 +11,7 @@ import { WSL_CLAUDE_PROFILE_HELPER_FILENAME } from '../../shared/remote-bundle-a import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' import { getWslHomeAsync, listRunningWslDistrosAsync } from '../wsl/discovery/distro-catalog' import { ensureWslPinnedRuntime } from '../wsl/execution/wsl-pinned-runtime' -import { relayBundleCandidates } from '../ssh/relay-bundle-paths' +import { relayBundleCandidates } from '../wsl/execution/relay-bundle-paths' import { runWslProcess, type WslSpec } from '../wsl/execution/wsl-runner' import { describeWslProcessFailure } from '../wsl/execution/wsl-process-failure' import { blockedWslDistroForPath } from '../wsl/filesystem/wsl-unc-access-gate' diff --git a/src/main/claude/structured/claude-structured-session-startup-exit.ts b/src/main/claude/structured/claude-structured-session-startup-exit.ts index 65a898168c8..6b3f39ac45e 100644 --- a/src/main/claude/structured/claude-structured-session-startup-exit.ts +++ b/src/main/claude/structured/claude-structured-session-startup-exit.ts @@ -38,7 +38,9 @@ export async function claudeExitForReport( connection: Pick, error: unknown ): Promise { - return error instanceof Error && claudeStartupAnswer(error) === 'reported' && connection.exited + return error instanceof Error && + (claudeStartupAnswer(error) === 'reported' || isClaudeQueryClosed(error)) && + connection.exited ? withTimeout(connection.exited, 2_000, undefined) : undefined } diff --git a/src/main/claude/structured/claude-structured-session-startup.test.ts b/src/main/claude/structured/claude-structured-session-startup.test.ts index dfb39fdfeff..480557b9953 100644 --- a/src/main/claude/structured/claude-structured-session-startup.test.ts +++ b/src/main/claude/structured/claude-structured-session-startup.test.ts @@ -6,6 +6,7 @@ import { claudeFrame, identityFor, recordingJournalSink, + USER_MESSAGE, PROVIDER_SESSION_ID } from './claude-structured-session-test-support' import { claudeOpened } from './claude-structured-startup-settled-test-support' @@ -115,6 +116,28 @@ describe('Claude host-awaited open', () => { } }) + it('opens a healthy Claude session whose initialize takes longer than a minute', async () => { + const claude = fakeClaude({ initDelayMs: 75_000 }) + const { adapter } = adapterFor(claude) + await adapter.acquire(ACQUIRE) + const opened = expect(claudeOpened(adapter, 'session-1')).resolves.toMatchObject({ + reportedOptions: expect.any(Object) + }) + await vi.advanceTimersByTimeAsync(75_000) + await opened + await expect( + adapter.dispatch({ + sessionId: 'session-1', + fence: 7, + clientMessageId: 'slow-start', + body: USER_MESSAGE + }) + ).resolves.toMatchObject({ state: 'admitted' }) + expect(claude.connections[0].sent).toMatchObject([ + { message: { content: [{ type: 'text', text: 'ship it' }] } } + ]) + }) + it('lets the host abort a silent initialize wait and close the owned process', async () => { const claude = fakeClaude({ initDelayMs: 12_000 }) const { adapter } = adapterFor(claude) diff --git a/src/main/claude/structured/claude-structured-session-startup.ts b/src/main/claude/structured/claude-structured-session-startup.ts index 78b4b2da36c..27f5e8cd116 100644 --- a/src/main/claude/structured/claude-structured-session-startup.ts +++ b/src/main/claude/structured/claude-structured-session-startup.ts @@ -8,7 +8,6 @@ import { import type { AgentSessionAccountKind } from '../../../shared/agent-session/agent-session-availability' import type { StructuredAgentSessionProviderOpenResult } from '../../native-chat/agent-session-wire/startup/structured-agent-session-provider-open-contract' -import { withProviderRequestTimeout } from '../../provider-process/provider-request-timeout' import type { ClaudeStreamJsonConnection } from '../claude-stream-json-connection' import { ClaudeSlashCommandCatalog } from '../claude-slash-command-catalog' import { @@ -61,8 +60,6 @@ export type ClaudeStartupFacts = ClaudeInitializeFacts & { prepared: ReturnType } -export const CLAUDE_INITIALIZE_TIMEOUT_MS = 60_000 - export async function readClaudeStartupFacts(input: { connection: ClaudeStreamJsonConnection initProof: ClaudeInitProof @@ -73,7 +70,6 @@ export async function readClaudeStartupFacts(input: { requestTimeoutMs: number | undefined emit: (event: ClaudeStructuredSessionEvent) => void }): Promise { - let timer: ReturnType | undefined const control = input.connection.initializationResult().then((result) => { const authError = claudeInitializationAuthError(result, input.account) if (authError) { @@ -83,6 +79,7 @@ export async function readClaudeStartupFacts(input: { }) const initialization = await Promise.race([ control.catch(async (error: unknown) => { + const exit = await claudeExitForReport(input.connection, error) let proof: unknown try { input.initProof.seen() @@ -94,8 +91,8 @@ export async function readClaudeStartupFacts(input: { throw claudeStartFailure([ input.connection.startupFailure?.(), proof, - error, - await claudeExitForReport(input.connection, error) + (proof || providerExitObserved(exit)) && isClaudeQueryClosed(error) ? undefined : error, + exit ]) }), Promise.race([ @@ -108,23 +105,8 @@ export async function readClaudeStartupFacts(input: { throw error } throw await claudeStartupAnswerAfterExit(input.connection, control, error) - }), - new Promise((_resolve, reject) => { - timer = setTimeout( - () => - reject( - withProviderRequestTimeout( - new Error( - `claude did not answer initialize within ${CLAUDE_INITIALIZE_TIMEOUT_MS}ms` - ), - { method: 'initialize', timeoutMs: CLAUDE_INITIALIZE_TIMEOUT_MS } - ) - ), - CLAUDE_INITIALIZE_TIMEOUT_MS - ) - timer.unref?.() }) - ]).finally(() => clearTimeout(timer)) + ]) if (input.connection.closed) { throw ( input.connection.startupFailure?.() ?? diff --git a/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts b/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts index 0715f51e7d1..7eb5d73dd65 100644 --- a/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts +++ b/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts @@ -51,8 +51,8 @@ import { acceptEphemeralVmWorkspaceWake, resumeEphemeralVmWorkspace } from './wo import { recordSshUserDisconnected, resetSshUserDisconnectsForTests -} from '../ssh/ssh-user-disconnect' -import { getRuntimeOwnedSshTargetId } from '../ssh/connection/ssh-connection-store' +} from '../ssh/connection/ssh-user-disconnect' +import { getRuntimeOwnedSshTargetId } from '../ssh/targets/ssh-target-runtime-ownership' // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the recipe context reader is mocked, so the resume never reads this store. const STORE = {} as Store diff --git a/src/main/ephemeral-vm/workspace-resume.ts b/src/main/ephemeral-vm/workspace-resume.ts index 48a83fdad3b..fe7e645ee6d 100644 --- a/src/main/ephemeral-vm/workspace-resume.ts +++ b/src/main/ephemeral-vm/workspace-resume.ts @@ -16,8 +16,11 @@ import { import { resumeEphemeralVmRuntime } from './runtime-service' import { connectRuntimeOwnedSshTarget, refreshRuntimeOwnedSshTarget } from './runtime-ssh' import { noteRecipeVmWakePairing } from './recipe-vm-wake-pairings' -import { getRuntimeOwnedSshTargetId } from '../ssh/connection/ssh-connection-store' -import { isSshUserDisconnected, sshUserDisconnectCount } from '../ssh/ssh-user-disconnect' +import { getRuntimeOwnedSshTargetId } from '../ssh/targets/ssh-target-runtime-ownership' +import { + isSshUserDisconnected, + sshUserDisconnectCount +} from '../ssh/connection/ssh-user-disconnect' import type { VmWakeRequest } from '../runtime/workspaces/sleep/workspace-sleep-platform' import { getRuntimeRecipeContext } from '../ipc/ephemeral-vm-recipe-context' import { invalidateRuntimeEnvironmentTransport } from '../ipc/runtime-environments/runtime-environments' diff --git a/src/main/external-editors/remote-ssh-editor-launch.ts b/src/main/external-editors/remote-ssh-editor-launch.ts index 66df4713450..8f762654731 100644 --- a/src/main/external-editors/remote-ssh-editor-launch.ts +++ b/src/main/external-editors/remote-ssh-editor-launch.ts @@ -6,8 +6,8 @@ import { resolveExternalEditorExecutable, type ExternalEditorLaunchSpec } from './external-editor-launch' -import { resolveVsCodeSshAuthority } from '../ssh/config/vscode-ssh-authority' -import { resolveZedSshUrl } from '../ssh/config/zed-ssh-url' +import { resolveVsCodeSshAuthority } from '../ssh/external-editors/vscode-ssh-authority' +import { resolveZedSshUrl } from '../ssh/external-editors/zed-ssh-url' export function resolveRemoteSshEditorLaunchSpec( command: string | undefined, diff --git a/src/main/github/body-image-read-adapters.test.ts b/src/main/github/body-image-read-adapters.test.ts new file mode 100644 index 00000000000..8dcd75701bc --- /dev/null +++ b/src/main/github/body-image-read-adapters.test.ts @@ -0,0 +1,154 @@ +import { beforeEach, expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ exec: vi.fn(), graphql: vi.fn() })) +vi.mock('./gh-utils', () => ({ + ghExecFileAsync: mocks.exec, + ghRepoExecOptions: () => ({}), + githubRepoContext: () => ({}) +})) +vi.mock('./rate-limit', () => ({ + repositoryRateLimitGuard: () => ({ blocked: false }), + noteRepositoryRateLimitSpend: () => {} +})) +vi.mock('./project-view/internals', () => ({ + assertPositiveInt: () => ({ ok: true }), + validateSlugArgs: () => ({ ok: true }), + projectGhExecOptions: () => ({}), + runGraphql: mocks.graphql +})) +import { getPRMetadata } from './pull-request-file-data' +import { getWorkItemDetailsBySlug } from './project-view/work-item-details' + +const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' +const html = + '' +const expectedMap = { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' +} +beforeEach(() => { + mocks.exec.mockReset() + mocks.graphql.mockReset() +}) + +it('gets PR metadata images in its existing uncached full-media read', async () => { + mocks.exec.mockResolvedValueOnce({ + stdout: JSON.stringify({ body, body_html: html, head: { sha: 'head' } }) + }) + const metadata = await getPRMetadata('/repo', 7, { owner: 'acme', repo: 'widgets' }) + expect(metadata).toMatchObject({ body, headSha: 'head', bodyImageUrls: expectedMap }) + expect(mocks.exec).toHaveBeenCalledTimes(1) + expect(mocks.exec.mock.calls[0][0]).toEqual([ + 'api', + '-H', + 'Accept: application/vnd.github.full+json', + 'repos/acme/widgets/pulls/7' + ]) +}) + +it.each(['issue', 'pr'] as const)( + 'gets slug %s body and comment images in one existing read', + async (type) => { + mocks.graphql.mockResolvedValueOnce({ + ok: true, + data: { + repository: { + [type === 'issue' ? 'issue' : 'pullRequest']: { + id: 'ITEM', + body, + bodyHTML: html, + comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] } + } + } + } + }) + const result = await getWorkItemDetailsBySlug({ + owner: 'acme', + repo: 'widgets', + number: 7, + type + }) + expect(result.ok && result.details.body).toBe(body) + expect(result.ok && result.details.bodyImageUrls).toEqual(expectedMap) + expect(result.ok && result.details.comments[0].bodyImageUrls).toEqual(expectedMap) + expect(mocks.graphql).toHaveBeenCalledTimes(1) + expect(mocks.exec).not.toHaveBeenCalled() + } +) + +it.each(['issue', 'pr'] as const)( + 'recovers available slug %s data without trusting failed HTML', + async (type) => { + const root = type === 'issue' ? 'issue' : 'pullRequest' + mocks.graphql.mockResolvedValueOnce({ + ok: false, + error: { type: 'unknown', message: 'field error' }, + raw: { + stdout: JSON.stringify({ + data: { + repository: { + [root]: { + id: 'ITEM', + body, + bodyHTML: html, + comments: { + nodes: [ + { databaseId: 1, body, bodyHTML: html }, + { databaseId: 2, body, bodyHTML: html } + ] + } + } + } + }, + errors: [ + { path: ['repository', root, 'bodyHTML'] }, + { path: ['repository', root, 'comments', 'nodes', 0, 'bodyHTML'] } + ] + }), + stderr: '' + } + }) + const result = await getWorkItemDetailsBySlug({ + owner: 'acme', + repo: 'widgets', + number: 7, + type + }) + expect(result.ok && result.details.body).toBe(body) + expect(result.ok && result.details.bodyImageUrls).toBeUndefined() + expect(result.ok && result.details.comments[0].bodyImageUrls).toBeUndefined() + expect(result.ok && result.details.comments[1].bodyImageUrls).toEqual(expectedMap) + expect(mocks.graphql).toHaveBeenCalledTimes(1) + expect(mocks.exec).not.toHaveBeenCalled() + } +) + +it.each(['null parent', 'required field', 'pathless'] as const)( + 'keeps the original slug failure for %s', + async (input) => { + const error = { type: 'unknown', message: 'original failure' } + mocks.graphql.mockResolvedValueOnce({ + ok: false, + error, + raw: { + stderr: '', + stdout: JSON.stringify({ + data: { + repository: { issue: input === 'null parent' ? null : { body, bodyHTML: html } } + }, + errors: [ + { + path: + input === 'pathless' + ? undefined + : ['repository', 'issue', input === 'required field' ? 'body' : 'bodyHTML'] + } + ] + }) + } + }) + await expect( + getWorkItemDetailsBySlug({ owner: 'acme', repo: 'widgets', number: 7, type: 'issue' }) + ).resolves.toEqual({ ok: false, error: { type: 'unknown', message: 'original failure' } }) + } +) diff --git a/src/main/github/body-image-urls.test.ts b/src/main/github/body-image-urls.test.ts new file mode 100644 index 00000000000..a9cb4b32f46 --- /dev/null +++ b/src/main/github/body-image-urls.test.ts @@ -0,0 +1,138 @@ +import type * as HtmlParser from 'hast-util-from-html-isomorphic' +import type { Root, RootContent } from 'hast' +import { describe, expect, it, vi } from 'vitest' +const traversal = vi.hoisted(() => ({ enabled: false, parses: 0, children: 0, fail: false })) +vi.mock('hast-util-from-html-isomorphic', async (load) => { + const actual = await load() + return { + ...actual, + fromHtmlIsomorphic: (...args: Parameters) => { + if (traversal.fail) { + throw new Error('Optional image HTML could not be parsed') + } + const tree = actual.fromHtmlIsomorphic(...args) + if (!traversal.enabled) { + return tree + } + traversal.parses++ + const pending: (Root | RootContent)[] = [tree] + while (pending.length) { + const node = pending.pop()! + if (!('children' in node)) { + continue + } + const children = node.children + pending.push(...children) + Object.defineProperty(node, 'children', { + get: () => { + traversal.children++ + return children + } + }) + } + return tree + } + } +}) +import { githubBodyImageUrls } from './body-image-urls' + +const original = 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488' +const signed = + 'https://private-user-images.githubusercontent.com/1/2-ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST&download=1' + +describe('GitHub body image sources', () => { + it.each([ + { body: `![shot](${original})`, html: true }, + { body: true, html: `` } + ])('ignores unusable optional representations ($body, $html)', ({ body, html }) => { + expect(githubBodyImageUrls(body, html)).toBeUndefined() + }) + + it('skips HTML parsing when the Markdown has no attachment candidates', () => { + traversal.enabled = true + traversal.parses = 0 + try { + expect(githubBodyImageUrls('A plain comment', ``)).toBeUndefined() + expect(traversal.parses).toBe(0) + } finally { + traversal.enabled = false + } + }) + + it('leaves the optional map absent if HTML extraction fails', () => { + traversal.fail = true + try { + expect(githubBodyImageUrls(`![shot](${original})`, ``)).toBeUndefined() + } finally { + traversal.fail = false + } + }) + + it('matches rendered images to canonical assets without changing editable Markdown', () => { + const body = `![shot](${original})\n\n![missing](https://github.com/user-attachments/assets/cc11040a-fb66-4289-927f-547b16dfc488)\n\`https://github.com/user-attachments/assets/dd11040a-fb66-4289-927f-547b16dfc488\`` + const html = `https://private-user-images.githubusercontent.com/1/dd11040a-fb66-4289-927f-547b16dfc488.png` + expect(githubBodyImageUrls(body, html)).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': signed, + 'https://github.enterprise/team/repo/assets/42/ab11040a-fb66-4289-927f-547b16dfc488': + 'https://github.enterprise/storage/ab11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(githubBodyImageUrls(body, undefined)).toBeUndefined() + expect(githubBodyImageUrls(`![public](${original})`, ``)).toBeUndefined() + expect( + githubBodyImageUrls( + body, + '' + ) + ).toBeUndefined() + }) + + it('bounds candidate validation and indexed lookups at N and 10N', () => { + for (const n of [100, 1000]) { + const ids = Array.from( + { length: n }, + (_, i) => `ce11040a-fb66-4289-927f-${String(i).padStart(12, '0')}` + ) + const body = ids + .map((id) => `![shot](https://github.com/user-attachments/assets/${id})`) + .join('\n') + const html = ids + .map( + (id) => + `` + ) + .join('\n') + traversal.enabled = true + traversal.parses = 0 + traversal.children = 0 + const pathname = vi.spyOn(URL.prototype, 'pathname', 'get') + const originalGet = Map.prototype.get + let lookups = 0 + Map.prototype.get = function (this: Map, key: unknown) { + if (typeof key === 'string' && key.startsWith('ce11040a-')) { + lookups++ + } + return originalGet.call(this, key) + } + try { + const result = githubBodyImageUrls(body, html) + expect(Object.keys(result ?? {})).toHaveLength(n) + // Each candidate and original is checked once, then each original gets one indexed lookup. + expect(pathname.mock.calls.length).toBeLessThanOrEqual(3 * n) + expect(lookups).toBe(n) + expect(traversal.parses).toBe(1) + expect(traversal.children).toBeLessThanOrEqual(n + 1) + expect( + result?.[ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-000000000000' + ] + ).toBe( + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-000000000000.png?jwt=TEST' + ) + } finally { + traversal.enabled = false + Map.prototype.get = originalGet + pathname.mockRestore() + } + } + }) +}) diff --git a/src/main/github/body-image-urls.ts b/src/main/github/body-image-urls.ts new file mode 100644 index 00000000000..c81f9a7952e --- /dev/null +++ b/src/main/github/body-image-urls.ts @@ -0,0 +1,144 @@ +import { fromHtmlIsomorphic } from 'hast-util-from-html-isomorphic' +import type { Root, RootContent } from 'hast' + +const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' +const githubBodyAssetPath = new RegExp(`/assets/(?:\\d+/)?(${UUID})$`, 'i') + +export function githubBodyImageCandidates(body: string): Map { + const originals = new Map() + for (const match of body.matchAll(/https:\/\/[^\s<>"'`()[\]]+/g)) { + if (!match[0].includes('/assets/')) { + continue + } + try { + const url = new URL(match[0]) + if (githubBodyAssetPath.test(url.pathname)) { + originals.set(match[0], url) + } + } catch { + // An invalid Markdown URL cannot identify an attachment. + } + } + return originals +} + +const imageId = new RegExp(UUID, 'i') +export const GITHUB_BODY_MEDIA_TYPE = 'Accept: application/vnd.github.full+json' + +type GitHubBodyHtmlObject = Record + +function isGitHubBodyHtmlObject(value: unknown): value is GitHubBodyHtmlObject { + return value !== null && typeof value === 'object' +} + +export function removeFailedGitHubBodyHtml( + data: unknown, + errors: T[] | undefined +): T[] | undefined { + const isIndex = (value: unknown): boolean => + typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 + return errors?.filter((error) => { + if (!error || typeof error !== 'object' || !('path' in error)) { + return true + } + const path = error.path + if ( + !Array.isArray(path) || + path[0] !== 'repository' || + (path[1] !== 'issue' && path[1] !== 'pullRequest') || + path.at(-1) !== 'bodyHTML' + ) { + return true + } + const owned = + path.length === 3 || + (path.length === 6 && + (path[2] === 'comments' || (path[1] === 'pullRequest' && path[2] === 'reviews')) && + path[3] === 'nodes' && + isIndex(path[4])) || + (path.length === 9 && + path[1] === 'pullRequest' && + path[2] === 'reviewThreads' && + path[3] === 'nodes' && + isIndex(path[4]) && + path[5] === 'comments' && + path[6] === 'nodes' && + isIndex(path[7])) + if (!owned) { + return true + } + let target = data + for (const part of path.slice(0, -1)) { + if (!isGitHubBodyHtmlObject(target) || (typeof part === 'number' && !Array.isArray(target))) { + return true + } + target = target[part] + } + if (!isGitHubBodyHtmlObject(target) || typeof target.body !== 'string') { + return true + } + delete target.bodyHTML + return false + }) +} + +export function githubBodyMediaHeaders(body: string): string[] { + return githubBodyImageCandidates(body).size ? ['-H', GITHUB_BODY_MEDIA_TYPE] : [] +} + +/** Keep short-lived display URLs separate from editable Markdown and persisted item metadata. */ +export function githubBodyImageUrls( + body: unknown, + html: unknown +): Record | undefined { + if (typeof body !== 'string' || typeof html !== 'string' || !html) { + return undefined + } + try { + const originals = githubBodyImageCandidates(body) + if (!originals.size) { + return undefined + } + + const signed = new Map() + const pending: (Root | RootContent)[] = [fromHtmlIsomorphic(html, { fragment: true })] + while (pending.length) { + const node = pending.pop()! + if ('children' in node) { + pending.push(...node.children) + } + if (node.type !== 'element' || node.tagName !== 'img') { + continue + } + const src = node.properties.src + if (typeof src !== 'string') { + continue + } + try { + const url = new URL(src) + const id = url.pathname.match(imageId)?.[0].toLowerCase() + if (id && url.protocol === 'https:') { + signed.set(id, url) + } + } catch { + // Relative or malformed HTML sources do not supply a signed attachment URL. + } + } + + const result: Record = {} + for (const [original, url] of originals) { + const id = url.pathname.match(githubBodyAssetPath)![1].toLowerCase() + const display = signed.get(id) + if ( + display && + display.href !== original && + (display.hostname.endsWith('.githubusercontent.com') || display.host === url.host) + ) { + result[original] = display.href + } + } + return Object.keys(result).length ? result : undefined + } catch { + return undefined + } +} diff --git a/src/main/github/client-pr-conversation-requests.test.ts b/src/main/github/client-pr-conversation-requests.test.ts index 65a657cc6e5..84d729a97ec 100644 --- a/src/main/github/client-pr-conversation-requests.test.ts +++ b/src/main/github/client-pr-conversation-requests.test.ts @@ -98,6 +98,8 @@ describe('PR conversation request reuse', () => { expect(comments.map((c) => c.body)).toEqual(['Conversation', 'Review summary']) expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual([ 'api', + '-H', + 'Accept: application/vnd.github.full+json', 'repos/acme/widgets/pulls/7/reviews?per_page=100' ]) expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) @@ -159,4 +161,144 @@ describe('PR conversation request reuse', () => { ['me', true] ]) }) + it.each([0, 100, 1000])( + 'gets image maps in the existing conversation request (%s bodies)', + async (n) => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const imageComments = Array.from({ length: n }, (_, i) => ({ + ...comment, + id: `IMAGE_${i}`, + databaseId: i, + body, + bodyHTML: + '', + path: 'file.ts' + })) + const threads = Array.from({ length: n / 100 }, (_, i) => ({ + id: `THREAD_${i}`, + isResolved: false, + line: 1, + startLine: null, + originalLine: 1, + originalStartLine: null, + comments: { nodes: imageComments.slice(i * 100, (i + 1) * 100) } + })) + ghExecFileAsyncMock.mockResolvedValueOnce( + response({ + comments: { nodes: [comment] }, + reviews: { nodes: [] }, + reviewThreads: { nodes: threads } + }) + ) + const result = await getPRComments('/repo', 7, { ...options, noCache: true }) + // One request owns all selected bodies, independent of their image population. + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(result.filter((c) => c.path === 'file.ts')).toHaveLength(n) + if (n === 0) { + return + } + expect(result.find((c) => c.id === 0)?.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(result.find((c) => c.id === 0)?.body).toBe(body) + } + ) + + it.each([false, true])( + 'holds the existing permit until the paired command settles (reject: %s)', + async (reject) => { + let settle!: (result: { stdout: string }) => void + let fail!: (error: Error) => void + const pending = new Promise<{ stdout: string }>((resolve, reject) => { + settle = resolve + fail = reject + }) + let started!: () => void + const commandStarted = new Promise((resolve) => { + started = resolve + }) + ghExecFileAsyncMock.mockImplementationOnce(() => { + started() + return pending + }) + const read = getPRComments('/repo', 7, { ...options, noCache: true }) + await commandStarted + expect(clientMocks.acquireMock).toHaveBeenCalledTimes(1) + expect(clientMocks.releaseMock).not.toHaveBeenCalled() + const raw = response({ + comments: { nodes: [comment] }, + reviews: { nodes: [] }, + reviewThreads: { nodes: [] } + }) + if (reject) { + fail(Object.assign(new Error('Partial GraphQL response'), raw)) + } else { + settle(raw) + } + const result = await read + expect(result).toMatchObject([{ body: 'Conversation' }]) + expect(clientMocks.releaseMock).toHaveBeenCalledTimes(1) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(result[0].bodyImageUrls).toBeUndefined() + } + ) + + it('keeps usable raw fields and siblings when optional HTML errors, without a fallback request', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + const partial = response( + { + comments: { nodes: [{ ...comment, body, bodyHTML: html }] }, + reviews: { nodes: [] }, + reviewThreads: { + nodes: [ + { + id: 'THREAD', + isResolved: false, + line: 1, + startLine: null, + originalLine: 1, + originalStartLine: null, + comments: { + nodes: [ + { ...comment, databaseId: 11, body, bodyHTML: html, path: 'file.ts' }, + { ...comment, databaseId: 12, body, bodyHTML: html, path: 'file.ts' } + ] + } + } + ] + } + }, + [ + { path: ['repository', 'pullRequest', 'comments', 'nodes', 0, 'bodyHTML'] }, + { + path: [ + 'repository', + 'pullRequest', + 'reviewThreads', + 'nodes', + 0, + 'comments', + 'nodes', + 0, + 'bodyHTML' + ] + } + ] + ) + ghExecFileAsyncMock.mockRejectedValueOnce(Object.assign(new Error('GraphQL error'), partial)) + const result = await getPRComments('/repo', 7, { ...options, noCache: true }) + expect(result.map((c) => c.body)).toEqual([body, body, body]) + expect(result.find((c) => c.id === 10)?.bodyImageUrls).toBeUndefined() + expect(result.find((c) => c.id === 11)?.bodyImageUrls).toBeUndefined() + expect(result.find((c) => c.id === 12)?.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/main/github/client/create/add-pr-review-comment.ts b/src/main/github/client/create/add-pr-review-comment.ts index 6b2f4016c66..25d298241ad 100644 --- a/src/main/github/client/create/add-pr-review-comment.ts +++ b/src/main/github/client/create/add-pr-review-comment.ts @@ -1,3 +1,4 @@ +import { githubBodyMediaHeaders } from '../../body-image-urls' import type { GitHubCommentResult, GitHubPRReviewCommentInput @@ -31,6 +32,7 @@ export async function addPRReviewComment( try { const fields = [ 'api', + ...githubBodyMediaHeaders(args.body), '-X', 'POST', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${args.prNumber}/comments`, @@ -97,6 +99,7 @@ export async function addPRReviewCommentReply( const { stdout } = await ghExecFileAsync( [ 'api', + ...githubBodyMediaHeaders(body), '-X', 'POST', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${prNumber}/comments/${commentId}/replies`, diff --git a/src/main/github/client/fetch/get-pr-comments.ts b/src/main/github/client/fetch/get-pr-comments.ts index 8401c219dbd..be44913966c 100644 --- a/src/main/github/client/fetch/get-pr-comments.ts +++ b/src/main/github/client/fetch/get-pr-comments.ts @@ -1,3 +1,4 @@ +import { GITHUB_BODY_MEDIA_TYPE } from '../../body-image-urls' import type { PRComment } from '../../../../shared/github/comment-types' import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' import { extractExecError } from '../../../git/exec-error' @@ -31,8 +32,6 @@ async function readPRComments( let restBudgetFailed = false try { if (ownerRepo) { - // Explicit refresh bypasses the polling cache. - const cacheArgs = options?.noCache ? [] : ['--cache', '60s'] const base = `repos/${ownerRepo.owner}/${ownerRepo.repo}` // Retain successful comment sources when another endpoint fails. @@ -60,9 +59,9 @@ async function readPRComments( ) } catch (error) { // gh exits nonzero for partial GraphQL errors; keep the successful sources. - const { stdout } = extractExecError(error) + const { stdout, stderr } = extractExecError(error) threadsResult = stdout ? { stdout } : null - console.warn('Failed to fetch review threads:', error) + console.warn('Failed to fetch review threads:', stderr) } } @@ -85,12 +84,12 @@ async function readPRComments( try { noteRepositoryRateLimitSpend(ownerRepo, 'core', reviews ? 1 : 2, ghOptions) const [{ stdout }, viewerLogin] = await Promise.all([ - ghExecFileAsync(['api', ...cacheArgs, endpoint], ghOptions), + ghExecFileAsync(['api', '-H', GITHUB_BODY_MEDIA_TYPE, endpoint], ghOptions), reviews ? null : readViewerLogin(ghOptions) ]) return parseRestPRComments(stdout, reviews, viewerLogin) } catch (error) { - console.warn('Failed to fetch PR conversation fallback:', error) + console.warn('Failed to fetch PR conversation fallback:', extractExecError(error).stderr) return [] } } diff --git a/src/main/github/client/fetch/pr-conversation-response.ts b/src/main/github/client/fetch/pr-conversation-response.ts index 7dfbac2e82a..1593a486f82 100644 --- a/src/main/github/client/fetch/pr-conversation-response.ts +++ b/src/main/github/client/fetch/pr-conversation-response.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../../body-image-urls' import type { Nodes } from 'mdast' import { z } from 'zod' import remarkParse from 'remark-parse' @@ -14,6 +15,7 @@ const commentSchema = z.object({ .object({ __typename: z.string().optional(), login: z.string(), avatarUrl: z.string() }) .nullable(), body: z.string().nullish(), + bodyHTML: z.unknown().optional(), createdAt: z.string(), submittedAt: z.string().nullish(), url: z.string(), @@ -82,11 +84,12 @@ function hasDatabaseId( function mapGraphQLComment( comment: z.infer & { databaseId: number } ): PRComment { - return { + const mapped: PRComment = { id: comment.databaseId, author: comment.author?.login ?? 'ghost', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body ?? '', + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: comment.submittedAt ?? comment.createdAt, url: comment.url, isBot: comment.author?.__typename === 'Bot', @@ -94,6 +97,7 @@ function mapGraphQLComment( reactionSubjectId: comment.id, reactions: mapGraphQLReactionGroups(comment.reactionGroups) } + return mapped } const reviewMarkdown = unified().use(remarkParse) @@ -123,10 +127,11 @@ export function parsePRConversationResponse(stdout: string): { reviewComments: PRComment[] } { const envelope = envelopeSchema.parse(JSON.parse(stdout)) + const errors = removeFailedGitHubBodyHtml(envelope.data, envelope.errors) const pr = envelope.data?.repository?.pullRequest const failed = (source: string): boolean => Boolean( - envelope.errors?.some( + errors?.some( (error) => !error.path?.length || !error.path.includes('pullRequest') || error.path[2] === source ) @@ -149,19 +154,20 @@ export function parsePRConversationResponse(stdout: string): { reviewComments: threads.success ? threads.data.nodes.flatMap((thread) => thread - ? thread.comments.nodes.filter(hasDatabaseId).map((c) => ({ - ...mapGraphQLComment(c), - // Left-side threads count old-file lines, which the shared tail numbering cannot place. - ...(c === thread.comments.nodes[0] && thread.diffSide !== 'LEFT' - ? rootDiffHunk(thread.rootHunk) - : {}), - path: c.path, - threadId: thread.id, - isResolved: thread.isResolved, - isOutdated: thread.line == null, - line: thread.line ?? thread.originalLine ?? undefined, - startLine: thread.startLine ?? thread.originalStartLine ?? undefined - })) + ? thread.comments.nodes.filter(hasDatabaseId).map((c) => + Object.assign(mapGraphQLComment(c), { + // Left-side threads count old-file lines, which the shared tail numbering cannot place. + ...(c === thread.comments.nodes[0] && thread.diffSide !== 'LEFT' + ? rootDiffHunk(thread.rootHunk) + : {}), + path: c.path, + threadId: thread.id, + isResolved: thread.isResolved, + isOutdated: thread.line == null, + line: thread.line ?? thread.originalLine ?? undefined, + startLine: thread.startLine ?? thread.originalStartLine ?? undefined + }) + ) : [] ) : [] @@ -181,6 +187,7 @@ const restCommentSchema = z.object({ .object({ login: z.string(), avatar_url: z.string(), type: z.string().optional() }) .nullable(), body: z.string().nullish(), + body_html: z.unknown().optional(), created_at: z.string().optional(), submitted_at: z.string().nullish(), html_url: z.string() @@ -200,6 +207,7 @@ export function parseRestPRComments( author: c.user?.login ?? 'ghost', authorAvatarUrl: c.user?.avatar_url ?? '', body: c.body ?? '', + bodyImageUrls: githubBodyImageUrls(c.body, c.body_html), createdAt: (reviews ? c.submitted_at : c.created_at) ?? '', url: c.html_url, isBot: c.user?.type === 'Bot', diff --git a/src/main/github/client/fetch/pr-review-threads-query.ts b/src/main/github/client/fetch/pr-review-threads-query.ts index d2ba6450133..0e608c43974 100644 --- a/src/main/github/client/fetch/pr-review-threads-query.ts +++ b/src/main/github/client/fetch/pr-review-threads-query.ts @@ -23,6 +23,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt url viewerDidAuthor @@ -44,6 +45,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt url viewerDidAuthor @@ -62,6 +64,7 @@ query($owner: String!, $repo: String!, $pr: Int!) { databaseId author { __typename login avatarUrl(size: 48) } body + bodyHTML createdAt submittedAt url diff --git a/src/main/github/client/map/review-comment-response.ts b/src/main/github/client/map/review-comment-response.ts index f13a69f3632..f17f653ba0e 100644 --- a/src/main/github/client/map/review-comment-response.ts +++ b/src/main/github/client/map/review-comment-response.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls } from '../../body-image-urls' import type { PRComment } from '../../../../shared/github/comment-types' export function mapReviewCommentResponse( data: { @@ -5,6 +6,7 @@ export function mapReviewCommentResponse( node_id?: string | null user: { login: string; avatar_url: string; type?: string } | null body?: string + body_html?: string | null created_at?: string html_url?: string path?: string @@ -22,6 +24,7 @@ export function mapReviewCommentResponse( author: data.user?.login ?? 'You', authorAvatarUrl: data.user?.avatar_url ?? '', body: data.body ?? body, + bodyImageUrls: githubBodyImageUrls(data.body ?? body, data.body_html), createdAt: data.created_at ?? new Date().toISOString(), url: data.html_url ?? '', isBot: data.user?.type === 'Bot', diff --git a/src/main/github/issue-comment-image.test.ts b/src/main/github/issue-comment-image.test.ts new file mode 100644 index 00000000000..c22f437bd88 --- /dev/null +++ b/src/main/github/issue-comment-image.test.ts @@ -0,0 +1,74 @@ +import { expect, it, vi } from 'vitest' +const mocks = vi.hoisted(() => ({ exec: vi.fn() })) +vi.mock('./gh-utils', () => ({ + ghExecFileAsync: mocks.exec, + acquire: async () => {}, + release: () => {}, + classifyGhError: () => ({ type: 'unknown' }) +})) +vi.mock('./github-api-repository', () => ({ + resolveGitHubRepoExecution: async () => ({ + ownerRepo: { owner: 'acme', repo: 'widgets' }, + ghOptions: {} + }) +})) +import { addIssueComment } from './issue-comment' +import { addPRReviewComment, addPRReviewCommentReply } from './client/create/add-pr-review-comment' + +it('returns signed display sources immediately after posting the original Markdown', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + mocks.exec.mockResolvedValue({ + stdout: JSON.stringify({ + id: 1, + user: null, + body, + body_html: + '' + }) + }) + const result = await addIssueComment('/repo', 42, body) + expect(mocks.exec.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') + expect(mocks.exec.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) + expect(result.ok && result.comment.body).toBe(body) + expect(result.ok && result.comment.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) +}) + +it.each(['review', 'reply'])( + 'returns paired image sources immediately for %s posts', + async (kind) => { + mocks.exec.mockClear() + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + mocks.exec.mockResolvedValue({ + stdout: JSON.stringify({ + id: 1, + body, + user: null, + body_html: + '' + }) + }) + const result = + kind === 'review' + ? await addPRReviewComment({ + repoPath: '/repo', + prNumber: 7, + body, + commitId: 'head', + path: 'file.ts', + line: 1 + }) + : await addPRReviewCommentReply('/repo', 7, 1, body) + expect(result.ok && result.comment.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(mocks.exec.mock.calls[0][0]).toContain( + 'body=![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + ) + } +) diff --git a/src/main/github/issue-comment.ts b/src/main/github/issue-comment.ts index 88f5f642c63..7f3c2a11f98 100644 --- a/src/main/github/issue-comment.ts +++ b/src/main/github/issue-comment.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls' import type { GitHubCommentResult, PRComment } from '../../shared/github/comment-types' import type { IssueSourcePreference } from '../../shared/repo-types' import type { LocalGitExecOptions, OwnerRepo } from './gh-utils' @@ -41,6 +42,7 @@ export async function addIssueComment( const { stdout } = await ghExecFileAsync( [ 'api', + ...githubBodyMediaHeaders(body), '-X', 'POST', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}/comments`, @@ -49,14 +51,15 @@ export async function addIssueComment( ], { ...ghOptions, stdin: JSON.stringify({ body }) } ) - const data = JSON.parse(stdout) as { + const data: { id?: number node_id?: string | null user: { login: string; avatar_url: string; type?: string } | null body?: string + body_html?: string | null created_at?: string html_url?: string - } + } = JSON.parse(stdout) if (typeof data.id !== 'number' || !Number.isSafeInteger(data.id) || data.id < 1) { return codeHostFailure('github.unexpectedResponse') } @@ -66,6 +69,7 @@ export async function addIssueComment( author: data.user?.login ?? 'You', authorAvatarUrl: data.user?.avatar_url ?? '', body: data.body ?? body, + bodyImageUrls: githubBodyImageUrls(data.body ?? body, data.body_html), createdAt: data.created_at ?? new Date().toISOString(), url: data.html_url ?? '', isBot: data.user?.type === 'Bot' diff --git a/src/main/github/issue-details-query.ts b/src/main/github/issue-details-query.ts index e22da93d914..5d6921884f0 100644 --- a/src/main/github/issue-details-query.ts +++ b/src/main/github/issue-details-query.ts @@ -14,6 +14,7 @@ export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $numb pageInfo { hasNextPage } } body + bodyHTML assignees(first: 50) { nodes { login avatarUrl(size: 48) ... on User { name } } pageInfo { hasNextPage } @@ -26,6 +27,7 @@ export const ISSUE_DETAILS_QUERY = `query($owner: String!, $repo: String!, $numb nodes { databaseId body + bodyHTML createdAt url viewerDidAuthor @@ -62,13 +64,15 @@ export type GraphQLIssueDetailsResponse = { repository?: { issue?: { body?: string | null + bodyHTML?: unknown assignees?: { nodes?: (Partial | null)[] | null } participants?: { nodes?: GitHubAssignableUser[] } comments?: { pageInfo?: { hasNextPage: boolean } - nodes?: { + nodes?: ({ databaseId?: number | null body?: string | null + bodyHTML?: unknown createdAt?: string | null url?: string | null viewerDidAuthor?: boolean | null @@ -77,10 +81,10 @@ export type GraphQLIssueDetailsResponse = { avatarUrl?: string | null __typename?: string } | null - }[] + } | null)[] } } | null } | null } - errors?: { message?: string }[] + errors?: { message?: string; path?: unknown }[] } diff --git a/src/main/github/issue-update.ts b/src/main/github/issue-update.ts index fa72852bde7..4a5fbe0bb63 100644 --- a/src/main/github/issue-update.ts +++ b/src/main/github/issue-update.ts @@ -9,6 +9,7 @@ import { import { acquire, classifyGhError, ghExecFileAsync, release } from './gh-utils' import { codeHostFailure, combinedClassifiedFailure } from '../../shared/code-host-failure-copy' import type { ClassifiedError } from '../../shared/classified-error' +import { githubBodyImageUrls, githubBodyMediaHeaders } from './body-image-urls' export async function updateIssue( repoPath: string, @@ -18,7 +19,7 @@ export async function updateIssue( localGitOptions: LocalGitExecOptions = {}, preference?: IssueSourcePreference, ownerRepoOverride?: GitHubApiRepository | null -): Promise<{ ok: true } | { ok: false; error: string }> { +): Promise<{ ok: true; bodyImageUrls?: Record } | { ok: false; error: string }> { const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution( repoPath, ownerRepoOverride ?? @@ -40,6 +41,7 @@ export async function updateIssue( const repo = `${ownerRepo.owner}/${ownerRepo.repo}` const errors: ClassifiedError[] = [] + let bodyImageUrls: Record | undefined if (updates.state) { await acquire() @@ -69,17 +71,26 @@ export async function updateIssue( if (updates.body !== undefined) { await acquire() try { - await ghExecFileAsync( + const { stdout } = await ghExecFileAsync( [ 'api', '-X', 'PATCH', `repos/${ownerRepo.owner}/${ownerRepo.repo}/issues/${issueNumber}`, + ...githubBodyMediaHeaders(updates.body), '--input', '-' ], { ...ghOptions, stdin: JSON.stringify({ body: updates.body }) } ) + try { + const response: { body?: string; body_html?: string } = JSON.parse(stdout) + if (response?.body === updates.body) { + bodyImageUrls = githubBodyImageUrls(response.body, response.body_html) + } + } catch { + // Optional display data cannot turn an accepted edit into a failed write. + } } catch (err) { const stderr = err instanceof Error ? err.message : String(err) errors.push(classifyGhError(stderr)) @@ -127,5 +138,5 @@ export async function updateIssue( if (errors.length > 0) { return combinedClassifiedFailure(errors) } - return { ok: true } + return { ok: true, bodyImageUrls } } diff --git a/src/main/github/issue-work-item-details-fresh.test.ts b/src/main/github/issue-work-item-details-fresh.test.ts index 9bdecc5b75b..8d735c87693 100644 --- a/src/main/github/issue-work-item-details-fresh.test.ts +++ b/src/main/github/issue-work-item-details-fresh.test.ts @@ -127,3 +127,104 @@ describe('explicit task refresh conversation reads', () => { await expect(getIssueBodyAndComments('/repo', 42, repository, null, {}, true)).rejects.toThrow() }) }) + +it('pairs issue and comment image sources through collapsed and REST detail reads', async () => { + mocks.exec.mockReset() + mocks.guard.mockReturnValue({ blocked: false }) + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + mocks.exec.mockImplementation(async (args: string[]) => ({ + stdout: JSON.stringify( + args.includes('graphql') + ? { + data: { + repository: { + issue: { + body, + bodyHTML: html, + comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] } + } + } + } + } + : args.some((arg) => arg.includes('/timeline?')) + ? [] + : args.some((arg) => arg.includes('/comments?')) + ? [{ id: 1, user: null, body, body_html: html }] + : { body, body_html: html } + ) + })) + const collapsed = await getIssueDetailsViaGraphQL('/repo', 42, repository) + const rest = await getIssueBodyAndComments('/repo', 42, repository) + for (const details of [collapsed!, rest]) { + expect(details.body).toBe(body) + expect(details.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(details.comments[0].bodyImageUrls).toEqual(details.bodyImageUrls) + } + for (const [args] of mocks.exec.mock.calls.filter(([args]) => + args.some((arg: string) => /\/issues\/42(?:$|\/comments)/.test(arg)) + )) { + expect(args).toContain('Accept: application/vnd.github.full+json') + expect(args).not.toContain('--cache') + } +}) + +it.each(['optional HTML', 'required body', 'pathless', 'rejection without errors'] as const)( + 'admits rejected issue stdout only for available optional HTML failures (%s)', + async (input) => { + mocks.exec.mockReset() + mocks.guard.mockReturnValue({ blocked: false }) + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + const html = + '' + mocks.exec.mockRejectedValueOnce( + Object.assign(new Error('GraphQL failed'), { + stdout: JSON.stringify({ + data: { + repository: { + issue: { + body, + bodyHTML: html, + comments: { + pageInfo: { hasNextPage: false }, + nodes: [{ databaseId: 1, body, bodyHTML: html }] + } + } + } + }, + errors: + input === 'rejection without errors' + ? undefined + : [ + { + path: + input === 'pathless' + ? undefined + : ['repository', 'issue', input === 'required body' ? 'body' : 'bodyHTML'] + } + ] + }) + }) + ) + mocks.exec.mockResolvedValueOnce({ stdout: '[]' }) + const result = await getIssueDetailsViaGraphQL('/repo', 42, repository, null, {}, false, true) + if (input !== 'optional HTML') { + expect(result).toBeNull() + expect(mocks.exec).toHaveBeenCalledTimes(1) + return + } + expect(result?.body).toBe(body) + expect(result?.bodyImageUrls).toBeUndefined() + expect(result?.comments[0].bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + expect(mocks.exec).toHaveBeenCalledTimes(2) + } +) diff --git a/src/main/github/issue-work-item-details.ts b/src/main/github/issue-work-item-details.ts index e12b34ba0f9..7b44631ac7a 100644 --- a/src/main/github/issue-work-item-details.ts +++ b/src/main/github/issue-work-item-details.ts @@ -1,3 +1,9 @@ +import { + GITHUB_BODY_MEDIA_TYPE, + githubBodyImageUrls, + removeFailedGitHubBodyHtml +} from './body-image-urls' +import { extractExecError } from '../git/exec-error' import type { GitHubIssueTimelineItem, PRComment } from '../../shared/github/comment-types' import type { GitHubAssignableUser } from '../../shared/github/pull-request-types' import { @@ -19,6 +25,7 @@ import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from './rate-l export type CollapsedIssueDetails = { item?: MainWorkItem body: string + bodyImageUrls?: Record comments: PRComment[] assignees: string[] assigneeUsers: GitHubAssignableUser[] @@ -47,25 +54,33 @@ export async function getIssueDetailsViaGraphQL( } try { noteRepositoryRateLimitSpend(repository, 'graphql', 1, ghOptions) - const { stdout } = await ghExecFileAsync( - [ - 'api', - 'graphql', - '-f', - `query=${ISSUE_DETAILS_QUERY}`, - '-f', - `owner=${repository.owner}`, - '-f', - `repo=${repository.repo}`, - '-F', - `number=${issueNumber}`, - '-F', - `includeItem=${includeItem}` - ], - ghOptions - ) - const parsed = JSON.parse(stdout) as GraphQLIssueDetailsResponse - if (parsed.errors && parsed.errors.length > 0) { + let stdout: string + let rejected = false + try { + ;({ stdout } = await ghExecFileAsync( + [ + 'api', + 'graphql', + '-f', + `query=${ISSUE_DETAILS_QUERY}`, + '-f', + `owner=${repository.owner}`, + '-f', + `repo=${repository.repo}`, + '-F', + `number=${issueNumber}`, + '-F', + `includeItem=${includeItem}` + ], + ghOptions + )) + } catch (error) { + stdout = extractExecError(error).stdout + rejected = true + } + const parsed: GraphQLIssueDetailsResponse = JSON.parse(stdout) + const errors = removeFailedGitHubBodyHtml(parsed.data, parsed.errors) + if (errors?.length || (rejected && !parsed.errors?.length)) { return null } const issue = parsed.data?.repository?.issue @@ -85,12 +100,15 @@ export async function getIssueDetailsViaGraphQL( return null } const comments: PRComment[] = (issue.comments?.nodes ?? []) - .filter((comment) => typeof comment.databaseId === 'number') + .filter( + (comment): comment is NonNullable => typeof comment?.databaseId === 'number' + ) .map((comment) => ({ id: comment.databaseId as number, author: comment.author?.login ?? 'ghost', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body ?? '', + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: comment.createdAt ?? '', url: comment.url ?? '', isBot: comment.author?.__typename === 'Bot', @@ -112,7 +130,7 @@ export async function getIssueDetailsViaGraphQL( name: user.name ?? null, avatarUrl: user.avatarUrl ?? '' })) - return { + const details: CollapsedIssueDetails = { ...(itemData?.success ? { item: mapIssueWorkItem({ @@ -125,12 +143,14 @@ export async function getIssueDetailsViaGraphQL( } : {}), body: issue.body ?? '', + bodyImageUrls: githubBodyImageUrls(issue.body, issue.bodyHTML), comments, assignees: assigneeUsers.map((assignee) => assignee.login), assigneeUsers, participants, timelineItems: await getIssueTimelineItems(repository, issueNumber, ghOptions, fresh) } + return details } catch { return null } @@ -143,7 +163,9 @@ export async function getIssueBodyAndComments( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {}, fresh = false -): Promise> { +): Promise< + Pick +> { const ghOptions = { ...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)), ...githubHostExecOptions(repository) @@ -161,7 +183,8 @@ export async function getIssueBodyAndComments( ghExecFileAsync( [ 'api', - ...(fresh ? [] : ['--cache', '60s']), + '-H', + GITHUB_BODY_MEDIA_TYPE, `repos/${repository.owner}/${repository.repo}/issues/${issueNumber}` ], ghOptions @@ -169,7 +192,8 @@ export async function getIssueBodyAndComments( ghExecFileAsync( [ 'api', - ...(fresh ? [] : ['--cache', '60s']), + '-H', + GITHUB_BODY_MEDIA_TYPE, ...(fresh ? ['--paginate', '--slurp'] : []), `repos/${repository.owner}/${repository.repo}/issues/${issueNumber}/comments?per_page=100` ], @@ -178,14 +202,16 @@ export async function getIssueBodyAndComments( getIssueTimelineItems(repository, issueNumber, ghOptions, fresh), readViewerLogin(ghOptions) ]) - const issue = JSON.parse(issueResult.stdout) as { + const issue: { body?: string | null + body_html?: unknown assignees?: { login: string }[] - } + } = JSON.parse(issueResult.stdout) type RESTComment = { id: number user: { login: string; avatar_url: string; type?: string } | null body: string + body_html?: unknown created_at: string html_url: string } @@ -199,17 +225,20 @@ export async function getIssueBodyAndComments( author: comment.user?.login ?? 'ghost', authorAvatarUrl: comment.user?.avatar_url ?? '', body: comment.body ?? '', + bodyImageUrls: githubBodyImageUrls(comment.body, comment.body_html), createdAt: comment.created_at, url: comment.html_url, isBot: comment.user?.type === 'Bot', ...viewerAuthorship(comment.user?.login, viewerLogin) })) - return { + const details = { body: issue.body ?? '', + bodyImageUrls: githubBodyImageUrls(issue.body, issue.body_html), comments, assignees: (issue.assignees ?? []).map((assignee) => assignee.login), timelineItems } + return details } if (connectionId) { // A connection-backed lookup must not use ambient local GH_REPO/GH_HOST. diff --git a/src/main/github/issues.test.ts b/src/main/github/issues.test.ts index 55862e1f0a1..3beaf260cd7 100644 --- a/src/main/github/issues.test.ts +++ b/src/main/github/issues.test.ts @@ -216,6 +216,56 @@ describe('issue source operations', () => { ) }) + it('keeps the accepted issue body representation through a compound metadata edit', async () => { + const body = + '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + body, + body_html: + '' + }) + }) + .mockResolvedValueOnce({ stdout: '' }) + await expect(updateIssue('/repo-root', 924, { body, title: 'Updated' })).resolves.toEqual({ + ok: true, + bodyImageUrls: { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + } + }) + expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( + 'Accept: application/vnd.github.full+json' + ) + expect(ghExecFileAsyncMock.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) + }) + + it.each([ + '', + 'not JSON', + JSON.stringify({ + body: 'different ![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)', + body_html: + '' + }) + ])( + 'keeps an accepted issue edit successful without a usable paired response (%s)', + async (stdout) => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout }) + await expect( + updateIssue('/repo-root', 924, { + body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + }) + ).resolves.toEqual({ + ok: true, + bodyImageUrls: undefined + }) + } + ) + it('reports a failed close whose gh error mentions "already"', async () => { getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) ghExecFileAsyncMock.mockRejectedValueOnce( diff --git a/src/main/github/project-view/body-image-mutations.test.ts b/src/main/github/project-view/body-image-mutations.test.ts new file mode 100644 index 00000000000..53c0925b77f --- /dev/null +++ b/src/main/github/project-view/body-image-mutations.test.ts @@ -0,0 +1,170 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + acquireMock, + ghExecFileAsyncMock, + noteRepositoryRateLimitSpendMock, + projectHostAuthenticationErrorMock, + repositoryRateLimitGuardMock, + releaseMock, + runGraphqlMock, + runRestMock +} = vi.hoisted(() => ({ + acquireMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + noteRepositoryRateLimitSpendMock: vi.fn(), + projectHostAuthenticationErrorMock: vi.fn(), + repositoryRateLimitGuardMock: vi.fn(), + releaseMock: vi.fn(), + runGraphqlMock: vi.fn(), + runRestMock: vi.fn() +})) + +vi.mock('./internals', () => ({ + acquire: acquireMock, + release: releaseMock, + extractExecError: (err: unknown) => ({ + stderr: err instanceof Error ? err.message : String(err), + stdout: '' + }), + ghExecFileAsync: ghExecFileAsyncMock, + rateLimitGuard: () => ({ blocked: false }), + noteRateLimitSpend: vi.fn(), + repositoryRateLimitGuard: repositoryRateLimitGuardMock, + noteRepositoryRateLimitSpend: noteRepositoryRateLimitSpendMock, + projectHostAuthenticationError: projectHostAuthenticationErrorMock, + projectGhExecOptions: (host?: string) => ({ host: host ?? 'github.com' }), + classifyProjectError: (stderr: string) => ({ type: 'unknown', message: stderr }), + rateLimitedError: () => ({ type: 'rate_limited', message: 'rate limited' }), + runGraphql: runGraphqlMock, + runRest: runRestMock, + validateSlugArgs: (owner: string, repo: string) => + owner && repo ? { ok: true } : { ok: false, error: { type: 'validation_error' } }, + assertPositiveInt: (value: number, name: string) => + Number.isInteger(value) && value > 0 + ? { ok: true, value } + : { ok: false, error: { type: 'validation_error', message: `${name} invalid` } } +})) + +import { updateIssueBySlug } from './mutations' +import { updatePullRequestBySlug } from './pull-request-mutation' +import { addIssueCommentBySlug } from './issue-comment-mutations' + +describe('Project accepted body representations', () => { + beforeEach(() => { + acquireMock.mockReset().mockResolvedValue(undefined) + ghExecFileAsyncMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' }) + noteRepositoryRateLimitSpendMock.mockReset() + projectHostAuthenticationErrorMock.mockReset().mockResolvedValue(null) + repositoryRateLimitGuardMock.mockReset().mockReturnValue({ blocked: false }) + releaseMock.mockReset() + runRestMock.mockReset().mockResolvedValue({ ok: true, data: {} }) + }) + + it.each([updateIssueBySlug, updatePullRequestBySlug])( + 'returns paired image sources after a body edit', + async (update) => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: { + body, + body_html: + '' + } + }) + const result = await update({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } }) + expect(result).toEqual({ + ok: true, + bodyImageUrls: { + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + } + }) + expect(runRestMock.mock.calls[0][0]).toContain(`body=${body}`) + expect(runRestMock.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') + } + ) + + it('returns the paired source for a newly posted Project comment', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: { + id: 1, + body, + body_html: + '' + } + }) + const result = await addIssueCommentBySlug({ owner: 'acme', repo: 'widgets', number: 12, body }) + expect(result.ok && result.comment.bodyImageUrls).toEqual({ + 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': + 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' + }) + }) + + it('does not attach a Project issue map from a different accepted body snapshot', async () => { + const body = + '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: { + body: `${body}\nchanged elsewhere`, + body_html: + '' + } + }) + await expect( + updateIssueBySlug({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } }) + ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) + }) + + it('keeps an accepted PR body save successful without an optional representation', async () => { + runRestMock.mockResolvedValueOnce({ ok: true, data: null }) + await expect( + updatePullRequestBySlug({ + owner: 'acme', + repo: 'widgets', + number: 12, + updates: { + body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + } + }) + ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) + }) + + it.each([null, true])( + 'finishes a Project compound save with unusable optional HTML (%s)', + async (html) => { + const body = + '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' + runRestMock.mockResolvedValueOnce({ + ok: true, + data: html === null ? null : { body, body_html: html } + }) + await expect( + updateIssueBySlug({ + owner: 'acme', + repo: 'widgets', + number: 12, + updates: { body, addLabels: ['saved-label'] } + }) + ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) + expect(runRestMock).toHaveBeenCalledWith( + [ + '-X', + 'POST', + 'repos/acme/widgets/issues/12/labels', + '--raw-field', + 'labels[]=saved-label' + ], + undefined, + 'core', + { host: 'github.com' } + ) + } + ) +}) diff --git a/src/main/github/project-view/issue-comment-mutations.ts b/src/main/github/project-view/issue-comment-mutations.ts index fa16455e66d..61dd68d32b9 100644 --- a/src/main/github/project-view/issue-comment-mutations.ts +++ b/src/main/github/project-view/issue-comment-mutations.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals' import type { PRComment } from '../../../shared/github/comment-types' import type { @@ -14,6 +15,7 @@ type RawIssueCommentResponse = { id?: number user?: { login?: string; avatar_url?: string; type?: string } | null body?: string + body_html?: string | null created_at?: string html_url?: string } @@ -24,6 +26,7 @@ function mapIssueComment(data: RawIssueCommentResponse, fallbackBody: string): P author: data.user?.login ?? 'You', authorAvatarUrl: data.user?.avatar_url ?? '', body: data.body ?? fallbackBody, + bodyImageUrls: githubBodyImageUrls(data.body ?? fallbackBody, data.body_html), createdAt: data.created_at ?? new Date().toISOString(), url: data.html_url ?? '', isBot: data.user?.type === 'Bot' @@ -55,6 +58,7 @@ export async function addIssueCommentBySlug( [ '-X', 'POST', + ...githubBodyMediaHeaders(args.body), `repos/${args.owner}/${args.repo}/issues/${args.number}/comments`, '--raw-field', `body=${args.body}` diff --git a/src/main/github/project-view/mutations.ts b/src/main/github/project-view/mutations.ts index 7388f7a3f99..4c31ac3a522 100644 --- a/src/main/github/project-view/mutations.ts +++ b/src/main/github/project-view/mutations.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' import { acquire, assertPositiveInt, @@ -46,15 +47,16 @@ export async function updateIssueBySlug( return stateResult } const { title, body } = args.updates + let bodyImageUrls: Record | undefined if (title !== undefined || body !== undefined) { const patchArgs = ['-X', 'PATCH', base] if (title !== undefined) { patchArgs.push('--raw-field', `title=${title}`) } if (body !== undefined) { - patchArgs.push('--raw-field', `body=${body}`) + patchArgs.push(...githubBodyMediaHeaders(body), '--raw-field', `body=${body}`) } - const result = await runRest( + const result = await runRest<{ body?: string; body_html?: string }>( patchArgs, undefined, 'core', @@ -63,12 +65,20 @@ export async function updateIssueBySlug( if (!result.ok) { return { ok: false, error: result.error } } + try { + if (body !== undefined && result.data?.body === body) { + bodyImageUrls = githubBodyImageUrls(body, result.data.body_html) + } + } catch { + // Optional display data cannot turn an accepted edit into a failed write. + } } const labelResult = await updateIssueLabels(args, base) if (!labelResult.ok) { return labelResult } - return updateIssueAssignees(args, base) + const assigneeResult = await updateIssueAssignees(args, base) + return assigneeResult.ok ? { ok: true, bodyImageUrls } : assigneeResult } function validateDuplicateUpdate(args: UpdateIssueBySlugArgs): GitHubProjectMutationResult | null { diff --git a/src/main/github/project-view/pull-request-mutation.ts b/src/main/github/project-view/pull-request-mutation.ts index 7a49d9cbf0e..def6756c126 100644 --- a/src/main/github/project-view/pull-request-mutation.ts +++ b/src/main/github/project-view/pull-request-mutation.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, githubBodyMediaHeaders } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runRest, validateSlugArgs } from './internals' import type { GitHubProjectMutationResult } from '../../../shared/github/project-result-types' import type { UpdatePullRequestBySlugArgs } from '../../../shared/github/project-request-types' @@ -30,7 +31,11 @@ export async function updatePullRequestBySlug( fieldCount++ } if (args.updates.body !== undefined) { - patchArgs.push('--raw-field', `body=${args.updates.body}`) + patchArgs.push( + ...githubBodyMediaHeaders(args.updates.body), + '--raw-field', + `body=${args.updates.body}` + ) fieldCount++ } if (args.updates.state !== undefined) { @@ -40,11 +45,19 @@ export async function updatePullRequestBySlug( if (fieldCount === 0) { return { ok: true } } - const result = await runRest( + const result = await runRest<{ body?: string; body_html?: string }>( patchArgs, undefined, 'core', projectGhExecOptions(args.host) ) - return result.ok ? { ok: true } : { ok: false, error: result.error } + return result.ok + ? { + ok: true, + bodyImageUrls: + args.updates.body !== undefined + ? githubBodyImageUrls(result.data?.body ?? args.updates.body, result.data?.body_html) + : undefined + } + : { ok: false, error: result.error } } diff --git a/src/main/github/project-view/work-item-details.ts b/src/main/github/project-view/work-item-details.ts index e09a8a038cb..6323f722a13 100644 --- a/src/main/github/project-view/work-item-details.ts +++ b/src/main/github/project-view/work-item-details.ts @@ -1,3 +1,4 @@ +import { githubBodyImageUrls, removeFailedGitHubBodyHtml } from '../body-image-urls' import { assertPositiveInt, projectGhExecOptions, runGraphql, validateSlugArgs } from './internals' import type { PRComment } from '../../../shared/github/comment-types' import type { GitHubAssignableUser } from '../../../shared/github/pull-request-types' @@ -11,6 +12,7 @@ type RawComment = { databaseId?: number author?: { login?: string; avatarUrl?: string; __typename?: string } | null body?: string + bodyHTML?: unknown createdAt?: string url?: string } @@ -24,6 +26,7 @@ type RawWorkItemContent = { isDraft?: boolean updatedAt?: string body?: string + bodyHTML?: unknown headRefName?: string baseRefName?: string author?: { login?: string } | null @@ -33,6 +36,13 @@ type RawWorkItemContent = { comments?: { nodes?: (RawComment | null)[] } } +type RawWorkItemDetailsResponse = { + repository?: { + issue?: RawWorkItemContent | null + pullRequest?: RawWorkItemContent | null + } | null +} + export async function getWorkItemDetailsBySlug( args: ProjectWorkItemDetailsBySlugArgs ): Promise { @@ -51,49 +61,63 @@ export async function getWorkItemDetailsBySlug( } } const contentFragment = args.type === 'issue' ? ISSUE_FRAGMENT : PULL_REQUEST_FRAGMENT - const result = await runGraphql<{ - repository?: { - issue?: RawWorkItemContent | null - pullRequest?: RawWorkItemContent | null - } | null - }>( + const result = await runGraphql( `query($owner:String!, $repo:String!, $num:Int!) { repository(owner:$owner, name:$repo) { ${contentFragment} } }`, { owner: args.owner, repo: args.repo, num: args.number }, projectGhExecOptions(args.host) ) - if (!result.ok) { + let data: RawWorkItemDetailsResponse | undefined + if (result.ok) { + data = result.data + } else { + try { + const response: { data?: RawWorkItemDetailsResponse; errors?: unknown[] } = JSON.parse( + result.raw.stdout + ) + if ( + !response.errors?.length || + removeFailedGitHubBodyHtml(response.data, response.errors)?.length + ) { + return { ok: false, error: result.error } + } + data = response.data + } catch { + return { ok: false, error: result.error } + } + } + const raw = args.type === 'issue' ? data?.repository?.issue : data?.repository?.pullRequest + if (!result.ok && typeof raw?.body !== 'string') { return { ok: false, error: result.error } } - const raw = - args.type === 'issue' ? result.data.repository?.issue : result.data.repository?.pullRequest if (!raw) { return { ok: false, error: { type: 'not_found', message: 'Item not found.', reason: 'item_not_found' } } } - return { ok: true, details: mapWorkItemDetails(raw, args) } + const details = mapWorkItemDetails(raw, args) + return { ok: true, details } } const ISSUE_FRAGMENT = `issue(number:$num) { - id number title url state stateReason updatedAt body author { login } + id number title url state stateReason updatedAt body bodyHTML author { login } labels(first:50) { nodes { name } } assignees(first:50) { nodes { login } } participants(first:50) { nodes { login name avatarUrl } } comments(first:100) { - nodes { databaseId author { login avatarUrl __typename } body createdAt url } + nodes { databaseId author { login avatarUrl __typename } body bodyHTML createdAt url } } }` const PULL_REQUEST_FRAGMENT = `pullRequest(number:$num) { - id number title url state isDraft updatedAt headRefName baseRefName body author { login } + id number title url state isDraft updatedAt headRefName baseRefName body bodyHTML author { login } labels(first:50) { nodes { name } } assignees(first:50) { nodes { login } } participants(first:50) { nodes { login name avatarUrl } } comments(first:100) { - nodes { databaseId author { login avatarUrl __typename } body createdAt url } + nodes { databaseId author { login avatarUrl __typename } body bodyHTML createdAt url } } }` @@ -117,6 +141,7 @@ function mapWorkItemDetails( author: comment.author?.login ?? '', authorAvatarUrl: comment.author?.avatarUrl ?? '', body: comment.body, + bodyImageUrls: githubBodyImageUrls(comment.body, comment.bodyHTML), createdAt: typeof comment.createdAt === 'string' ? comment.createdAt : '', url: typeof comment.url === 'string' ? comment.url : '', isBot: comment.author?.__typename === 'Bot' @@ -161,6 +186,7 @@ function mapWorkItemDetails( args.type === 'pr' && typeof raw.baseRefName === 'string' ? raw.baseRefName : undefined }, body: typeof raw.body === 'string' ? raw.body : '', + bodyImageUrls: githubBodyImageUrls(raw.body, raw.bodyHTML), comments, participants, assignees diff --git a/src/main/github/pull-request-file-data.ts b/src/main/github/pull-request-file-data.ts index d6c42f0b392..e4406581f91 100644 --- a/src/main/github/pull-request-file-data.ts +++ b/src/main/github/pull-request-file-data.ts @@ -1,3 +1,4 @@ +import { GITHUB_BODY_MEDIA_TYPE, githubBodyImageUrls } from './body-image-urls' import type { GitHubPRFile } from '../../shared/github/pull-request-types' import type { PRFileViewedStatesResult } from './pull-request-detail-context' import { ghExecFileAsync, ghRepoExecOptions, githubRepoContext } from './gh-utils' @@ -49,7 +50,12 @@ export async function getPRMetadata( repository: GitHubApiRepository | null, connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} -): Promise<{ body: string; headSha?: string; baseSha?: string }> { +): Promise<{ + body: string + bodyImageUrls?: Record + headSha?: string + baseSha?: string +}> { if (!repository) { return { body: '' } } @@ -63,19 +69,27 @@ export async function getPRMetadata( try { noteRepositoryRateLimitSpend(repository, 'core', 1, ghOptions) const { stdout } = await ghExecFileAsync( - ['api', '--cache', '60s', `repos/${repository.owner}/${repository.repo}/pulls/${prNumber}`], + [ + 'api', + '-H', + GITHUB_BODY_MEDIA_TYPE, + `repos/${repository.owner}/${repository.repo}/pulls/${prNumber}` + ], ghOptions ) - const data = JSON.parse(stdout) as { + const data: { body?: string | null + body_html?: unknown head?: { sha?: string } base?: { sha?: string } - } - return { + } = JSON.parse(stdout) + const metadata = { body: data.body ?? '', + bodyImageUrls: githubBodyImageUrls(data.body, data.body_html), ...(data.head?.sha ? { headSha: data.head.sha } : {}), ...(data.base?.sha ? { baseSha: data.base.sha } : {}) } + return metadata } catch { return { body: '' } } diff --git a/src/main/github/work-item-details.ts b/src/main/github/work-item-details.ts index 4c94c58a912..3db15194c9e 100644 --- a/src/main/github/work-item-details.ts +++ b/src/main/github/work-item-details.ts @@ -156,29 +156,31 @@ export async function getWorkItemDetails( ...collapsed.assigneeUsers ]), body: collapsed.body, + bodyImageUrls: collapsed.bodyImageUrls, comments: collapsed.comments, assignees: item.assignees?.map((user) => user.login) ?? collapsed.assignees, participants: collapsed.participants, timelineItems: collapsed.timelineItems } } - const [{ body, comments, assignees, timelineItems }, participants] = await Promise.all([ - getIssueBodyAndComments( - repoPath, - item.number, - resolvedRepository, - connectionId, - localGitOptions, - canonical - ), - getWorkItemParticipants( - repoPath, - item, - resolvedRepository, - connectionId, - localGitOptions - ) - ]) + const [{ body, bodyImageUrls, comments, assignees, timelineItems }, participants] = + await Promise.all([ + getIssueBodyAndComments( + repoPath, + item.number, + resolvedRepository, + connectionId, + localGitOptions, + canonical + ), + getWorkItemParticipants( + repoPath, + item, + resolvedRepository, + connectionId, + localGitOptions + ) + ]) const mentionParticipants = await getMentionParticipants( repoPath, item, @@ -191,6 +193,7 @@ export async function getWorkItemDetails( return { item: enrichItemDisplayAvatars(item, mentionParticipants), body, + bodyImageUrls, comments, assignees: item.assignees?.map((user) => user.login) ?? assignees, participants: mentionParticipants, @@ -256,6 +259,7 @@ export async function getWorkItemDetails( mentionParticipants ), body: metadata.body, + bodyImageUrls: metadata.bodyImageUrls, comments, headSha: metadata.headSha, baseSha: metadata.baseSha, diff --git a/src/main/ipc/browser/desktop-browser-bridge-host-control.ts b/src/main/ipc/browser/desktop-browser-bridge-host-control.ts index b08a157517b..7703fbc38da 100644 --- a/src/main/ipc/browser/desktop-browser-bridge-host-control.ts +++ b/src/main/ipc/browser/desktop-browser-bridge-host-control.ts @@ -8,7 +8,7 @@ import { } from '../../../shared/desktop-browser-bridge-host-control-contract' import type { GlobalSettings } from '../../../shared/global-settings-types' import type { SshTarget } from '../../../shared/ssh-types' -import { isRuntimeOwnedSshTarget } from '../../ssh/connection/ssh-connection-store' +import { isRuntimeOwnedSshTarget } from '../../ssh/targets/ssh-target-runtime-ownership' import { setDesktopBrowserBridgeHostStopped } from './desktop-browser-bridge-reconcile' /** Old entries fall off so runtime-created hosts cannot grow the list without bound. */ diff --git a/src/main/ipc/filesystem/filesystem-mutations.test.ts b/src/main/ipc/filesystem/filesystem-mutations.test.ts index c38aeaa1b8b..cea6a25543c 100644 --- a/src/main/ipc/filesystem/filesystem-mutations.test.ts +++ b/src/main/ipc/filesystem/filesystem-mutations.test.ts @@ -29,7 +29,7 @@ vi.mock('fs/promises', () => ({ })) import { registerFilesystemMutationHandlers } from './filesystem-mutations' -import { resetSshConnectionGenerations } from '../../ssh/connection/ssh-connection-generation' +import { resetSshConnectionGenerations } from '../../ssh/connection/authority/ssh-connection-generation' // Resolve fixture paths like production to preserve cross-platform comparisons. const REPO_PATH = path.resolve('/workspace/repo') diff --git a/src/main/ipc/filesystem/filesystem-mutations.ts b/src/main/ipc/filesystem/filesystem-mutations.ts index 70994692913..934e356887e 100644 --- a/src/main/ipc/filesystem/filesystem-mutations.ts +++ b/src/main/ipc/filesystem/filesystem-mutations.ts @@ -12,7 +12,7 @@ import type { LocalFileAccess } from '../../../shared/file-access/local-file-acc import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { resolveLocalDroppedPathsForAgent } from '../dropped-path-resolution' import type { SshMutationExpectation } from '../../../shared/ssh-types' -import { assertSshMutationExpectation } from '../../ssh/connection/ssh-connection-generation' +import { assertSshMutationExpectation } from '../../ssh/connection/authority/ssh-connection-generation' import { renameLocalPathSerializedByDestination } from '../../filesystem/destination-serialized-local-rename' import { assertNotExists, rethrowWithUserMessage } from './filesystem-create-path-guards' import type { diff --git a/src/main/ipc/filesystem/filesystem-write-handlers.ts b/src/main/ipc/filesystem/filesystem-write-handlers.ts index 8d3ca40b258..1d257c9e046 100644 --- a/src/main/ipc/filesystem/filesystem-write-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-write-handlers.ts @@ -1,7 +1,7 @@ import { ipcMain, shell } from 'electron' import { lstat, rm, writeFile } from 'node:fs/promises' import type { SshMutationExpectation } from '../../../shared/ssh-types' -import { assertSshMutationExpectation } from '../../ssh/connection/ssh-connection-generation' +import { assertSshMutationExpectation } from '../../ssh/connection/authority/ssh-connection-generation' import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' import { tryDeleteWslUncPath } from '../../wsl/filesystem/wsl-unc-delete' import type { LocalFileAccess } from '../../../shared/file-access/local-file-access' diff --git a/src/main/ssh/connection/ssh-expired-lease-pane-readoption.test.ts b/src/main/ipc/pty/pane/ssh-expired-lease-pane-readoption.test.ts similarity index 86% rename from src/main/ssh/connection/ssh-expired-lease-pane-readoption.test.ts rename to src/main/ipc/pty/pane/ssh-expired-lease-pane-readoption.test.ts index 7ef799ea918..8c7f43ddbd5 100644 --- a/src/main/ssh/connection/ssh-expired-lease-pane-readoption.test.ts +++ b/src/main/ipc/pty/pane/ssh-expired-lease-pane-readoption.test.ts @@ -2,17 +2,17 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { resolvePersistedStablePaneOwner } from '../../ipc/pty/pane/stable-owner' -import { adoptStablePane } from '../../ipc/pty/pane/adopt-stable' -import { PtyHostNotDispatchableError } from '../../ipc/pty/provider/registry' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { resolvePersistedStablePaneOwner } from './stable-owner' +import { adoptStablePane } from './adopt-stable' +import { PtyHostNotDispatchableError } from '../provider/registry' import { testState, createStoreWithSshRemotePtyLeases -} from '../../persistence/persistence-test-harness' -import { makeTerminalTab, TEST_LEAF_1 } from '../../persistence/persistence-session-fixtures' +} from '../../../persistence/persistence-test-harness' +import { makeTerminalTab, TEST_LEAF_1 } from '../../../persistence/persistence-session-fixtures' -import { PtyExitProof } from '../../pty/process-retirement/pty-exit-proof' +import { PtyExitProof } from '../../../pty/process-retirement/pty-exit-proof' vi.mock('electron', () => ({ app: { getPath: () => testState.dir }, diff --git a/src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts b/src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts index 00eba5477c0..b09ca853efe 100644 --- a/src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts +++ b/src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts @@ -4,7 +4,7 @@ import type { SshRemotePtyLease } from '../../../../shared/ssh-types' import { closeLegacyRelayPane, installLegacyRelayBridge -} from '../../../ssh/legacy-relay/legacy-relay-bridge-registry' +} from '../../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry' import { stopRendererOwnedPty, type PtyKillIpcDeps } from '../ipc/renderer-kill' const TARGET = 'ssh-box' diff --git a/src/main/ipc/pty/runtime/kill.ts b/src/main/ipc/pty/runtime/kill.ts index e0d023a6cda..5a4265aea40 100644 --- a/src/main/ipc/pty/runtime/kill.ts +++ b/src/main/ipc/pty/runtime/kill.ts @@ -19,7 +19,7 @@ import { closeLegacyRelayPane, isLegacyRelayBridgedPty, stopLegacyRelayPaneAndWait -} from '../../../ssh/legacy-relay/legacy-relay-bridge-registry' +} from '../../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry' // Bounds the wait for an observed exit to reach the runtime record when the caller set no deadline. const OBSERVED_EXIT_RECORD_WAIT_MS = 10_000 diff --git a/src/main/ipc/renderer-shutdown-checkpoint.ts b/src/main/ipc/renderer-shutdown-checkpoint.ts index 08f708fa933..b0fb0a9b5e0 100644 --- a/src/main/ipc/renderer-shutdown-checkpoint.ts +++ b/src/main/ipc/renderer-shutdown-checkpoint.ts @@ -9,7 +9,7 @@ import { applyCommandToSession } from '../persistence/terminal-topology/terminal import type { PersistedUIState } from '../../shared/persisted-ui-state-types' import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' import type { Store } from '../persistence/loading-store/store' -import { isFrozenOrcadSourceSessionPartition } from '../ssh/orcad-retained-source' +import { isFrozenOrcadSourceSessionPartition } from '../persistence/migrating-orcad-catalog/orcad-source-visibility' import { isWslMoveWindowWriteHeld } from '../persistence/moving-wsl-projects/wsl-move-window-write-hold' import { windowViewSaveForMain, type ReconnectFactsFor } from '../persistence/window-save-view' import { reportWindowSaveDrift } from '../persistence/window-save-divergence' diff --git a/src/main/ipc/repos-execution-host-catalog.test.ts b/src/main/ipc/repos-execution-host-catalog.test.ts index 3bfc66e405f..301376c8904 100644 --- a/src/main/ipc/repos-execution-host-catalog.test.ts +++ b/src/main/ipc/repos-execution-host-catalog.test.ts @@ -48,7 +48,7 @@ vi.mock('../workspaces/creation/worktree-root-preparation', () => import { registerRepoHandlers } from './repos' import { clearGitCapabilityStateForTests } from '../git/command-runner/git-capability-state' -import { resetSshProviderAuthorities } from '../ssh/ssh-provider-authority' +import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority' import { getGitRepoRoot, isGitRepo } from '../git/repo' import { createRepoHandlerHarness, resetProjectGroupMocks } from './repos-remote-test-harness' import { mkdtempSync, rmSync } from 'node:fs' diff --git a/src/main/ipc/repos-nested-import.test.ts b/src/main/ipc/repos-nested-import.test.ts index f113ec4b0b4..f70d1a9bae3 100644 --- a/src/main/ipc/repos-nested-import.test.ts +++ b/src/main/ipc/repos-nested-import.test.ts @@ -51,7 +51,7 @@ vi.mock('../workspaces/creation/worktree-root-preparation', () => import { registerRepoHandlers } from './repos' import { clearGitCapabilityStateForTests } from '../git/command-runner/git-capability-state' -import { resetSshProviderAuthorities } from '../ssh/ssh-provider-authority' +import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority' import { getGitRepoRoot, isGitRepo } from '../git/repo' import { createRepoHandlerHarness, resetProjectGroupMocks } from './repos-remote-test-harness' diff --git a/src/main/ipc/repos-nested-scan.test.ts b/src/main/ipc/repos-nested-scan.test.ts index 15ae074c798..119156cbb34 100644 --- a/src/main/ipc/repos-nested-scan.test.ts +++ b/src/main/ipc/repos-nested-scan.test.ts @@ -51,7 +51,7 @@ vi.mock('../workspaces/creation/worktree-root-preparation', () => import { registerRepoHandlers } from './repos' import { clearGitCapabilityStateForTests } from '../git/command-runner/git-capability-state' -import { resetSshProviderAuthorities } from '../ssh/ssh-provider-authority' +import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority' import { getGitRepoRoot, isGitRepo } from '../git/repo' import { createRepoHandlerHarness, resetProjectGroupMocks } from './repos-remote-test-harness' diff --git a/src/main/ipc/repos/folder-workspace-handlers.ts b/src/main/ipc/repos/folder-workspace-handlers.ts index a0404646ff2..84eca8181bc 100644 --- a/src/main/ipc/repos/folder-workspace-handlers.ts +++ b/src/main/ipc/repos/folder-workspace-handlers.ts @@ -16,7 +16,7 @@ import { FolderWorkspaceUpdateArgs, parseProjectGroupIpcArgs } from './repo-ipc-arg-schemas' -import { visibleFolderWorkspaces } from '../../ssh/orcad-retained-source' +import { visibleFolderWorkspaces } from '../../persistence/migrating-orcad-catalog/orcad-source-visibility' import { createFolderWorkspaceWithPluginHooks } from '../../plugins/hooks/workspace-create-plugin-hook' import { isLocalWslMoveRow, diff --git a/src/main/ipc/repos/project-group-handlers.ts b/src/main/ipc/repos/project-group-handlers.ts index 958a1acf148..1dd1ccfe7e4 100644 --- a/src/main/ipc/repos/project-group-handlers.ts +++ b/src/main/ipc/repos/project-group-handlers.ts @@ -19,7 +19,7 @@ import { assertWslMoveRepoWritable } from '../../persistence/moving-wsl-projects/wsl-move-scope-guard' import { activeNestedRepoScans, runNestedRepoScanForIpc } from './nested-repo-scan-ipc' -import { visibleProjectGroups } from '../../ssh/orcad-retained-source' +import { visibleProjectGroups } from '../../persistence/migrating-orcad-catalog/orcad-source-visibility' export function registerProjectGroupHandlers(mainWindow: BrowserWindow, store: Store): void { ipcMain.handle('projectGroups:list', () => visibleProjectGroups(store)) diff --git a/src/main/ipc/repos/repo-catalog-handlers.ts b/src/main/ipc/repos/repo-catalog-handlers.ts index ed27791cebc..8142efccef8 100644 --- a/src/main/ipc/repos/repo-catalog-handlers.ts +++ b/src/main/ipc/repos/repo-catalog-handlers.ts @@ -13,7 +13,10 @@ import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered- import { notifyReposChanged } from './repos-changed-notification' import { scheduleCurrentWorktreeBaseDirectoryWatcherSync } from '../worktrees/creation/worktree-base-directory-watcher' import { ProjectUpdateIpcArgs, parseProjectGroupIpcArgs } from './repo-ipc-arg-schemas' -import { visibleProjectHostSetups, visibleRepos } from '../../ssh/orcad-retained-source' +import { + visibleProjectHostSetups, + visibleRepos +} from '../../persistence/migrating-orcad-catalog/orcad-source-visibility' import { assertWslMoveProjectWritable, assertWslMoveReposWritable, diff --git a/src/main/ipc/runtime-environments/managed-orcad-actions.ts b/src/main/ipc/runtime-environments/managed-orcad-actions.ts index e9e6e850053..f56124684a0 100644 --- a/src/main/ipc/runtime-environments/managed-orcad-actions.ts +++ b/src/main/ipc/runtime-environments/managed-orcad-actions.ts @@ -5,11 +5,9 @@ import { stopManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-runtime-decommission' import { getManagedOrcadRuntimeStatus } from '../../managed-server/lifecycle/orcad-runtime-status' -import { - recoverManagedOrcadEnvironment, - rollbackManagedOrcadEnvironment, - updateManagedOrcadEnvironment -} from '../../ssh/orcad-runtime-maintenance' +import { recoverManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-managed-recovery' +import { rollbackManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-managed-rollback' +import { updateManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-runtime-maintenance' import { getOrcadSshDeployment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import type { diff --git a/src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts b/src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts index 54ab1409bd8..38b957d8f69 100644 --- a/src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts +++ b/src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts @@ -7,14 +7,17 @@ import type { import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { requireManagedOrcadInfrastructure } from '../../managed-server/lifecycle/orcad-managed-runtime-context' import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' -import { keepOrcadServerVersion, runOrcadDeltaMove } from '../../ssh/orcad-migration-delta-move' -import { planOrcadDeltaMove } from '../../ssh/orcad-migration-delta-plan' -import { censusHostRelayTerminalsFor } from '../../ssh/legacy-relay/ssh-host-relay-census-for-target' +import { + keepOrcadServerVersion, + runOrcadDeltaMove +} from '../../managed-server/migration/cutover/orcad-migration-delta-move' +import { planOrcadDeltaMove } from '../../managed-server/migration/cutover/orcad-migration-delta-plan' +import { censusHostRelayTerminalsFor } from '../../ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target' import { orcadMigrationDestinationFor, orcadServerAutomationEnablerFor } from '../../managed-server/lifecycle/orcad-runtime-conversion-wiring' -import { enableMovedOrcadAutomationsForTarget } from '../../ssh/orcad-migration-moved-automations' +import { enableMovedOrcadAutomationsForTarget } from '../../persistence/migrating-orcad-catalog/orcad-migration-moved-automations' import { requiredString } from './orcad-runtime-lifecycle-handlers' import { publishResolvedChangedHostStatus } from './runtime-environment-managed-tunnel' import { runTargetLifecycle } from '../ssh/ssh-target-lifecycle-queue' diff --git a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts index 563e18eac54..c28731557b7 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-connectivity-handlers.ts @@ -20,7 +20,7 @@ import { removeThroughOwningService } from './runtime-environment-host-service-ops' import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' -import type { RuntimeStatus } from '../../../shared/runtime-types' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import type { Store } from '../../persistence/loading-store/store' import { retireRemovedRuntimeEnvironment } from './runtime-environment-removal-cleanup' import { removeRedundantManagedPairing } from './runtime-environment-redundant-managed-removal' @@ -40,7 +40,7 @@ import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' import { noteRuntimeEnvironmentConnectRequested } from './runtime-environment-pairing-refusal-registry' import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key' import { withWslOrcadAccountEnv } from '../../wsl/orcad/wsl-orcad-account-env' -import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/ssh-credential-decline' +import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/authentication/ssh-credential-decline' import { disconnectManagedHostOfEnvironmentForUser, disconnectRuntimeEnvironmentForUser, diff --git a/src/main/ipc/runtime-environments/runtime-environment-managed-tunnel.ts b/src/main/ipc/runtime-environments/runtime-environment-managed-tunnel.ts index 46c722e6c57..21c7d4622f8 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-managed-tunnel.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-managed-tunnel.ts @@ -9,7 +9,7 @@ import type { SshManagedServerUpdateNote, SshTarget } from '../../../shared/ssh-types' -import { managedServerUpdateDeps } from '../../ssh/managed-server-update-deps' +import { managedServerUpdateDeps } from '../../ssh/host-server/managed-server-update-deps' import { ensureOrcadManagedTunnel, rebuildOrcadManagedTunnel @@ -28,7 +28,10 @@ import { redeployStoppedManagedOrcad, updateManagedOrcadOnRestore } from '../../managed-server/lifecycle/orcad-managed-update-on-restore' -import { getSshHostServerStatus, setSshHostServerStatus } from '../../ssh/ssh-host-server-status' +import { + getSshHostServerStatus, + setSshHostServerStatus +} from '../../ssh/host-server/ssh-host-server-status' import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' import { connectionManager, getCurrentMainWindow } from '../ssh/ssh-ipc-context' import { diff --git a/src/main/ipc/runtime-environments/runtime-environment-pairing-verification.ts b/src/main/ipc/runtime-environments/runtime-environment-pairing-verification.ts index b006423d0e3..502a486fc40 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-pairing-verification.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-pairing-verification.ts @@ -23,7 +23,7 @@ import { isEphemeralVmRuntimeEnvironment, redactRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { RuntimeStatus } from '../../../shared/runtime-types' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import { remoteServerPairingFailureText, type RemoteServerPairingFailureCode diff --git a/src/main/ipc/runtime-environments/runtime-environment-status-owner.ts b/src/main/ipc/runtime-environments/runtime-environment-status-owner.ts index e46538641c9..1df482a0150 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-status-owner.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-status-owner.ts @@ -10,7 +10,7 @@ import { managedOrcadRefusalNeedingUserCode } from '../../managed-server/lifecyc import { recoverRefusedPairing } from './runtime-environment-pairing-refusal-registry' import { recordRuntimeEnvironmentUsage } from '../../../shared/remote-runtime/host-store/runtime-environment-usage-record' import { RuntimeHostStatusOwner } from '../../../shared/remote-runtime/host-status/runtime-host-status-owner' -import type { RuntimeStatus } from '../../../shared/runtime-types' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import { RUNTIME_HOST_STATUS_CHANNEL, type RuntimeHostStatusSnapshot, diff --git a/src/main/ipc/runtime-ssh-access-handlers.ts b/src/main/ipc/runtime-ssh-access-handlers.ts index ffd24857a12..aa34e54131f 100644 --- a/src/main/ipc/runtime-ssh-access-handlers.ts +++ b/src/main/ipc/runtime-ssh-access-handlers.ts @@ -3,7 +3,10 @@ import { RuntimeSshAccessLinkRequestSchema, RuntimeSshAccessUnlinkRequestSchema } from '../../shared/runtime-ssh-access' -import { linkRuntimeSshAccess, unlinkRuntimeSshAccess } from '../ssh/runtime-ssh-access' +import { + linkRuntimeSshAccess, + unlinkRuntimeSshAccess +} from '../ssh/runtime-access/runtime-ssh-access' import { addFanoutListener } from '../runtime/events/event-listener-fanout' export function registerRuntimeSshAccessHandlers(options: { diff --git a/src/main/ipc/session.ts b/src/main/ipc/session.ts index 79e16ff22cc..17f1072ff44 100644 --- a/src/main/ipc/session.ts +++ b/src/main/ipc/session.ts @@ -2,9 +2,9 @@ import { ipcMain } from 'electron' import type { Store } from '../persistence/loading-store/store' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { parseTerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' -import { isFrozenOrcadSourceSessionPartition } from '../ssh/orcad-retained-source' +import { isFrozenOrcadSourceSessionPartition } from '../persistence/migrating-orcad-catalog/orcad-source-visibility' import { isWslMoveWindowWriteHeld } from '../persistence/moving-wsl-projects/wsl-move-window-write-hold' -import { visibleSessionHostIds } from '../ssh/orcad-retained-source-session' +import { visibleSessionHostIds } from '../persistence/migrating-orcad-catalog/orcad-retained-source-session' import { markAgentLaunchesClosedByUser } from '../agent-launch/agent-launch-pane-attachment' import { windowViewPatchForMain, windowViewSaveForMain } from '../persistence/window-save-view' import { reportWindowSaveDrift } from '../persistence/window-save-divergence' diff --git a/src/main/ipc/shell-editor-ssh-host.ts b/src/main/ipc/shell-editor-ssh-host.ts index 99102af2a9a..c7f27e9fdb0 100644 --- a/src/main/ipc/shell-editor-ssh-host.ts +++ b/src/main/ipc/shell-editor-ssh-host.ts @@ -8,7 +8,7 @@ import { type KnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' import type { SshTarget } from '../../shared/ssh-types' -import { fingerprintRuntimeSshTarget } from '../ssh/runtime-ssh-target-fingerprint' +import { fingerprintRuntimeSshTarget } from '../ssh/runtime-access/runtime-ssh-target-fingerprint' export type ListRuntimeEnvironments = () => readonly Pick< KnownRuntimeEnvironment, diff --git a/src/main/ipc/ssh/plain-ssh-terminal-handlers.ts b/src/main/ipc/ssh/plain-ssh-terminal-handlers.ts index b699107dd75..2ec075211c8 100644 --- a/src/main/ipc/ssh/plain-ssh-terminal-handlers.ts +++ b/src/main/ipc/ssh/plain-ssh-terminal-handlers.ts @@ -7,7 +7,7 @@ import { } from '../../../shared/plain-ssh-terminal' import { isSshHostMoveBlocked } from '../../../shared/ssh-host-move-blocked' import { mayUserSshConfigClaimAlias } from '../../ssh/config/ssh-config-alias-claim' -import { getSshHostServerStatus } from '../../ssh/ssh-host-server-status' +import { getSshHostServerStatus } from '../../ssh/host-server/ssh-host-server-status' import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' import { findSystemSsh } from '../../ssh/system-transport/system-ssh-binary' import { ensureNodePtySpawnHelperExecutable } from '../../providers/local-pty/local-pty-executable-spawn' diff --git a/src/main/ipc/ssh/ssh-app-shutdown.test.ts b/src/main/ipc/ssh/ssh-app-shutdown.test.ts index cc44ee68de8..22ba8fc719b 100644 --- a/src/main/ipc/ssh/ssh-app-shutdown.test.ts +++ b/src/main/ipc/ssh/ssh-app-shutdown.test.ts @@ -7,10 +7,10 @@ const mocks = await vi.hoisted(async () => { vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/connection/ssh-connection-store', () => mocks.sshConnectionStore) +vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) +vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) const { shutdownTunnelsMock } = vi.hoisted(() => ({ shutdownTunnelsMock: vi.fn() })) diff --git a/src/main/ipc/ssh/ssh-browse.ts b/src/main/ipc/ssh/ssh-browse.ts index 808bce33151..47028376536 100644 --- a/src/main/ipc/ssh/ssh-browse.ts +++ b/src/main/ipc/ssh/ssh-browse.ts @@ -1,6 +1,9 @@ import { ipcMain } from 'electron' import type { SshConnectionManager } from '../../ssh/connection/ssh-connection-manager' -import { browseSshDirectory, type RemoteBrowseResult } from '../../ssh/ssh-remote-directory-browse' +import { + browseSshDirectory, + type RemoteBrowseResult +} from '../../ssh/filesystem/ssh-remote-directory-browse' export function registerSshBrowseHandler( getConnectionManager: () => SshConnectionManager | null diff --git a/src/main/ipc/ssh/ssh-connect-attempt-registry.ts b/src/main/ipc/ssh/ssh-connect-attempt-registry.ts index 486e1dc7968..c531ced8292 100644 --- a/src/main/ipc/ssh/ssh-connect-attempt-registry.ts +++ b/src/main/ipc/ssh/ssh-connect-attempt-registry.ts @@ -4,7 +4,7 @@ import { getSshProviderAuthority, isCurrentSshProviderAuthority, rotateSshProviderAuthority -} from '../../ssh/ssh-provider-authority' +} from '../../ssh/connection/authority/ssh-provider-authority' // Preserve credential tracking across macOS window recreation. export const credentialRequestedForTarget = new Set() diff --git a/src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts b/src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts index 7b43d0b5509..d81363a47e8 100644 --- a/src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts +++ b/src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts @@ -7,17 +7,20 @@ const mocks = await vi.hoisted(async () => { vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/connection/ssh-connection-store', () => mocks.sshConnectionStore) +vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) +vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) -vi.mock(import('../../ssh/legacy-relay/legacy-relay-bridge-registry'), async (importOriginal) => ({ - ...(await importOriginal()), - startLegacyRelayBridge: vi.fn(async () => {}), - stopLegacyRelayBridge: vi.fn() -})) +vi.mock( + import('../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry'), + async (importOriginal) => ({ + ...(await importOriginal()), + startLegacyRelayBridge: vi.fn(async () => {}), + stopLegacyRelayBridge: vi.fn() + }) +) import type { SshManagedServerStatus, SshTarget } from '../../../shared/ssh-types' import type { SshConnection } from '../../ssh/connection/ssh-connection' @@ -34,12 +37,15 @@ import { connectInFlight } from './ssh-connect-attempt-registry' import { getSshProviderAuthority, isCurrentSshProviderAuthority -} from '../../ssh/ssh-provider-authority' -import { clearSshHostServerStatus, setSshHostServerStatus } from '../../ssh/ssh-host-server-status' +} from '../../ssh/connection/authority/ssh-provider-authority' +import { + clearSshHostServerStatus, + setSshHostServerStatus +} from '../../ssh/host-server/ssh-host-server-status' import { startLegacyRelayBridge, stopLegacyRelayBridge -} from '../../ssh/legacy-relay/legacy-relay-bridge-registry' +} from '../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry' import { createSshIpcHarness } from './ssh-ipc-test-harness' const { mockSshStore, mockConnectionManager } = mocks diff --git a/src/main/ipc/ssh/ssh-connect-flow.ts b/src/main/ipc/ssh/ssh-connect-flow.ts index f2b3d9c4fb4..d25e049bd38 100644 --- a/src/main/ipc/ssh/ssh-connect-flow.ts +++ b/src/main/ipc/ssh/ssh-connect-flow.ts @@ -1,11 +1,11 @@ import { appendFileSync } from 'node:fs' import type { SshConnectionState } from '../../../shared/ssh-types' -import { createCancelledConnectAttemptError } from '../../ssh/ssh-connect-attempt-cancellation' +import { createCancelledConnectAttemptError } from '../../ssh/connection/reconnect/ssh-connect-attempt-cancellation' import { getSshProviderAuthority, isCurrentSshProviderAuthority, rotateSshProviderAuthority -} from '../../ssh/ssh-provider-authority' +} from '../../ssh/connection/authority/ssh-provider-authority' import { adoptSshConnection, runAttributedToSshOwner @@ -33,17 +33,17 @@ import { import { connectionManager } from './ssh-ipc-context' import { abandonDecisionTransport } from './ssh-session-teardown' import { awaitTargetLifecycle } from './ssh-target-lifecycle-queue' -import { startLegacyRelayBridge } from '../../ssh/legacy-relay/legacy-relay-bridge-registry' +import { startLegacyRelayBridge } from '../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry' import { getSshHostServerStatus, isSshHostKeptForBridgedTerminals -} from '../../ssh/ssh-host-server-status' -import type { HostServerOnConnectResult } from '../../ssh/ssh-host-server-on-connect' -import { clearSshCredentialDeclined } from '../../ssh/ssh-credential-decline' +} from '../../ssh/host-server/ssh-host-server-status' +import type { HostServerOnConnectResult } from '../../ssh/host-server/ssh-host-server-on-connect' +import { clearSshCredentialDeclined } from '../../ssh/authentication/ssh-credential-decline' import { createSshUserDisconnectedError, isSshUserDisconnected -} from '../../ssh/ssh-user-disconnect' +} from '../../ssh/connection/ssh-user-disconnect' import { isManagedServerRemovalHeld, liftSshHostUserDisconnect, diff --git a/src/main/ipc/ssh/ssh-connection-handlers.ts b/src/main/ipc/ssh/ssh-connection-handlers.ts index b3b484c670a..308084d044b 100644 --- a/src/main/ipc/ssh/ssh-connection-handlers.ts +++ b/src/main/ipc/ssh/ssh-connection-handlers.ts @@ -16,7 +16,7 @@ import { errorMessage } from '../../../shared/error-message' import { clearSshCredentialDeclined, isSshCredentialDeclined -} from '../../ssh/ssh-credential-decline' +} from '../../ssh/authentication/ssh-credential-decline' export function registerSshConnectionHandlers(): void { setSshTargetRegistryHandlers({ diff --git a/src/main/ipc/ssh/ssh-connection-state-callbacks.ts b/src/main/ipc/ssh/ssh-connection-state-callbacks.ts index 297bb89de08..77753f144f5 100644 --- a/src/main/ipc/ssh/ssh-connection-state-callbacks.ts +++ b/src/main/ipc/ssh/ssh-connection-state-callbacks.ts @@ -4,7 +4,7 @@ import { isSshHostCensusInFlight } from '../../ssh/connection/ssh-connection-att import { clearSshCredentialDeclined, isSshCredentialDeclined -} from '../../ssh/ssh-credential-decline' +} from '../../ssh/authentication/ssh-credential-decline' import { connectInFlight, credentialRequestedForTarget, diff --git a/src/main/ipc/ssh/ssh-credential-cancel.test.ts b/src/main/ipc/ssh/ssh-credential-cancel.test.ts index 4bb5933d3a3..2095dd2265f 100644 --- a/src/main/ipc/ssh/ssh-credential-cancel.test.ts +++ b/src/main/ipc/ssh/ssh-credential-cancel.test.ts @@ -7,16 +7,16 @@ const mocks = await vi.hoisted(async () => { vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/connection/ssh-connection-store', () => mocks.sshConnectionStore) +vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) +vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) import type { SshCredentialKind } from '../../ssh/connection/ssh-connection-callbacks' import type { SshTarget } from '../../../shared/ssh-types' -import { isSshCredentialDeclined } from '../../ssh/ssh-credential-decline' +import { isSshCredentialDeclined } from '../../ssh/authentication/ssh-credential-decline' import { createSshIpcHarness } from './ssh-ipc-test-harness' import { createSshConnectionCallbacks } from './ssh-connection-state-callbacks' diff --git a/src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts b/src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts index ee012f87fd7..4e5f7948461 100644 --- a/src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts +++ b/src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts @@ -7,10 +7,10 @@ const mocks = await vi.hoisted(async () => { vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/connection/ssh-connection-store', () => mocks.sshConnectionStore) +vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) +vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) diff --git a/src/main/ipc/ssh/ssh-host-launch-session-note.ts b/src/main/ipc/ssh/ssh-host-launch-session-note.ts index b2162f76ba5..f5fa43272bd 100644 --- a/src/main/ipc/ssh/ssh-host-launch-session-note.ts +++ b/src/main/ipc/ssh/ssh-host-launch-session-note.ts @@ -2,8 +2,8 @@ import { getAppEnvironment } from '../../../shared/app-environment' import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { readManagedOrcadLaunchSshSession } from '../../managed-server/lifecycle/orcad-managed-launch-session' -import { knownSshHostPlatform } from '../../ssh/ssh-host-platform-memo' -import { getSshHostServerStatus } from '../../ssh/ssh-host-server-status' +import { knownSshHostPlatform } from '../../ssh/remote-host/ssh-host-platform-memo' +import { getSshHostServerStatus } from '../../ssh/host-server/ssh-host-server-status' import { connectionManager } from './ssh-ipc-context' import { clearLaunchSessionNote, diff --git a/src/main/ipc/ssh/ssh-host-server-connect.ts b/src/main/ipc/ssh/ssh-host-server-connect.ts index e060cb3518f..33f0aa9da86 100644 --- a/src/main/ipc/ssh/ssh-host-server-connect.ts +++ b/src/main/ipc/ssh/ssh-host-server-connect.ts @@ -7,24 +7,27 @@ import type { SshManagedServerUpdateNote, SshTarget } from '../../../shared/ssh-types' -import type { HostServerOnConnectResult } from '../../ssh/ssh-host-server-on-connect' -import { unservedHostServerMessage, unservedServerStatus } from '../../ssh/ssh-host-unserved-status' +import type { HostServerOnConnectResult } from '../../ssh/host-server/ssh-host-server-on-connect' +import { + unservedHostServerMessage, + unservedServerStatus +} from '../../ssh/host-server/ssh-host-unserved-status' import { clearSshHostServerStatus, getSshHostServerStatus, isSshHostKeptForBridgedTerminals, setSshHostServerStatus -} from '../../ssh/ssh-host-server-status' +} from '../../ssh/host-server/ssh-host-server-status' import { connectionManager, getCurrentMainWindow } from './ssh-ipc-context' import { broadcastSshState, getPublicSshState } from './ssh-renderer-broadcast' -import { isAuthError } from '../../ssh/ssh-reconnect-error-classification' -import { isSshSessionStartFailure } from '../../ssh/ssh-session-start-failure' -import { describeSshConnectFailure } from '../../ssh/ssh-connect-failure-next-step' +import { isAuthError } from '../../ssh/connection/reconnect/ssh-reconnect-error-classification' +import { isSshSessionStartFailure } from '../../ssh/connection/ssh-session-start-failure' +import { describeSshConnectFailure } from '../../ssh/connection/ssh-connect-failure-next-step' export async function decideHostServer(target: SshTarget): Promise { // Load managed-server deploy/migration/tunnel dependencies only when connecting. const [{ resolveHostServerOnConnect }, { hostServerOnConnectDeps }] = await Promise.all([ - import('../../ssh/ssh-host-server-on-connect'), + import('../../ssh/host-server/ssh-host-server-on-connect'), import('./ssh-host-server-on-connect-wiring') ]) return await resolveHostServerOnConnect( @@ -36,7 +39,7 @@ export async function decideHostServer(target: SshTarget): Promise { const deps = wiring.hostServerOnConnectDeps(getAppEnvironment().getPath('userData')) diff --git a/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts b/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts index 1334e02a5c4..fc49d4d4658 100644 --- a/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts +++ b/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts @@ -4,13 +4,13 @@ import { managedOrcadServerName } from '../../../shared/managed-orcad-ssh-owner' import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { findOrcadMigrationSourceCutoverForTarget } from '../../ssh/orcad-migration-cutover-journal' -import { abandonOrcadConversion } from '../../ssh/orcad-conversion-abandon' -import { retainOrcadMigrationSource } from '../../ssh/orcad-migration-source-retention' -import { enableMovedOrcadAutomationsForTarget } from '../../ssh/orcad-migration-moved-automations' +import { findOrcadMigrationSourceCutoverForTarget } from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { abandonOrcadConversion } from '../../managed-server/migration/cutover/orcad-conversion-abandon' +import { retainOrcadMigrationSource } from '../../persistence/migrating-orcad-catalog/orcad-migration-source-retention' +import { enableMovedOrcadAutomationsForTarget } from '../../persistence/migrating-orcad-catalog/orcad-migration-moved-automations' import { hasOrcadTemplate } from '../../orcad/orcad-artifact-materializer' import { isOrcadHostUnavailableFixableOnHost } from '../../orcad/orcad-host-unavailable' -import { managedServerUpdateDeps } from '../../ssh/managed-server-update-deps' +import { managedServerUpdateDeps } from '../../ssh/host-server/managed-server-update-deps' import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' import { verifyOrcadManagedServing } from '../../managed-server/lifecycle/orcad-managed-serving-verify' import { convertSshTargetToManagedOrcad } from '../../managed-server/lifecycle/orcad-runtime-conversion' @@ -21,24 +21,24 @@ import { orcadServerRepositoriesFor } from '../../managed-server/lifecycle/orcad-runtime-conversion-wiring' import { createManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-runtime-deployment' -import type { HostServerOnConnectDeps } from '../../ssh/ssh-host-server-on-connect' +import type { HostServerOnConnectDeps } from '../../ssh/host-server/ssh-host-server-on-connect' import { censusSshHostRelaysBeforeSession, relayTerminalsOnConnect -} from '../../ssh/legacy-relay/ssh-host-relay-terminals-on-connect' +} from '../../ssh/legacy-relay/endpoints/ssh-host-relay-terminals-on-connect' import { requireManagedOrcadInfrastructure } from '../../managed-server/lifecycle/orcad-managed-runtime-context' -import { censusHostRelayTerminalsFor } from '../../ssh/legacy-relay/ssh-host-relay-census-for-target' -import { setSshHostServerStatus } from '../../ssh/ssh-host-server-status' -import { trackSshHostServerEvent } from '../../ssh/ssh-host-server-telemetry' -import { knownSshHostPlatform } from '../../ssh/ssh-host-platform-memo' -import { knownOrcadTunnelTransport } from '../../ssh/orcad-tunnel-transport-memo' +import { censusHostRelayTerminalsFor } from '../../ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target' +import { setSshHostServerStatus } from '../../ssh/host-server/ssh-host-server-status' +import { trackSshHostServerEvent } from '../../ssh/host-server/ssh-host-server-telemetry' +import { knownSshHostPlatform } from '../../ssh/remote-host/ssh-host-platform-memo' +import { knownOrcadTunnelTransport } from '../../managed-server/lifecycle/orcad-tunnel-transport-memo' import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' -import { releaseUnreachableOrcadSetup } from '../../ssh/orcad-unreachable-setup-release' +import { releaseUnreachableOrcadSetup } from '../../managed-server/migration/cutover/orcad-unreachable-setup-release' import { getCurrentMainWindow } from './ssh-ipc-context' import { broadcastSshState } from './ssh-renderer-broadcast' import { connectInFlight } from './ssh-connect-attempt-registry' -import { startLegacyRelayBridge } from '../../ssh/legacy-relay/legacy-relay-bridge-registry' -import { isBridgeableLease } from '../../ssh/legacy-relay/legacy-relay-bridge-leases' +import { startLegacyRelayBridge } from '../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry' +import { isBridgeableLease } from '../../ssh/legacy-relay/bridge/legacy-relay-bridge-leases' export function hostServerOnConnectDeps(userDataPath: string): HostServerOnConnectDeps { const registry = getSshTargetRegistryStore()! diff --git a/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts b/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts index 22773534593..a6ab2753254 100644 --- a/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts +++ b/src/main/ipc/ssh/ssh-host-user-disconnect.test.ts @@ -11,10 +11,10 @@ const runtime = vi.hoisted(() => { vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/connection/ssh-connection-store', () => mocks.sshConnectionStore) +vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) +vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) vi.mock( @@ -36,7 +36,7 @@ vi.mock('../runtime-environments/runtime-environments', () => ({ })) import type { SshTarget } from '../../../shared/ssh-types' import { clearRuntimeEnvironmentManualDisconnect } from '../runtime-environments/runtime-environment-manual-disconnect' -import { isSshUserDisconnected } from '../../ssh/ssh-user-disconnect' +import { isSshUserDisconnected } from '../../ssh/connection/ssh-user-disconnect' import { createSshIpcHarness } from './ssh-ipc-test-harness' import { runTargetLifecycle } from './ssh-target-lifecycle-queue' diff --git a/src/main/ipc/ssh/ssh-host-user-disconnect.ts b/src/main/ipc/ssh/ssh-host-user-disconnect.ts index be2f70a343a..64f67dd2820 100644 --- a/src/main/ipc/ssh/ssh-host-user-disconnect.ts +++ b/src/main/ipc/ssh/ssh-host-user-disconnect.ts @@ -12,7 +12,7 @@ import { clearSshUserDisconnectedForEnvironment, isSshUserDisconnected, recordSshUserDisconnected -} from '../../ssh/ssh-user-disconnect' +} from '../../ssh/connection/ssh-user-disconnect' import { connectRegisteredSshTarget, getSshTargetRegistryStore @@ -25,7 +25,7 @@ import { import { getRuntimeEnvironmentStatusOwner } from '../runtime-environments/runtime-environment-request-connections' import { disconnectRegisteredSshTarget } from './ssh-session-teardown' import { noteRuntimeEnvironmentConnectRequested } from '../runtime-environments/runtime-environment-pairing-refusal-registry' -import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/ssh-credential-decline' +import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/authentication/ssh-credential-decline' /** Managed server and SSH host share user disconnect intent; only explicit Connect may restore either. */ diff --git a/src/main/ipc/ssh/ssh-ipc-module-mocks.ts b/src/main/ipc/ssh/ssh-ipc-module-mocks.ts index 9e9fcd62cd3..46e470a0acb 100644 --- a/src/main/ipc/ssh/ssh-ipc-module-mocks.ts +++ b/src/main/ipc/ssh/ssh-ipc-module-mocks.ts @@ -132,11 +132,6 @@ export function createSshIpcMocks(): SshIpcMocks { })) }, sshConnectionStore: { - isRuntimeOwnedSshTarget: (target: { owner?: unknown }) => target.owner !== undefined, - isManagedOrcadSshTarget: (target: { orcadFence?: unknown; orcadProvisioning?: unknown }) => - target.orcadFence !== undefined || target.orcadProvisioning !== undefined, - allowsDirectSshRelay: (target: { orcadFence?: unknown; orcadProvisioning?: unknown }) => - target.orcadFence === undefined && target.orcadProvisioning === undefined, SshConnectionStore: class MockSshConnectionStore { constructor() { return mockSshStore diff --git a/src/main/ipc/ssh/ssh-managed-port-forward-restore.ts b/src/main/ipc/ssh/ssh-managed-port-forward-restore.ts index 17b95b7bf8c..d06682b4a28 100644 --- a/src/main/ipc/ssh/ssh-managed-port-forward-restore.ts +++ b/src/main/ipc/ssh/ssh-managed-port-forward-restore.ts @@ -1,5 +1,8 @@ import type { SshConnection } from '../../ssh/connection/ssh-connection' -import { getSshHostServerStatus, isSshHostServed } from '../../ssh/ssh-host-server-status' +import { + getSshHostServerStatus, + isSshHostServed +} from '../../ssh/host-server/ssh-host-server-status' import { connectionManager, getCurrentMainWindow } from './ssh-ipc-context' import { restorePortForwards, savedPortForwardsAllLive } from './ssh-port-forward-persistence' import { forgetForwardFailures } from './ssh-port-forward-unrestored' diff --git a/src/main/ipc/ssh/ssh-passphrase.test.ts b/src/main/ipc/ssh/ssh-passphrase.test.ts index e14817a55b8..e7374c9b8cb 100644 --- a/src/main/ipc/ssh/ssh-passphrase.test.ts +++ b/src/main/ipc/ssh/ssh-passphrase.test.ts @@ -1,7 +1,7 @@ import { ipcMain, type BrowserWindow } from 'electron' import { beforeEach, describe, expect, it, vi } from 'vitest' import { registerCredentialHandler, requestCredential } from './ssh-passphrase' -import { resetSshCredentialDeclinesForTests } from '../../ssh/ssh-credential-decline' +import { resetSshCredentialDeclinesForTests } from '../../ssh/authentication/ssh-credential-decline' vi.mock('electron', () => ({ ipcMain: { diff --git a/src/main/ipc/ssh/ssh-passphrase.ts b/src/main/ipc/ssh/ssh-passphrase.ts index 78bc7b59b6a..c83d6b558c3 100644 --- a/src/main/ipc/ssh/ssh-passphrase.ts +++ b/src/main/ipc/ssh/ssh-passphrase.ts @@ -2,7 +2,7 @@ import { ipcMain, type BrowserWindow } from 'electron' import { randomUUID } from 'node:crypto' import { SSH_CREDENTIAL_TIMEOUT_MS } from '../../ssh/connection/ssh-connection-timing' import type { SshCredentialKind } from '../../ssh/connection/ssh-connection-callbacks' -import { recordSshCredentialDeclined } from '../../ssh/ssh-credential-decline' +import { recordSshCredentialDeclined } from '../../ssh/authentication/ssh-credential-decline' const pendingRequests = new Map< string, { targetId: string; resolve: (value: string | null) => void; close: () => void } diff --git a/src/main/ipc/ssh/ssh-renderer-broadcast.ts b/src/main/ipc/ssh/ssh-renderer-broadcast.ts index bbf7efd6f35..bfcd5e498f6 100644 --- a/src/main/ipc/ssh/ssh-renderer-broadcast.ts +++ b/src/main/ipc/ssh/ssh-renderer-broadcast.ts @@ -11,9 +11,12 @@ import { enrichSshForwardEntries, getWorktreeIdsForConnection } from '../../ports/ssh-advertised-url-enrichment' -import { isRuntimeOwnedSshTarget } from '../../ssh/connection/ssh-connection-store' -import { getSshProviderAuthority } from '../../ssh/ssh-provider-authority' -import { clearSshHostServerStatus, getSshHostServerStatus } from '../../ssh/ssh-host-server-status' +import { isRuntimeOwnedSshTarget } from '../../ssh/targets/ssh-target-runtime-ownership' +import { getSshProviderAuthority } from '../../ssh/connection/authority/ssh-provider-authority' +import { + clearSshHostServerStatus, + getSshHostServerStatus +} from '../../ssh/host-server/ssh-host-server-status' import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' import { connectionManager, diff --git a/src/main/ipc/ssh/ssh-session-teardown.ts b/src/main/ipc/ssh/ssh-session-teardown.ts index 9e0629ab241..91c143ed3aa 100644 --- a/src/main/ipc/ssh/ssh-session-teardown.ts +++ b/src/main/ipc/ssh/ssh-session-teardown.ts @@ -1,6 +1,6 @@ import type { DirectSshAuthority } from '../../../shared/ssh-types' import { getSshTargetRegistryStore } from '../../ssh/targets/ssh-target-registry' -import { clearSshHostServerStatus } from '../../ssh/ssh-host-server-status' +import { clearSshHostServerStatus } from '../../ssh/host-server/ssh-host-server-status' import { isSshConnectionSolelyOwnedBy } from '../../ssh/connection/ssh-connection-attribution' import { connectInFlight, @@ -23,7 +23,7 @@ import { errorMessage } from '../../../shared/error-message' import { forgetLegacyRelayTarget, stopLegacyRelayBridge -} from '../../ssh/legacy-relay/legacy-relay-bridge-registry' +} from '../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry' export async function disconnectRegisteredSshTarget(targetId: string): Promise { invalidateConnectAttempt(targetId) diff --git a/src/main/ipc/ssh/ssh-sign-in-requirement.ts b/src/main/ipc/ssh/ssh-sign-in-requirement.ts index bc1491cc300..b34e82d9dc4 100644 --- a/src/main/ipc/ssh/ssh-sign-in-requirement.ts +++ b/src/main/ipc/ssh/ssh-sign-in-requirement.ts @@ -1,6 +1,6 @@ -import { recordSshSignInAwaited } from '../../ssh/ssh-credential-decline' +import { recordSshSignInAwaited } from '../../ssh/authentication/ssh-credential-decline' import type { SshConnectionManager } from '../../ssh/connection/ssh-connection-manager' -import type { SshConnectionStore } from '../../ssh/connection/ssh-connection-store' +import type { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' import { credentialRequestedForTarget } from './ssh-connect-attempt-registry' /** Persist credential need so background restore waits for explicit sign-in after the next launch. */ diff --git a/src/main/ipc/ssh/ssh-target-crud-handlers.ts b/src/main/ipc/ssh/ssh-target-crud-handlers.ts index af73d55d44a..98e6f4fc1a5 100644 --- a/src/main/ipc/ssh/ssh-target-crud-handlers.ts +++ b/src/main/ipc/ssh/ssh-target-crud-handlers.ts @@ -13,7 +13,7 @@ import { } from '../../ssh/config/ssh-config-host-picker' import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' import { closeOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' -import { rotateSshProviderAuthority } from '../../ssh/ssh-provider-authority' +import { rotateSshProviderAuthority } from '../../ssh/connection/authority/ssh-provider-authority' import { getSshTargetRegistryStore, setSshTargetMutations @@ -22,10 +22,10 @@ import { allowsDirectSshRelay, isManagedOrcadSshTarget, isRuntimeOwnedSshTarget -} from '../../ssh/connection/ssh-connection-store' +} from '../../ssh/targets/ssh-target-runtime-ownership' import { connectionManager, getCurrentMainWindow } from './ssh-ipc-context' import { runTargetLifecycle } from './ssh-target-lifecycle-queue' -import { fingerprintRuntimeSshTarget } from '../../ssh/runtime-ssh-target-fingerprint' +import { fingerprintRuntimeSshTarget } from '../../ssh/runtime-access/runtime-ssh-target-fingerprint' import { removeRegisteredSshTarget } from './ssh-session-teardown' import { notifyReposChanged } from '../repos/repos-changed-notification' import { diff --git a/src/main/ipc/ssh/ssh.test.ts b/src/main/ipc/ssh/ssh.test.ts index dbdd5e0f4d9..0f6a2840621 100644 --- a/src/main/ipc/ssh/ssh.test.ts +++ b/src/main/ipc/ssh/ssh.test.ts @@ -7,10 +7,10 @@ const mocks = await vi.hoisted(async () => { vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/connection/ssh-connection-store', () => mocks.sshConnectionStore) +vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) +vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) @@ -22,7 +22,10 @@ import { recordSshConnectionOpened } from '../../ssh/connection/ssh-connection-attribution' import type { SshConnection } from '../../ssh/connection/ssh-connection' -import { clearSshHostServerStatus, setSshHostServerStatus } from '../../ssh/ssh-host-server-status' +import { + clearSshHostServerStatus, + setSshHostServerStatus +} from '../../ssh/host-server/ssh-host-server-status' const { mockSshStore, mockConnectionManager } = mocks diff --git a/src/main/ipc/ssh/ssh.ts b/src/main/ipc/ssh/ssh.ts index f53e2894cc2..6a9bd3262c6 100644 --- a/src/main/ipc/ssh/ssh.ts +++ b/src/main/ipc/ssh/ssh.ts @@ -1,6 +1,6 @@ import { ipcMain, type BrowserWindow } from 'electron' import type { Store } from '../../persistence/loading-store/store' -import { SshConnectionStore } from '../../ssh/connection/ssh-connection-store' +import { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' import { awaitSignInForCredentialHosts } from './ssh-sign-in-requirement' import { holdLaunchReconnectOptOuts, @@ -23,8 +23,8 @@ import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { initializeSshConnectionGenerationSession, resetSshConnectionGenerations -} from '../../ssh/connection/ssh-connection-generation' -import { resetSshProviderAuthorities } from '../../ssh/ssh-provider-authority' +} from '../../ssh/connection/authority/ssh-connection-generation' +import { resetSshProviderAuthorities } from '../../ssh/connection/authority/ssh-provider-authority' import { installManagedOrcadStartStatus } from '../runtime-environments/runtime-environment-managed-tunnel' import { connectInFlight, @@ -33,8 +33,8 @@ import { testingTargets } from './ssh-connect-attempt-registry' import { createSshConnectionCallbacks } from './ssh-connection-state-callbacks' -import { resetSshCredentialDeclinesForTests } from '../../ssh/ssh-credential-decline' -import { resetSshUserDisconnectsForTests } from '../../ssh/ssh-user-disconnect' +import { resetSshCredentialDeclinesForTests } from '../../ssh/authentication/ssh-credential-decline' +import { resetSshUserDisconnectsForTests } from '../../ssh/connection/ssh-user-disconnect' import { registerSshConnectionHandlers } from './ssh-connection-handlers' import { registerPlainSshTerminalHandlers } from './plain-ssh-terminal-handlers' import { @@ -59,21 +59,21 @@ import { getSshHostServerStatus, isSshHostKeptForBridgedTerminals, setSshHostServedListener -} from '../../ssh/ssh-host-server-status' +} from '../../ssh/host-server/ssh-host-server-status' import { broadcastPortForwards } from './ssh-renderer-broadcast' import { resetSshShutdownDrain } from './ssh-shutdown-drain' import { registerSshTargetCrudHandlers } from './ssh-target-crud-handlers' import { targetLifecycleInFlight } from './ssh-target-lifecycle-queue' import { disposeOrcadManagedTunnels } from '../../managed-server/lifecycle/orcad-managed-tunnel' -import { retainUnretainedOrcadMigrationSources } from '../../ssh/orcad-migration-source-retention' -import { reconcileManagedOrcadSshTargets } from '../../ssh/orcad-retained-source' -import { installOrcadMigrationScrollbackRetention } from '../../ssh/orcad-migration-scrollback-retention-wiring' +import { retainUnretainedOrcadMigrationSources } from '../../persistence/migrating-orcad-catalog/orcad-migration-source-retention' +import { reconcileManagedOrcadSshTargets } from '../../persistence/migrating-orcad-catalog/orcad-retained-source' +import { installOrcadMigrationScrollbackRetention } from '../../persistence/migrating-orcad-catalog/orcad-migration-scrollback-retention-wiring' import { getAppEnvironment } from '../../../shared/app-environment' -import { registerLegacyRelayBridgeIpc } from '../../ssh/legacy-relay/legacy-relay-bridge-ipc' +import { registerLegacyRelayBridgeIpc } from '../../ssh/legacy-relay/bridge/legacy-relay-bridge-ipc' import { onLastBridgedTerminalExit, retryMoveAfterLastBridgedExit -} from '../../ssh/legacy-relay/legacy-relay-move-retry' +} from '../../ssh/legacy-relay/bridge/legacy-relay-move-retry' import { connectTarget } from './ssh-connect-flow' import { disposeDesktopBrowserBridge, diff --git a/src/main/ipc/telemetry.ts b/src/main/ipc/telemetry.ts index d687b48c313..f093a434105 100644 --- a/src/main/ipc/telemetry.ts +++ b/src/main/ipc/telemetry.ts @@ -13,7 +13,8 @@ import { getOnboardingCohortAtEmit } from '../telemetry/onboarding-cohort-classi import { resolveConsent, type ConsentState } from '../telemetry/consent' import type { Store } from '../persistence/loading-store/store' import { isCohortExtendedEvent, isOnboardingEvent } from '../../shared/telemetry-events' -import type { EventName, EventProps, OptInVia } from '../../shared/telemetry-events' +import type { EventName, OptInVia } from '../../shared/telemetry-events' +import type { EventProps } from '../../shared/telemetry-event-classification' // Derive consent provenance synchronously from pre-mutation settings. let storeRef: Store | null = null diff --git a/src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts b/src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts index e5df76ef8cb..1eadd52492b 100644 --- a/src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts +++ b/src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts @@ -2,7 +2,7 @@ import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree import { beforeEach, describe, expect, it, vi } from 'vitest' import type { ProviderRequestId } from '../../shared/detected-worktree-provider-contract' import { toSshExecutionHostId } from '../../shared/execution-host' -import { getSshProviderAuthority } from '../ssh/ssh-provider-authority' +import { getSshProviderAuthority } from '../ssh/connection/authority/ssh-provider-authority' import { listWorktreesMock } from './worktrees-test-module-mocks' import { handlers, ipcEvent, setupWorktreeHandlers, store } from './worktrees-test-harness' diff --git a/src/main/ipc/worktrees-test-harness.ts b/src/main/ipc/worktrees-test-harness.ts index 59c12fb5087..06a130f5f2c 100644 --- a/src/main/ipc/worktrees-test-harness.ts +++ b/src/main/ipc/worktrees-test-harness.ts @@ -6,7 +6,7 @@ import { registerWorktreeHandlers } from './worktrees' import { __resetDetectedWorktreeScanCacheForTests } from './worktrees/listing/detected-worktree-scan-cache' import { clearConfiguredWorktreeSharedDirectoriesCacheForTests } from '../git/worktrees/content-paths/worktree-shared-directories' import { resetRetirementCollisionKeyCacheForTests } from '../workspaces/removal/retirement/worktree-name-retirement' -import { resetSshProviderAuthorities } from '../ssh/ssh-provider-authority' +import { resetSshProviderAuthorities } from '../ssh/connection/authority/ssh-provider-authority' import { createWorktreeRuntimeStub, type WorktreeRuntimeStub } from './worktrees-test-runtime-stub' import { handlers, mainWindow, store } from './worktrees-test-ipc-surface' import { configureMetadataPruningStoreMocks } from './worktrees-test-metadata-pruning-store' diff --git a/src/main/ipc/worktrees/listing/host-qualified-worktree-listing.ts b/src/main/ipc/worktrees/listing/host-qualified-worktree-listing.ts index 28f7f58c32c..5f0c9610d75 100644 --- a/src/main/ipc/worktrees/listing/host-qualified-worktree-listing.ts +++ b/src/main/ipc/worktrees/listing/host-qualified-worktree-listing.ts @@ -10,7 +10,7 @@ import type { HostQualifiedDetectedWorktreeResult, DirectSshDetectedWorktreeRequest } from '../../../../shared/detected-worktree-provider-contract' -import { isCurrentSshProviderAuthority } from '../../../ssh/ssh-provider-authority' +import { isCurrentSshProviderAuthority } from '../../../ssh/connection/authority/ssh-provider-authority' import { hasValidDirectSshAuthority, listDetectedWorktreesForCapturedRepo diff --git a/src/main/ipc/worktrees/listing/register-detected-worktree-handlers.ts b/src/main/ipc/worktrees/listing/register-detected-worktree-handlers.ts index ba2ea62e92e..460903d2195 100644 --- a/src/main/ipc/worktrees/listing/register-detected-worktree-handlers.ts +++ b/src/main/ipc/worktrees/listing/register-detected-worktree-handlers.ts @@ -10,7 +10,7 @@ import { registerSshProviderRequestAbort, getSshProviderAuthority, isCurrentSshProviderAuthority -} from '../../../ssh/ssh-provider-authority' +} from '../../../ssh/connection/authority/ssh-provider-authority' import type { DetectedWorktreeRequestArgs } from '../ipc-context-schemas' import { hasValidDirectSshAuthority, diff --git a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts index e18296418c1..0a0886b8a34 100644 --- a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts +++ b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts @@ -38,7 +38,9 @@ vi.mock('../runtime-environments/runtime-environment-transport-routing', () => ( vi.mock('../runtime-environments/runtime-environment-request-connections', () => ({ isRemoteRuntimeConnectionReady: () => false })) -vi.mock('../../ssh/orcad-terminal-census-client', () => ({ requestOrcadTerminalCensus: vi.fn() })) +vi.mock('../../managed-server/lifecycle/orcad-terminal-census-client', () => ({ + requestOrcadTerminalCensus: vi.fn() +})) const service = vi.hoisted(() => ({ add: vi.fn( async (): Promise<{ diff --git a/src/main/ipc/wsl/wsl-host-handlers.ts b/src/main/ipc/wsl/wsl-host-handlers.ts index e26fdbbb841..6f0d8f30492 100644 --- a/src/main/ipc/wsl/wsl-host-handlers.ts +++ b/src/main/ipc/wsl/wsl-host-handlers.ts @@ -37,7 +37,7 @@ import { isRemoteRuntimeConnectionReady } from '../runtime-environments/runtime- import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { reconcileWslHostBridgePorts } from '../../../shared/remote-runtime/host-store/runtime-environment-wsl-host-store' import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { requestOrcadTerminalCensus } from '../../ssh/orcad-terminal-census-client' +import { requestOrcadTerminalCensus } from '../../managed-server/lifecycle/orcad-terminal-census-client' import type { WslHostRuntimeAccess } from '../../wsl/host-lifecycle/wsl-host-server-stop' import { changesWslHostAccounts, diff --git a/src/main/ipc/wsl/wsl-move-driver-wiring.ts b/src/main/ipc/wsl/wsl-move-driver-wiring.ts index f44dd161e37..b66817c2556 100644 --- a/src/main/ipc/wsl/wsl-move-driver-wiring.ts +++ b/src/main/ipc/wsl/wsl-move-driver-wiring.ts @@ -73,12 +73,10 @@ import { setWslMoveReloadLanding, setWslMoveReloadableWindow } from '../../persistence/moving-wsl-projects/wsl-move-window-write-hold' -import { - commitRemoteOrcadMigrationCatalog, - listRemoteOrcadRepositories, - stageRemoteOrcadMigrationBlobChunk -} from '../../ssh/orcad-migration-catalog-client' -import { listRemoteOrcadFolderCatalog } from '../../ssh/orcad-server-folder-workspaces' +import { commitRemoteOrcadMigrationCatalog } from '../../managed-server/migration/catalog/orcad-migration-catalog-client' +import { listRemoteOrcadRepositories } from '../../managed-server/migration/linking/orcad-server-repositories' +import { stageRemoteOrcadMigrationBlobChunk } from '../../managed-server/migration/transfers/orcad-migration-chunk-client' +import { listRemoteOrcadFolderCatalog } from '../../managed-server/migration/linking/orcad-server-folder-workspaces' import { makeTerminalScrollbackSnapshotRef } from '../../pty/scrollback/terminal-scrollback-snapshots' import { pauseWorkspacesForProjectMove } from '../../window/project-move-pause' import { getWslHostService } from '../../wsl/host-lifecycle/wsl-host-service-instance' diff --git a/src/main/managed-server/activation/orcad-activation-fence-generation.test.ts b/src/main/managed-server/activation/orcad-activation-fence-generation.test.ts index e9d865c1042..251defb5795 100644 --- a/src/main/managed-server/activation/orcad-activation-fence-generation.test.ts +++ b/src/main/managed-server/activation/orcad-activation-fence-generation.test.ts @@ -12,7 +12,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' -import { unusedOrcadHostTransport } from '../../ssh/unused-host-transport.test-fixture' +import { unusedOrcadHostTransport } from '../testing/managed-host-transport.test-fixture' // Execute generated host guards in real local shells. const shell = vi.hoisted((): { env: NodeJS.ProcessEnv | undefined } => ({ env: undefined })) @@ -37,7 +37,7 @@ const { execOrcadRemote } = await import('../install/orcad-remote-runtime-contro const { OrcadFenceLostError, runWithOrcadFence } = await import('./orcad-activation-fence-scope') const { execOrcadStateMutation } = await import('../host-state/orcad-state-mutation-exec') const { clearOrcadStateSnapshotMembersCommand } = await import('../host-state/orcad-state-snapshot') -const { getRemoteHostPlatform } = await import('../../ssh/ssh-remote-platform') +const { getRemoteHostPlatform } = await import('../../ssh/remote-host/ssh-remote-platform') const homes: string[] = [] afterEach(() => { diff --git a/src/main/managed-server/activation/orcad-activation-fence-hold.ts b/src/main/managed-server/activation/orcad-activation-fence-hold.ts index 5ce5516e0de..d40fe5a8d71 100644 --- a/src/main/managed-server/activation/orcad-activation-fence-hold.ts +++ b/src/main/managed-server/activation/orcad-activation-fence-hold.ts @@ -7,7 +7,7 @@ import { import { readOrcadActivationTransaction } from './orcad-activation-transaction-store' import { orcadActivationFenceLockDir } from './orcad-activation-transaction' import { isRelayInstallLockStale } from '../install/remote-install-lock' -import { findExitedOwnLockToken } from '../../ssh/orcad-exited-own-lock' +import { findExitedOwnLockToken } from './orcad-exited-own-lock' import { orcadRemoteBaseDir } from '../install/orcad-remote-windows-node' export const ORCAD_ACTIVATION_FENCE_BUSY_CODE = 'orcad_activation_fence_busy' diff --git a/src/main/managed-server/activation/orcad-activation-host-test-harness.ts b/src/main/managed-server/activation/orcad-activation-host-test-harness.ts index a2e6c280e0c..a22c056cd8f 100644 --- a/src/main/managed-server/activation/orcad-activation-host-test-harness.ts +++ b/src/main/managed-server/activation/orcad-activation-host-test-harness.ts @@ -5,7 +5,7 @@ import { withActivatedVersion, type OrcadActivationRecord } from './orcad-activation-record' -import { isSnapshotCaptureCommand } from '../../ssh/orcad-snapshot-capture-command' +import { isSnapshotCaptureCommand } from './testing/orcad-snapshot-capture-command' import { sshCommandExitError } from '../../ssh/remote-exec/remote-exec-command' export const OLD = '0.1.0+aa01' diff --git a/src/main/managed-server/activation/orcad-activation-lock.ts b/src/main/managed-server/activation/orcad-activation-lock.ts index 88197048cfa..79251b4fd90 100644 --- a/src/main/managed-server/activation/orcad-activation-lock.ts +++ b/src/main/managed-server/activation/orcad-activation-lock.ts @@ -19,9 +19,9 @@ import { type OrcadFence } from './orcad-activation-fence-scope' import { orcadRemoteBaseDir, orcadWindowsHomeOpCommand } from '../install/orcad-remote-windows-node' -import { forgetHeldOrcadFence, rememberHeldOrcadFence } from '../../ssh/orcad-held-fence-tokens' -import { exitedOwnLockProof } from '../../ssh/orcad-exited-own-lock' -import { isWindowsRemoteHost } from '../../ssh/ssh-remote-platform' +import { forgetHeldOrcadFence, rememberHeldOrcadFence } from './orcad-held-fence-tokens' +import { exitedOwnLockProof } from './orcad-exited-own-lock' +import { isWindowsRemoteHost } from '../../ssh/remote-host/ssh-remote-platform' import { orcadActivationFenceLockDir, orcadActivationTransactionPath, diff --git a/src/main/managed-server/activation/orcad-activation-record-store.ts b/src/main/managed-server/activation/orcad-activation-record-store.ts index 9ee03f1d6b6..d26f115ecda 100644 --- a/src/main/managed-server/activation/orcad-activation-record-store.ts +++ b/src/main/managed-server/activation/orcad-activation-record-store.ts @@ -1,6 +1,6 @@ // Unreadable activation records must fail closed; treating them as absent could overwrite a live install and its rollback target. -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import type { OrcadHostTransport } from '../install/orcad-host-transport' +import { RELAY_REMOTE_DIR } from '../install/remote-install-root' import { ORCAD_ACTIVATION_FILENAME, emptyOrcadActivationRecord, @@ -9,7 +9,7 @@ import { type OrcadActivationReadResult, type OrcadActivationRecord } from './orcad-activation-record' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { readBoundedOrcadRemoteRecord, writeAtomicOrcadRemoteRecord diff --git a/src/main/managed-server/activation/orcad-activation-recovery.ts b/src/main/managed-server/activation/orcad-activation-recovery.ts index 9e01427416c..00dfd8c2323 100644 --- a/src/main/managed-server/activation/orcad-activation-recovery.ts +++ b/src/main/managed-server/activation/orcad-activation-recovery.ts @@ -14,16 +14,16 @@ import { withStaleOrcadActivationRecoveryLock } from './orcad-activation-lock' import { RemoteInstallLockBusyError } from '../install/remote-install-lock' -import { ensureOrcadSlotServing, resolveOrcadSlotIdentity } from '../../ssh/orcad-recovery-slot' +import { ensureOrcadSlotServing, resolveOrcadSlotIdentity } from './orcad-recovery-slot' import { reconcileOrcadDecommission } from '../lifecycle/orcad-decommission-recovery' import { recoverOrcadIncumbent, type OrcadIncumbentRecoveryOptions -} from '../../ssh/orcad-incumbent-recovery' +} from './orcad-incumbent-recovery' import type { OrcadManagedRefusal } from '../../../shared/orcad-managed-runtime' -import { resumeInterruptedOrcadCandidate } from '../../ssh/orcad-interrupted-candidate-resume' +import { resumeInterruptedOrcadCandidate } from './orcad-interrupted-candidate-resume' import { errorMessage } from '../../../shared/error-message' -import { isOrcadLaunchFailure } from '../../ssh/orcad-launch-failure' +import { isOrcadLaunchFailure } from './orcad-launch-failure' export type OrcadActivationRecoveryResult = | { outcome: 'none' } diff --git a/src/main/managed-server/activation/orcad-activation-transaction.ts b/src/main/managed-server/activation/orcad-activation-transaction.ts index 224450e4332..04ffe78cd7d 100644 --- a/src/main/managed-server/activation/orcad-activation-transaction.ts +++ b/src/main/managed-server/activation/orcad-activation-transaction.ts @@ -18,8 +18,8 @@ import { } from '../lifecycle/orcad-decommission-transaction' import { errorMessage } from '../../../shared/error-message' import { RELAY_INSTALL_LOCK_NAME } from '../../../shared/relay-install-lock-name' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { RELAY_REMOTE_DIR } from '../install/remote-install-root' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' export const ORCAD_ACTIVATION_TRANSACTION_FILENAME = 'transaction.json' export const ORCAD_ACTIVATION_TRANSACTION_DIRNAME = '.orcad-activation-transaction' diff --git a/src/main/ssh/orcad-active-readiness.ts b/src/main/managed-server/activation/orcad-active-readiness.ts similarity index 90% rename from src/main/ssh/orcad-active-readiness.ts rename to src/main/managed-server/activation/orcad-active-readiness.ts index 3e7b56ba5d0..a79f2e2e066 100644 --- a/src/main/ssh/orcad-active-readiness.ts +++ b/src/main/managed-server/activation/orcad-active-readiness.ts @@ -1,25 +1,22 @@ -import { - evaluateOrcadActivation, - type OrcadActivationExpectation -} from '../managed-server/activation/orcad-activation-gate' +import { evaluateOrcadActivation, type OrcadActivationExpectation } from './orcad-activation-gate' import { orcadLivenessProbeCommand, parseOrcadLiveness, type OrcadLaunchSpec, type OrcadReadinessParse -} from '../managed-server/install/orcad-remote-launch' +} from '../install/orcad-remote-launch' import { execOrcadRemote, launchOrcadAndAwaitReadiness, type OrcadRemoteExecTarget -} from '../managed-server/install/orcad-remote-runtime-control' +} from '../install/orcad-remote-runtime-control' import { parseOrcadReadinessWaitOutput, readOrcadReadinessNowCommand -} from '../managed-server/install/orcad-remote-readiness-wait' -import type { ServeReadiness } from '../server/serve-readiness' -import { withOrcadLogTail } from '../managed-server/install/orcad-remote-log-tail' -import type { RemoteHostPlatform } from './ssh-remote-platform' +} from '../install/orcad-remote-readiness-wait' +import type { ServeReadiness } from '../../server/serve-readiness' +import { withOrcadLogTail } from '../install/orcad-remote-log-tail' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' type OrcadReadinessFailureVerdict = 'exited' | 'unverifiable' | 'rejected' diff --git a/src/main/ssh/orcad-candidate-launch-verdict.ts b/src/main/managed-server/activation/orcad-candidate-launch-verdict.ts similarity index 74% rename from src/main/ssh/orcad-candidate-launch-verdict.ts rename to src/main/managed-server/activation/orcad-candidate-launch-verdict.ts index 3f7bb3afdac..30cb42340e2 100644 --- a/src/main/ssh/orcad-candidate-launch-verdict.ts +++ b/src/main/managed-server/activation/orcad-candidate-launch-verdict.ts @@ -1,14 +1,11 @@ -import { - evaluateOrcadActivation, - type OrcadActivationVerdict -} from '../managed-server/activation/orcad-activation-gate' -import { orcadActivationTransactionRoot } from '../managed-server/activation/orcad-activation-transaction' -import type { OrcadReadinessParse } from '../managed-server/install/orcad-remote-launch' +import { evaluateOrcadActivation, type OrcadActivationVerdict } from './orcad-activation-gate' +import { orcadActivationTransactionRoot } from './orcad-activation-transaction' +import type { OrcadReadinessParse } from '../install/orcad-remote-launch' import { launchOrcadAndAwaitReadiness, type OrcadRemoteExecTarget -} from '../managed-server/install/orcad-remote-runtime-control' -import { isUnconfirmedSshCommandTermination } from './remote-exec/remote-exec-command' +} from '../install/orcad-remote-runtime-control' +import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' type CandidateLaunchTarget = Parameters[0] & OrcadRemoteExecTarget & { diff --git a/src/main/ssh/orcad-candidate-preflight.ts b/src/main/managed-server/activation/orcad-candidate-preflight.ts similarity index 84% rename from src/main/ssh/orcad-candidate-preflight.ts rename to src/main/managed-server/activation/orcad-candidate-preflight.ts index 04171e13a87..8f0bddbcfac 100644 --- a/src/main/ssh/orcad-candidate-preflight.ts +++ b/src/main/managed-server/activation/orcad-candidate-preflight.ts @@ -1,5 +1,5 @@ -import { errorMessage } from '../../shared/error-message' -import { preflightInstalledOrcad } from '../managed-server/install/orcad-remote-preflight' +import { errorMessage } from '../../../shared/error-message' +import { preflightInstalledOrcad } from '../install/orcad-remote-preflight' /** Preflight before any stop; asked to, the candidate also names the daemon generations under the served data root. */ export async function preflightOrcadCandidate( diff --git a/src/main/ssh/orcad-daemon-protocol-crossing.ts b/src/main/managed-server/activation/orcad-daemon-protocol-crossing.ts similarity index 95% rename from src/main/ssh/orcad-daemon-protocol-crossing.ts rename to src/main/managed-server/activation/orcad-daemon-protocol-crossing.ts index 43778fcf1ea..f77f854f713 100644 --- a/src/main/ssh/orcad-daemon-protocol-crossing.ts +++ b/src/main/managed-server/activation/orcad-daemon-protocol-crossing.ts @@ -2,8 +2,8 @@ import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS, PROTOCOL_VERSION -} from '../daemon/protocol/daemon-protocol-version' -import type { OrcadTerminalCensus } from '../../shared/orcad-terminal-census' +} from '../../daemon/protocol/daemon-protocol-version' +import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' export type OrcadDaemonProtocolFacts = { protocolVersion: number diff --git a/src/main/ssh/orcad-exited-own-fence-mutation-race.test.ts b/src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts similarity index 94% rename from src/main/ssh/orcad-exited-own-fence-mutation-race.test.ts rename to src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts index 63021346395..1b656d1c3d3 100644 --- a/src/main/ssh/orcad-exited-own-fence-mutation-race.test.ts +++ b/src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts @@ -11,11 +11,11 @@ import { hostname, tmpdir, uptime } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { runProcess, spawnProcess } from '@orca/process-host' -import type * as ExecCommandModule from './remote-exec/remote-exec-command' -import { unusedOrcadHostTransport } from './unused-host-transport.test-fixture' +import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' +import { unusedOrcadHostTransport } from '../testing/managed-host-transport.test-fixture' // Run generated host-side proof commands in a real local shell. -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => { +vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => { const { runProcess: run } = await import('@orca/process-host') return { ...(await importOriginal()), @@ -27,13 +27,11 @@ vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => { const { exitedOwnLockProof } = await import('./orcad-exited-own-lock') const { initOrcadHeldFenceTokenFile, ORCAD_HELD_FENCE_TOKENS_FILE_NAME } = await import('./orcad-held-fence-tokens') -const { tryStealInstallLockCommand } = - await import('../managed-server/install/remote-install-lock-commands') -const { serializedStateMutationCommand } = - await import('../managed-server/host-state/orcad-state-snapshot') +const { tryStealInstallLockCommand } = await import('../install/remote-install-lock-commands') +const { serializedStateMutationCommand } = await import('../host-state/orcad-state-snapshot') const { ORCAD_FENCE_LOST_EXIT, ORCAD_FENCE_LOST_MARKER } = - await import('../managed-server/activation/orcad-activation-fence-scope') -const { getRemoteHostPlatform } = await import('./ssh-remote-platform') + await import('./orcad-activation-fence-scope') +const { getRemoteHostPlatform } = await import('../../ssh/remote-host/ssh-remote-platform') const OWNER = '.orca-fence-owner' // Above every Linux and macOS pid_max, so no process can hold it. diff --git a/src/main/ssh/orcad-exited-own-fence.test.ts b/src/main/managed-server/activation/orcad-exited-own-fence.test.ts similarity index 93% rename from src/main/ssh/orcad-exited-own-fence.test.ts rename to src/main/managed-server/activation/orcad-exited-own-fence.test.ts index 5dd4eef2fa6..ac11f8bbd2c 100644 --- a/src/main/ssh/orcad-exited-own-fence.test.ts +++ b/src/main/managed-server/activation/orcad-exited-own-fence.test.ts @@ -11,14 +11,14 @@ import { import { hostname, tmpdir, uptime } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as ExecCommandModule from './remote-exec/remote-exec-command' -import { unusedOrcadHostTransport } from './unused-host-transport.test-fixture' +import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' +import { unusedOrcadHostTransport } from '../testing/managed-host-transport.test-fixture' // Run generated host-side checks in a real local shell. const shell = vi.hoisted((): { env: NodeJS.ProcessEnv | undefined } => ({ env: undefined })) -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => { +vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => { const { runProcess } = await import('@orca/process-host') - const { sshCommandExitError } = await import('./remote-exec/remote-exec-command') + const { sshCommandExitError } = await import('../../ssh/remote-exec/remote-exec-command') return { ...(await importOriginal()), execCommand: async (_conn: unknown, command: string) => { @@ -31,13 +31,11 @@ vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => { } }) -const { orcadActivationFenceRefusal } = - await import('../managed-server/activation/orcad-activation-fence-hold') -const { withOrcadActivationLock } = - await import('../managed-server/activation/orcad-activation-lock') +const { orcadActivationFenceRefusal } = await import('./orcad-activation-fence-hold') +const { withOrcadActivationLock } = await import('./orcad-activation-lock') const { initOrcadHeldFenceTokenFile, ORCAD_HELD_FENCE_TOKENS_FILE_NAME } = await import('./orcad-held-fence-tokens') -const { getRemoteHostPlatform } = await import('./ssh-remote-platform') +const { getRemoteHostPlatform } = await import('../../ssh/remote-host/ssh-remote-platform') // Above every Linux and macOS pid_max, so no process can hold it. const EXITED_PID = 4_194_304 + 1 diff --git a/src/main/ssh/orcad-exited-own-install-lock.test.ts b/src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts similarity index 84% rename from src/main/ssh/orcad-exited-own-install-lock.test.ts rename to src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts index cbd606f8cd0..30e2b4005ac 100644 --- a/src/main/ssh/orcad-exited-own-install-lock.test.ts +++ b/src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts @@ -11,13 +11,13 @@ import { import { hostname, tmpdir, uptime } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as ExecCommandModule from './remote-exec/remote-exec-command' -import { unusedOrcadHostTransport } from './unused-host-transport.test-fixture' +import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' +import { unusedOrcadHostTransport } from '../testing/managed-host-transport.test-fixture' // Run generated host-side checks in a real local shell. -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => { +vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => { const { runProcess } = await import('@orca/process-host') - const { sshCommandExitError } = await import('./remote-exec/remote-exec-command') + const { sshCommandExitError } = await import('../../ssh/remote-exec/remote-exec-command') return { ...(await importOriginal()), execCommand: async (_conn: unknown, command: string) => { @@ -31,11 +31,11 @@ vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => { }) const { acquireInstallLock, RemoteInstallLockBusyError } = - await import('../managed-server/install/remote-install-lock') + await import('../install/remote-install-lock') const { exitedOwnLockProof } = await import('./orcad-exited-own-lock') const { initOrcadHeldFenceTokenFile, ORCAD_HELD_FENCE_TOKENS_FILE_NAME } = await import('./orcad-held-fence-tokens') -const { getRemoteHostPlatform } = await import('./ssh-remote-platform') +const { getRemoteHostPlatform } = await import('../../ssh/remote-host/ssh-remote-platform') // Above every Linux and macOS pid_max, so no process can hold it. const EXITED_PID = 4_194_304 + 1 @@ -84,15 +84,6 @@ function versionDirWithLock(owner: string, heldToken: string) { describe.skipIf(process.platform === 'win32')( 'an install lock this desktop’s exited process left', () => { - it('is taken over at once', async () => { - const { lock, store, acquire } = versionDirWithLock('t-exited', 't-exited') - const started = Date.now() - await acquire(5_000) - expect(Date.now() - started).toBeLessThan(5_000) - expect(readFileSync(join(lock, '.orca-fence-owner'), 'utf-8')).toBe('t-relaunch') - expect(readFileSync(store, 'utf-8')).not.toContain('t-exited') - }) - it('never writes to the lock while proving its holder exited', async () => { const { lock, proof } = versionDirWithLock('t-exited', 't-exited') const before = statSync(lock).mtimeMs diff --git a/src/main/ssh/orcad-exited-own-lock-windows.test.ts b/src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts similarity index 81% rename from src/main/ssh/orcad-exited-own-lock-windows.test.ts rename to src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts index baf0789464b..2e33ab43be0 100644 --- a/src/main/ssh/orcad-exited-own-lock-windows.test.ts +++ b/src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts @@ -2,15 +2,15 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { hostname, tmpdir, uptime } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ExecCommandModule from './remote-exec/remote-exec-command' -import { unusedOrcadHostTransport } from './unused-host-transport.test-fixture' +import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' +import { unusedOrcadHostTransport } from '../testing/managed-host-transport.test-fixture' // Host-script checks run separately against the real script; these cases cover client interpretation. const remote = vi.hoisted((): { commands: string[]; reply: string } => ({ commands: [], reply: '' })) -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand: async (_conn: unknown, command: string) => { remote.commands.push(command) @@ -21,7 +21,7 @@ vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ const { findExitedOwnLockToken } = await import('./orcad-exited-own-lock') const { initOrcadHeldFenceTokenFile, ORCAD_HELD_FENCE_TOKENS_FILE_NAME } = await import('./orcad-held-fence-tokens') -const { getRemoteHostPlatform } = await import('./ssh-remote-platform') +const { getRemoteHostPlatform } = await import('../../ssh/remote-host/ssh-remote-platform') // Above every Linux and macOS pid_max, so no process can hold it. const EXITED_PID = 4_194_304 + 1 @@ -66,25 +66,12 @@ describe('reclaiming this desktop’s exited lock on a Windows host', () => { expect(op).toMatch(/fence-exited-owner"? "?[^ ]*\.install-lock"? "?1"?/u) }) - it('finds nothing when the host kept the lock', async () => { - hold({ token: 't-exited', pid: EXITED_PID }) - remote.reply = 'KEPT\n' - await expect(find(false)).resolves.toBeNull() - expect(checkOps()).toHaveLength(1) - }) - it('ignores an answer naming a token it did not offer', async () => { hold({ token: 't-exited', pid: EXITED_PID }) remote.reply = 'EXITED_OWNER t-foreign\n' await expect(find(false)).resolves.toBeNull() }) - it('asks the host nothing while no holder is proven exited', async () => { - hold({ token: 't-live', pid: process.pid }) - await expect(find(true)).resolves.toBeNull() - expect(remote.commands).toEqual([]) - }) - it('falls back to the stale window when the check would not fit cmd.exe', async () => { hold({ token: 't-exited', pid: EXITED_PID }) remote.reply = 'EXITED_OWNER t-exited\n' diff --git a/src/main/ssh/orcad-exited-own-lock.ts b/src/main/managed-server/activation/orcad-exited-own-lock.ts similarity index 86% rename from src/main/ssh/orcad-exited-own-lock.ts rename to src/main/managed-server/activation/orcad-exited-own-lock.ts index 0d269f0ea4a..18a72abb623 100644 --- a/src/main/ssh/orcad-exited-own-lock.ts +++ b/src/main/managed-server/activation/orcad-exited-own-lock.ts @@ -2,28 +2,28 @@ import { ORCAD_FENCE_OWNER_FILENAME, posixOrcadFenceOwnedTest -} from '../managed-server/activation/orcad-activation-fence-scope' +} from './orcad-activation-fence-scope' import { forgetHeldOrcadFence, orcadFenceTokensHeldByExitedProcesses } from './orcad-held-fence-tokens' -import { readBoundedOrcadRemoteRecord } from '../managed-server/install/orcad-remote-record-file' +import { readBoundedOrcadRemoteRecord } from '../install/orcad-remote-record-file' import { execOrcadRemote, type OrcadRemoteExecTarget -} from '../managed-server/install/orcad-remote-runtime-control' +} from '../install/orcad-remote-runtime-control' import { installOrcadWindowsHostScript, orcadWindowsHostOpCommand -} from '../managed-server/install/orcad-remote-windows-node' +} from '../install/orcad-remote-windows-node' import { ORCAD_EXITED_OWN_LOCK_QUIET_SECONDS, ORCAD_STATE_MUTATION_LOCK_DIRNAME -} from '../managed-server/host-state/orcad-state-snapshot-members' -import { CMD_EXE_COMMAND_LINE_MAX_CHARS } from '../providers/windows-shell-args' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import type { InstallLockExitedOwnerProof } from '../managed-server/install/remote-install-lock' -import { isWindowsRemoteHost, joinRemotePath } from './ssh-remote-platform' +} from '../host-state/orcad-state-snapshot-members' +import { CMD_EXE_COMMAND_LINE_MAX_CHARS } from '../../providers/windows-shell-args' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import type { InstallLockExitedOwnerProof } from '../install/remote-install-lock' +import { isWindowsRemoteHost, joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' // Bound Windows command length; omitted older tokens simply wait for normal stale-lock arbitration. const MAX_WINDOWS_CANDIDATES = 16 diff --git a/src/main/ssh/orcad-fenced-stop.test.ts b/src/main/managed-server/activation/orcad-fenced-stop.test.ts similarity index 95% rename from src/main/ssh/orcad-fenced-stop.test.ts rename to src/main/managed-server/activation/orcad-fenced-stop.test.ts index e863f970951..6aa1c2bad7e 100644 --- a/src/main/ssh/orcad-fenced-stop.test.ts +++ b/src/main/managed-server/activation/orcad-fenced-stop.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { ORCAD_UPDATE_ADMISSION_STOP_BY_MS } from '../../shared/orcad-terminal-census' +import { ORCAD_UPDATE_ADMISSION_STOP_BY_MS } from '../../../shared/orcad-terminal-census' import { runFencedStop, type FencedStop } from './orcad-fenced-stop' const idle = { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 3 } diff --git a/src/main/ssh/orcad-fenced-stop.ts b/src/main/managed-server/activation/orcad-fenced-stop.ts similarity index 95% rename from src/main/ssh/orcad-fenced-stop.ts rename to src/main/managed-server/activation/orcad-fenced-stop.ts index 19eba0ca4c6..67333840fed 100644 --- a/src/main/ssh/orcad-fenced-stop.ts +++ b/src/main/managed-server/activation/orcad-fenced-stop.ts @@ -3,8 +3,8 @@ import { ORCAD_UPDATE_ADMISSION_STOP_BY_MS, type OrcadTerminalCensus, UNVERIFIABLE_ORCAD_TERMINAL_CENSUS -} from '../../shared/orcad-terminal-census' -import type { OrcadTerminalCensusRequestOptions } from './orcad-terminal-census-client' +} from '../../../shared/orcad-terminal-census' +import type { OrcadTerminalCensusRequestOptions } from '../lifecycle/orcad-terminal-census-client' /** Only the final count closes terminal admission: the initial update census may precede a long upload. */ export function updateTerminalCounts( diff --git a/src/main/ssh/orcad-gc-transaction-pins.ts b/src/main/managed-server/activation/orcad-gc-transaction-pins.ts similarity index 73% rename from src/main/ssh/orcad-gc-transaction-pins.ts rename to src/main/managed-server/activation/orcad-gc-transaction-pins.ts index 66becbec513..349666af14b 100644 --- a/src/main/ssh/orcad-gc-transaction-pins.ts +++ b/src/main/managed-server/activation/orcad-gc-transaction-pins.ts @@ -1,10 +1,10 @@ /** Pin every journaled slot needed for recovery. An unreadable journal or unjournaled held fence hides transaction state, so GC must retain everything. */ -import { orcadInstallDirNames } from '../managed-server/activation/orcad-activation-record' -import type { OrcadActivationTransaction } from '../managed-server/activation/orcad-activation-transaction' -import { readOrcadActivationTransaction } from '../managed-server/activation/orcad-activation-transaction-store' -import { orcadActivationFenceExists } from '../managed-server/activation/orcad-activation-lock' -import { isUnconfirmedSshCommandTermination } from './remote-exec/remote-exec-command' -import type { OrcadRemoteExecTarget } from '../managed-server/install/orcad-remote-runtime-control' +import { orcadInstallDirNames } from './orcad-activation-record' +import type { OrcadActivationTransaction } from './orcad-activation-transaction' +import { readOrcadActivationTransaction } from './orcad-activation-transaction-store' +import { orcadActivationFenceExists } from './orcad-activation-lock' +import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' +import type { OrcadRemoteExecTarget } from '../install/orcad-remote-runtime-control' type OrcadGcTransactionPins = { state: 'pinned'; dirNames: string[] } | { state: 'keep-all' } diff --git a/src/main/ssh/orcad-held-fence-tokens.ts b/src/main/managed-server/activation/orcad-held-fence-tokens.ts similarity index 97% rename from src/main/ssh/orcad-held-fence-tokens.ts rename to src/main/managed-server/activation/orcad-held-fence-tokens.ts index 2abd9920991..2cf6c630a66 100644 --- a/src/main/ssh/orcad-held-fence-tokens.ts +++ b/src/main/managed-server/activation/orcad-held-fence-tokens.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs' import { hostname, uptime } from 'node:os' import { dirname, join } from 'node:path' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { writeDurableSecureJsonFile } from '../../../shared/secure-storage/secure-file' export const ORCAD_HELD_FENCE_TOKENS_FILE_NAME = 'orcad-held-fence-tokens.json' // Older entries are leaks from releases never confirmed; the fence went stale long ago anyway. diff --git a/src/main/ssh/orcad-host-version-admission.ts b/src/main/managed-server/activation/orcad-host-version-admission.ts similarity index 81% rename from src/main/ssh/orcad-host-version-admission.ts rename to src/main/managed-server/activation/orcad-host-version-admission.ts index 5d1ce7580dc..0c16051d522 100644 --- a/src/main/ssh/orcad-host-version-admission.ts +++ b/src/main/managed-server/activation/orcad-host-version-admission.ts @@ -1,6 +1,6 @@ /** Reject activation over state a newer host build may already have migrated. */ -import { compareAppVersions } from '../../shared/app-version' -import type { OrcadActivationRecord } from '../managed-server/activation/orcad-activation-record' +import { compareAppVersions } from '../../../shared/app-version' +import type { OrcadActivationRecord } from './orcad-activation-record' export type OrcadHostVersionRefusal = 'host-newer' diff --git a/src/main/ssh/orcad-incumbent-recovery.ts b/src/main/managed-server/activation/orcad-incumbent-recovery.ts similarity index 86% rename from src/main/ssh/orcad-incumbent-recovery.ts rename to src/main/managed-server/activation/orcad-incumbent-recovery.ts index d1f760d3e60..d6650de7861 100644 --- a/src/main/ssh/orcad-incumbent-recovery.ts +++ b/src/main/managed-server/activation/orcad-incumbent-recovery.ts @@ -1,18 +1,18 @@ /** Restore changed state only after proven slot exit and operator consent: a launched RPC server may have created terminals the stopped host cannot census, making the snapshot stale. Use the same rule for failure and crash recovery. */ -import { execOrcadStateMutation } from '../managed-server/host-state/orcad-state-mutation-exec' -import { orcadRemoteBaseDir } from '../managed-server/install/orcad-remote-windows-node' -import type { ServeReadiness } from '../server/serve-readiness' -import { RELAY_REMOTE_DIR } from './remote-exec/remote-frame-protocol' -import { ORCAD_STATE_SNAPSHOT_DIR } from '../managed-server/activation/orcad-activation-record' -import type { OrcadSnapshotVerdict } from '../managed-server/activation/orcad-activation-transaction' +import { execOrcadStateMutation } from '../host-state/orcad-state-mutation-exec' +import { orcadRemoteBaseDir } from '../install/orcad-remote-windows-node' +import type { ServeReadiness } from '../../server/serve-readiness' +import { RELAY_REMOTE_DIR } from '../install/remote-install-root' +import { ORCAD_STATE_SNAPSHOT_DIR } from './orcad-activation-record' +import type { OrcadSnapshotVerdict } from './orcad-activation-transaction' import { clearOrcadStateSnapshotMembersCommand, compareOrcadStateSnapshotCommand, orcadSnapshotIsUnchanged, parseOrcadSnapshotRestore, restoreOrcadStateSnapshotCommand -} from '../managed-server/host-state/orcad-state-snapshot' -import { execOrcadRemote } from '../managed-server/install/orcad-remote-runtime-control' +} from '../host-state/orcad-state-snapshot' +import { execOrcadRemote } from '../install/orcad-remote-runtime-control' import { ensureOrcadSlotServing, launchOrcadSlot, @@ -20,8 +20,8 @@ import { type OrcadSlotIdentity, type OrcadSlotOptions } from './orcad-recovery-slot' -import { joinRemotePath } from './ssh-remote-platform' -import { ORCAD_RECOVERY_CHANGED_STATE_CODE } from '../../shared/orcad-managed-runtime' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' +import { ORCAD_RECOVERY_CHANGED_STATE_CODE } from '../../../shared/orcad-managed-runtime' export type OrcadIncumbentRecoveryOptions = OrcadSlotOptions & { /** The operator accepted restoring the snapshot over state a launched build changed. */ diff --git a/src/main/ssh/orcad-initial-activation-admission.ts b/src/main/managed-server/activation/orcad-initial-activation-admission.ts similarity index 87% rename from src/main/ssh/orcad-initial-activation-admission.ts rename to src/main/managed-server/activation/orcad-initial-activation-admission.ts index 32b65982b56..f346413dcfb 100644 --- a/src/main/ssh/orcad-initial-activation-admission.ts +++ b/src/main/managed-server/activation/orcad-initial-activation-admission.ts @@ -1,10 +1,14 @@ /** Before first activation, rule out hand-started orcad/headless owners of the data root. Live, unreadable or unexpected PID records defer to avoid concurrent owners. */ -import { ORCAD_LOCK_FILE_NAME } from '../orcad/orcad-instance-lock' -import { PRIMARY_RUNTIME_METADATA_FILE } from '../../shared/runtime-bootstrap' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { selectOrcadSlotRuntimeCommand } from '../managed-server/install/orcad-remote-runtime' -import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform } from './ssh-remote-platform' -import { orcadWindowsSlotOpCommand } from '../managed-server/install/orcad-remote-windows-node' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { PRIMARY_RUNTIME_METADATA_FILE } from '../../../shared/runtime-bootstrap' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { selectOrcadSlotRuntimeCommand } from '../install/orcad-remote-runtime' +import { + isWindowsRemoteHost, + joinRemotePath, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' +import { orcadWindowsSlotOpCommand } from '../install/orcad-remote-windows-node' const OWNER_RECORD_MAX_BYTES = 64 * 1024 diff --git a/src/main/ssh/orcad-installed-activation.ts b/src/main/managed-server/activation/orcad-installed-activation.ts similarity index 86% rename from src/main/ssh/orcad-installed-activation.ts rename to src/main/managed-server/activation/orcad-installed-activation.ts index 1fbe2e6746f..28d231bc668 100644 --- a/src/main/ssh/orcad-installed-activation.ts +++ b/src/main/managed-server/activation/orcad-installed-activation.ts @@ -1,57 +1,54 @@ /** Journal durably before mutation so interrupted deploys can finish or recover. Release the fence only once the host is provably settled on one slot. */ -import { orcadRemoteBaseDir } from '../managed-server/install/orcad-remote-windows-node' +import { orcadRemoteBaseDir } from '../install/orcad-remote-windows-node' import { randomUUID } from 'node:crypto' -import type { OrcadDeployOptions, OrcadDeployResult } from './orcad-remote-deploy' -import { isUnconfirmedSshCommandTermination } from './remote-exec/remote-exec-command' +import type { OrcadDeployOptions, OrcadDeployResult } from '../install/orcad-remote-deploy' +import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' import { withActivatedVersion, type OrcadActivationRecord, type OrcadStateSnapshot -} from '../managed-server/activation/orcad-activation-record' +} from './orcad-activation-record' import { readOrcadActivationRecord, writeOrcadActivationRecord -} from '../managed-server/activation/orcad-activation-record-store' +} from './orcad-activation-record-store' import { launchAndJudgeOrcadSlot } from './orcad-candidate-launch-verdict' import { planOrcadUpdate } from './orcad-update-plan' import { type OrcadTerminalCensus, UNVERIFIABLE_ORCAD_TERMINAL_CENSUS -} from '../../shared/orcad-terminal-census' +} from '../../../shared/orcad-terminal-census' import { runFencedStop } from './orcad-fenced-stop' import { censusNeedsHostDaemonProtocols, CURRENT_ORCAD_DAEMON_PROTOCOL } from './orcad-daemon-protocol-crossing' -import { ORCAD_LOG_FILENAME } from '../managed-server/install/orcad-remote-host-support' -import { orcadSnapshotFailureReason } from '../managed-server/host-state/orcad-state-snapshot-space' +import { ORCAD_LOG_FILENAME } from '../install/orcad-remote-host-support' +import { orcadSnapshotFailureReason } from '../host-state/orcad-state-snapshot-space' import { ORCAD_SNAPSHOT_SPACE_INSUFFICIENT_CODE, orcadSnapshotRoomRefusal, orcadSnapshotsRoot -} from './orcad-snapshot-room' +} from '../host-state/orcad-snapshot-room' import { captureOrcadStateSnapshotCommand, orcadSnapshotDirName, parseOrcadSnapshotCapture -} from '../managed-server/host-state/orcad-state-snapshot' -import { joinRemotePath } from './ssh-remote-platform' -import { computeLocalOrcadBuildHash } from './orcad-local-build-hash' +} from '../host-state/orcad-state-snapshot' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' +import { computeLocalOrcadBuildHash } from '../install/orcad-local-build-hash' import { preflightOrcadCandidate } from './orcad-candidate-preflight' -import type { OrcadActivationLockControl } from '../managed-server/activation/orcad-activation-lock' -import type { OrcadActivateTransaction } from '../managed-server/activation/orcad-activation-transaction' +import type { OrcadActivationLockControl } from './orcad-activation-lock' +import type { OrcadActivateTransaction } from './orcad-activation-transaction' import { createOrcadActivationTransaction, withOrcadActivationCandidateReady, withOrcadActivationIncumbentStopped, withOrcadActivationSnapshot -} from '../managed-server/activation/orcad-activation-transaction-transitions' -import { writeOrcadActivationTransaction } from '../managed-server/activation/orcad-activation-transaction-store' -import { - execOrcadRemoteOr, - withoutAbortSignal -} from '../managed-server/install/orcad-remote-runtime-control' -import { execOrcadStateMutationOr } from '../managed-server/host-state/orcad-state-mutation-exec' +} from './orcad-activation-transaction-transitions' +import { writeOrcadActivationTransaction } from './orcad-activation-transaction-store' +import { execOrcadRemoteOr, withoutAbortSignal } from '../install/orcad-remote-runtime-control' +import { execOrcadStateMutationOr } from '../host-state/orcad-state-mutation-exec' import { initialOrcadActivationAdmissionCommand, parseInitialOrcadActivationAdmission @@ -67,9 +64,9 @@ import { restoreAfterRejectedCandidate, stopTransactionIncumbent } from './orcad-transaction-incumbent' -import { withOrcadLogTail } from '../managed-server/install/orcad-remote-log-tail' -import { orcadCandidateLaunchFailureCode } from '../orcad/orcad-host-unavailable' -import { errorMessage } from '../../shared/error-message' +import { withOrcadLogTail } from '../install/orcad-remote-log-tail' +import { orcadCandidateLaunchFailureCode } from '../../orcad/orcad-host-unavailable' +import { errorMessage } from '../../../shared/error-message' type Outcome = Extract diff --git a/src/main/ssh/orcad-interrupted-candidate-resume.ts b/src/main/managed-server/activation/orcad-interrupted-candidate-resume.ts similarity index 83% rename from src/main/ssh/orcad-interrupted-candidate-resume.ts rename to src/main/managed-server/activation/orcad-interrupted-candidate-resume.ts index f10b48520dd..da0b2de2d1e 100644 --- a/src/main/ssh/orcad-interrupted-candidate-resume.ts +++ b/src/main/managed-server/activation/orcad-interrupted-candidate-resume.ts @@ -1,16 +1,16 @@ /** Resume through the original readiness gate before undoing: the candidate may already serve changed state, and stopping it could require operator consent before anything can serve again. */ -import type { ServeReadiness } from '../server/serve-readiness' -import { withActivatedVersion } from '../managed-server/activation/orcad-activation-record' -import { writeOrcadActivationRecord } from '../managed-server/activation/orcad-activation-record-store' -import type { OrcadActivateTransaction } from '../managed-server/activation/orcad-activation-transaction' -import { writeOrcadActivationTransaction } from '../managed-server/activation/orcad-activation-transaction-store' -import { withOrcadActivationCandidateReady } from '../managed-server/activation/orcad-activation-transaction-transitions' +import type { ServeReadiness } from '../../server/serve-readiness' +import { withActivatedVersion } from './orcad-activation-record' +import { writeOrcadActivationRecord } from './orcad-activation-record-store' +import type { OrcadActivateTransaction } from './orcad-activation-transaction' +import { writeOrcadActivationTransaction } from './orcad-activation-transaction-store' +import { withOrcadActivationCandidateReady } from './orcad-activation-transaction-transitions' import { OrcadActiveReadinessError } from './orcad-active-readiness' -import { orcadLivenessProvenExited } from '../managed-server/install/orcad-remote-launch' +import { orcadLivenessProvenExited } from '../install/orcad-remote-launch' import { ORCAD_RECOVERY_CHANGED_STATE_CODE, type OrcadManagedRefusal -} from '../../shared/orcad-managed-runtime' +} from '../../../shared/orcad-managed-runtime' import { ensureOrcadSlotServing, orcadSlotDir, diff --git a/src/main/ssh/orcad-launch-failure.ts b/src/main/managed-server/activation/orcad-launch-failure.ts similarity index 84% rename from src/main/ssh/orcad-launch-failure.ts rename to src/main/managed-server/activation/orcad-launch-failure.ts index b999cfd4e2e..21eefd1bde2 100644 --- a/src/main/ssh/orcad-launch-failure.ts +++ b/src/main/managed-server/activation/orcad-launch-failure.ts @@ -1,4 +1,4 @@ -import { OrcadWindowsLaunchFailedError } from '../managed-server/install/orcad-remote-launch-windows' +import { OrcadWindowsLaunchFailedError } from '../install/orcad-remote-launch-windows' import { OrcadLaunchReadinessError } from './orcad-active-readiness' /** A launch that ended a run: it never became ready, or the host reported it could not start. */ diff --git a/src/main/ssh/orcad-recovery-slot.ts b/src/main/managed-server/activation/orcad-recovery-slot.ts similarity index 89% rename from src/main/ssh/orcad-recovery-slot.ts rename to src/main/managed-server/activation/orcad-recovery-slot.ts index 40a554ded86..f9c1c09668a 100644 --- a/src/main/ssh/orcad-recovery-slot.ts +++ b/src/main/managed-server/activation/orcad-recovery-slot.ts @@ -1,9 +1,9 @@ /** Only positive host evidence proves slot exit. Unanswered probes stay unverifiable and never authorize starting a second slot. */ -import type { ServeReadiness } from '../server/serve-readiness' -import type { OrcadActivationExpectation } from '../managed-server/activation/orcad-activation-gate' -import { ORCAD_INSTALL_MODEL } from '../managed-server/install/remote-install-model' -import { computeRemoteInstallDir } from '../managed-server/install/remote-versioned-install' -import { readRemoteOrcadBuildHash } from '../managed-server/install/orcad-remote-build-hash' +import type { ServeReadiness } from '../../server/serve-readiness' +import type { OrcadActivationExpectation } from './orcad-activation-gate' +import { ORCAD_INSTALL_MODEL } from '../install/remote-install-model' +import { computeRemoteInstallDir } from '../install/remote-versioned-install' +import { readRemoteOrcadBuildHash } from '../install/orcad-remote-build-hash' import { launchOrcadSlotAndAwaitReadiness, OrcadActiveReadinessError, @@ -14,17 +14,17 @@ import { orcadLivenessProvenExited, parseOrcadLiveness, type OrcadLiveness -} from '../managed-server/install/orcad-remote-launch' +} from '../install/orcad-remote-launch' import { parseOrcadStopOutcome, stopOrcadCommand, type OrcadStopOutcome -} from '../managed-server/install/orcad-remote-process-control' +} from '../install/orcad-remote-process-control' import { execOrcadRemote, type OrcadRemoteExecTarget -} from '../managed-server/install/orcad-remote-runtime-control' -import { orcadActivationTransactionRoot } from '../managed-server/activation/orcad-activation-transaction' +} from '../install/orcad-remote-runtime-control' +import { orcadActivationTransactionRoot } from './orcad-activation-transaction' import { initialOrcadActivationAdmissionCommand, parseInitialOrcadActivationAdmission diff --git a/src/main/ssh/orcad-retained-fence-takeover.test.ts b/src/main/managed-server/activation/orcad-retained-fence-takeover.test.ts similarity index 87% rename from src/main/ssh/orcad-retained-fence-takeover.test.ts rename to src/main/managed-server/activation/orcad-retained-fence-takeover.test.ts index 48b29143b14..33c12a83d5d 100644 --- a/src/main/ssh/orcad-retained-fence-takeover.test.ts +++ b/src/main/managed-server/activation/orcad-retained-fence-takeover.test.ts @@ -7,9 +7,9 @@ import { orphanInstallLockCommand, tryCreateInstallLockCommand, tryStealInstallLockCommand -} from '../managed-server/install/remote-install-lock-commands' -import { INSTALL_LOCK_STALE_SECONDS } from '../managed-server/install/remote-install-lock' -import { getRemoteHostPlatform } from './ssh-remote-platform' +} from '../install/remote-install-lock-commands' +import { INSTALL_LOCK_STALE_SECONDS } from '../install/remote-install-lock' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const host = getRemoteHostPlatform(process.platform === 'darwin' ? 'darwin-arm64' : 'linux-x64') const roots: string[] = [] diff --git a/src/main/ssh/orcad-running-version-adoption.ts b/src/main/managed-server/activation/orcad-running-version-adoption.ts similarity index 82% rename from src/main/ssh/orcad-running-version-adoption.ts rename to src/main/managed-server/activation/orcad-running-version-adoption.ts index 065de51f2e9..f3e64ead80d 100644 --- a/src/main/ssh/orcad-running-version-adoption.ts +++ b/src/main/managed-server/activation/orcad-running-version-adoption.ts @@ -1,11 +1,11 @@ /** Pair with an already-running foreign build before considering update; an unpaired first deploy cannot census its terminals. */ -import type { ServeReadiness } from '../server/serve-readiness' -import type { OrcadManagedDeferral } from '../../shared/orcad-managed-runtime' -import { orcadActivationFenceRefusal } from '../managed-server/activation/orcad-activation-fence-hold' +import type { ServeReadiness } from '../../server/serve-readiness' +import type { OrcadManagedDeferral } from '../../../shared/orcad-managed-runtime' +import { orcadActivationFenceRefusal } from './orcad-activation-fence-hold' import { OrcadActiveReadinessError, probeActiveOrcadReadiness } from './orcad-active-readiness' -import type { OrcadActivationRecord } from '../managed-server/activation/orcad-activation-record' -import { readOrcadActivationRecord } from '../managed-server/activation/orcad-activation-record-store' -import { wakeStoppedManagedOrcad } from '../managed-server/lifecycle/orcad-managed-wake' +import type { OrcadActivationRecord } from './orcad-activation-record' +import { readOrcadActivationRecord } from './orcad-activation-record-store' +import { wakeStoppedManagedOrcad } from '../lifecycle/orcad-managed-wake' import { resolveOrcadSlotIdentity, type OrcadSlotOptions } from './orcad-recovery-slot' export type OrcadRunningAdoption = { diff --git a/src/main/ssh/orcad-transaction-incumbent.ts b/src/main/managed-server/activation/orcad-transaction-incumbent.ts similarity index 89% rename from src/main/ssh/orcad-transaction-incumbent.ts rename to src/main/managed-server/activation/orcad-transaction-incumbent.ts index f3aceab470e..d9b28065333 100644 --- a/src/main/ssh/orcad-transaction-incumbent.ts +++ b/src/main/managed-server/activation/orcad-transaction-incumbent.ts @@ -1,7 +1,7 @@ -import type { OrcadActivationLockControl } from '../managed-server/activation/orcad-activation-lock' -import type { OrcadSnapshotVerdict } from '../managed-server/activation/orcad-activation-transaction' -import { orcadStopFreedTheHost } from '../managed-server/install/orcad-remote-process-control' -import { withoutAbortSignal } from '../managed-server/install/orcad-remote-runtime-control' +import type { OrcadActivationLockControl } from './orcad-activation-lock' +import type { OrcadSnapshotVerdict } from './orcad-activation-transaction' +import { orcadStopFreedTheHost } from '../install/orcad-remote-process-control' +import { withoutAbortSignal } from '../install/orcad-remote-runtime-control' import { launchOrcadSlot, stopOrcadSlot, @@ -10,7 +10,7 @@ import { type OrcadSlotOptions } from './orcad-recovery-slot' import { recoverOrcadIncumbent } from './orcad-incumbent-recovery' -import { errorMessage } from '../../shared/error-message' +import { errorMessage } from '../../../shared/error-message' /** Return null on proven exit; otherwise retain the fence when a delivered stop may still change the host. */ export async function stopTransactionIncumbent( diff --git a/src/main/managed-server/activation/orcad-update-plan.ts b/src/main/managed-server/activation/orcad-update-plan.ts new file mode 100644 index 00000000000..722b7e41af6 --- /dev/null +++ b/src/main/managed-server/activation/orcad-update-plan.ts @@ -0,0 +1,139 @@ +import type { OrcadActivationRecord } from './orcad-activation-record' +import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' +import { + assessOrcadLiveDaemonCrossing, + describeDaemonProtocols +} from './orcad-daemon-protocol-crossing' + +import type { OrcadDaemonProtocolFacts } from './orcad-daemon-protocol-crossing' + +type OrcadUpdateDecision = + | { action: 'noop'; reason: string } + | { + action: 'proceed' + preservesLiveDaemon: boolean + notes: string[] + } + | { action: 'defer'; code: OrcadUpdateDeferCode; reason: string } + +/** `live-terminals` passes only a counted live-terminal deferral, never an uncounted census. */ +export type OrcadUpdateForce = boolean | 'live-terminals' + +export type OrcadUpdateDeferCode = + | 'orcad_update_terminals_running' + | 'orcad_update_terminal_census_unavailable' + | 'orcad_update_strands_live_terminals' + | 'orcad_update_daemon_protocol_unverifiable' + | 'orcad_update_ends_in_process_terminals' + +/** Defer live-session mixed-build pairs unless the operator chooses force; force cannot authorize an unsupported daemon protocol. */ +export function planOrcadUpdate(input: { + record: OrcadActivationRecord + candidateVersion: string + census: OrcadTerminalCensus + candidateDaemonProtocol: OrcadDaemonProtocolFacts + /** Daemon generations the candidate found alive on the host; consulted only when the census cannot name them. */ + hostDaemonProtocols?: readonly number[] + force?: OrcadUpdateForce +}): OrcadUpdateDecision { + if (input.record.active === input.candidateVersion) { + return { + action: 'noop', + reason: `${input.candidateVersion} is already the active version; nothing to restart.` + } + } + const inProcess = input.census.inProcessSessions ?? 0 + // In-process terminals cannot survive restart; force cannot override this even if daemon census is empty. + if (inProcess > 0) { + return { + action: 'defer', + code: 'orcad_update_ends_in_process_terminals', + reason: + `${inProcess} terminal${inProcess === 1 ? ' runs' : 's run'} inside the orcad process ` + + 'itself because its terminal daemon is degraded. Any restart ends ' + + `${inProcess === 1 ? 'it' : 'them'}, and forcing the update cannot keep ` + + `${inProcess === 1 ? 'it' : 'them'} alive. Close ${inProcess === 1 ? 'it' : 'them'}, ` + + 'then update.' + } + } + const crossing = assessOrcadLiveDaemonCrossing( + input.census, + input.candidateDaemonProtocol, + input.hostDaemonProtocols + ) + // Force can accept mixed builds, never unreachable terminals. + if (crossing.state === 'strands-live-terminals') { + return { + action: 'defer', + code: 'orcad_update_strands_live_terminals', + reason: + `A terminal daemon on this host speaks ${describeDaemonProtocols(crossing.unattachable)}, ` + + `which orcad ${input.candidateVersion} cannot attach to. Restarting now would leave ` + + 'any terminals it runs unreachable. Update when no terminals are running.' + } + } + const { liveSessions } = input.census + if (input.force && crossing.state === 'unverifiable') { + return { + action: 'defer', + code: 'orcad_update_daemon_protocol_unverifiable', + reason: + 'The terminal daemon did not report its protocol, so this update cannot show that ' + + `orcad ${input.candidateVersion} will reach the terminals it is forced past. Retry ` + + 'when the daemon answers.' + } + } + if (liveSessions === null) { + if (input.force !== true) { + return { + action: 'defer', + code: 'orcad_update_terminal_census_unavailable', + reason: + 'The terminal daemon did not answer a session count, so this update cannot tell ' + + 'whether work is running on the host. Retry, or force the update knowing terminals ' + + 'may be mid-flight.' + } + } + return { + action: 'proceed', + // Unknown census must preserve possible live sessions; never assume the daemon replaceable. + preservesLiveDaemon: true, + notes: [ + 'Forced with an unverifiable session count. Planning as if terminals are live: the ' + + 'daemon will be preserved across the restart, and the outgoing version directory ' + + 'stays pinned against GC.' + ] + } + } + if (liveSessions > 0 && !input.force) { + return { + action: 'defer', + code: 'orcad_update_terminals_running', + reason: + `${liveSessions} terminal${liveSessions === 1 ? ' is' : 's are'} running on this host. ` + + 'The restart would not kill them — the daemon is preserved — but the host would run ' + + `orcad ${input.candidateVersion} against a daemon forked from ` + + `${input.record.active ?? 'the previous build'} until they all exit. Update when the ` + + 'host is idle, or force it.' + } + } + if (liveSessions > 0) { + return { + action: 'proceed', + preservesLiveDaemon: true, + notes: [ + `Forced with ${liveSessions} live terminal${liveSessions === 1 ? '' : 's'}. They survive ` + + 'the restart on the existing daemon; the outgoing version directory stays pinned ' + + 'against GC because that daemon was forked from it.' + ] + } + } + return { + action: 'proceed', + // At zero sessions daemon-init can safely replace the old daemon. + preservesLiveDaemon: false, + notes: [ + 'No terminals are running, so the daemon is replaced by one forked from the new bundle.' + ] + } +} diff --git a/src/main/ssh/orcad-snapshot-capture-command.ts b/src/main/managed-server/activation/testing/orcad-snapshot-capture-command.ts similarity index 100% rename from src/main/ssh/orcad-snapshot-capture-command.ts rename to src/main/managed-server/activation/testing/orcad-snapshot-capture-command.ts diff --git a/src/main/ssh/orcad-fence-lost-classification.test.ts b/src/main/managed-server/host-state/orcad-fence-lost-classification.test.ts similarity index 89% rename from src/main/ssh/orcad-fence-lost-classification.test.ts rename to src/main/managed-server/host-state/orcad-fence-lost-classification.test.ts index 36f3316b61e..cbc9eb562d8 100644 --- a/src/main/ssh/orcad-fence-lost-classification.test.ts +++ b/src/main/managed-server/host-state/orcad-fence-lost-classification.test.ts @@ -1,22 +1,19 @@ import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ClientChannel } from 'ssh2' -import { execOrcadStateMutation } from '../managed-server/host-state/orcad-state-mutation-exec' -import { - execOrcadRemote, - execOrcadRemoteOr -} from '../managed-server/install/orcad-remote-runtime-control' +import { execOrcadStateMutation } from './orcad-state-mutation-exec' +import { execOrcadRemote, execOrcadRemoteOr } from '../install/orcad-remote-runtime-control' import { ORCAD_FENCE_LOST_MARKER, OrcadFenceLostError, posixOrcadFenceGuard, runWithOrcadFence -} from '../managed-server/activation/orcad-activation-fence-scope' +} from '../activation/orcad-activation-fence-scope' -import { isUnconfirmedSshCommandTermination } from './remote-exec/remote-exec-command' +import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' -import { getRemoteHostPlatform } from './ssh-remote-platform' -import type { OrcadHostTransport } from './orcad-host-transport' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import type { OrcadHostTransport } from '../install/orcad-host-transport' /** Model an exec channel whose unreachable host never acknowledges close. */ class HostChannel extends EventEmitter { diff --git a/src/main/managed-server/host-state/orcad-machine-claim-command.ts b/src/main/managed-server/host-state/orcad-machine-claim-command.ts index ea8b6f40b87..93c4bb4c6bb 100644 --- a/src/main/managed-server/host-state/orcad-machine-claim-command.ts +++ b/src/main/managed-server/host-state/orcad-machine-claim-command.ts @@ -1,13 +1,13 @@ import { randomUUID } from 'node:crypto' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import { RELAY_REMOTE_DIR } from '../install/remote-install-root' import { ORCAD_MACHINE_CLAIM_FILENAME, ORCAD_MACHINE_CLAIM_SCHEMA_VERSION, parseOrcadMachineClaim } from './orcad-machine-home' import { dfAvailableKb } from './remote-filesystem-space' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' /** Claim arbiter under ~/.orca-remote when hard links cannot elect an owner. */ export const ORCAD_MACHINE_CLAIM_ARBITER_DIRNAME = 'orcad-machine.arbiter' diff --git a/src/main/managed-server/host-state/orcad-machine-home.test.ts b/src/main/managed-server/host-state/orcad-machine-home.test.ts index 529a4e6bdf8..ea5bc5c349a 100644 --- a/src/main/managed-server/host-state/orcad-machine-home.test.ts +++ b/src/main/managed-server/host-state/orcad-machine-home.test.ts @@ -4,8 +4,8 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' import type { OrcadMachineHomeProbe } from './orcad-machine-home' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import type { RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { OrcadHostTransport } from '../install/orcad-host-transport' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' // Local shell commands run with per-machine hostname and hardware identity shims. const shell = vi.hoisted((): { env: NodeJS.ProcessEnv | undefined } => ({ @@ -41,7 +41,7 @@ await import('../install/remote-install-model') await import('../install/orcad-remote-launch') await import('../install/orcad-remote-host-support') await import('../install/orcad-remote-runtime-control') -const { getRemoteHostPlatform } = await import('../../ssh/ssh-remote-platform') +const { getRemoteHostPlatform } = await import('../../ssh/remote-host/ssh-remote-platform') type Probe = OrcadMachineHomeProbe type Host = RemoteHostPlatform diff --git a/src/main/managed-server/host-state/orcad-machine-home.ts b/src/main/managed-server/host-state/orcad-machine-home.ts index 5967ccdc5a5..c5ae5c51011 100644 --- a/src/main/managed-server/host-state/orcad-machine-home.ts +++ b/src/main/managed-server/host-state/orcad-machine-home.ts @@ -1,6 +1,6 @@ // Shared-home hosts need per-machine state and runtime GC: a PID can prove ownership only on the machine that issued it (#29059). import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import { RELAY_REMOTE_DIR } from '../install/remote-install-root' import { machineKeyOf, namedMachineHome, @@ -14,7 +14,7 @@ import { normalizeRemoteHome, validateRemoteHome, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' export const ORCAD_MACHINE_CLAIM_FILENAME = 'orcad-machine.json' export const ORCAD_MACHINE_HOMES_DIRNAME = 'hosts' diff --git a/src/main/managed-server/host-state/orcad-machine-name-home.ts b/src/main/managed-server/host-state/orcad-machine-name-home.ts index 27145ff82d4..48529ac4f9c 100644 --- a/src/main/managed-server/host-state/orcad-machine-name-home.ts +++ b/src/main/managed-server/host-state/orcad-machine-name-home.ts @@ -1,7 +1,7 @@ // ORCA_MACHINE_NAME separates hosts that share a home and a cloned machine-id (#32918). import { createHash } from 'node:crypto' import { ORCA_MACHINE_NAME_ENV } from '../../../shared/orcad-managed-launch-env' -import type { RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import type { OrcadMachineHomeDecision } from './orcad-machine-home' const MACHINE_NAME_PREFIX = `${ORCA_MACHINE_NAME_ENV}=` diff --git a/src/main/ssh/orcad-snapshot-room.test.ts b/src/main/managed-server/host-state/orcad-snapshot-room.test.ts similarity index 66% rename from src/main/ssh/orcad-snapshot-room.test.ts rename to src/main/managed-server/host-state/orcad-snapshot-room.test.ts index 1c0c65caa48..15fa5bb8bd4 100644 --- a/src/main/ssh/orcad-snapshot-room.test.ts +++ b/src/main/managed-server/host-state/orcad-snapshot-room.test.ts @@ -1,50 +1,46 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as ExecCommandModule from './remote-exec/remote-exec-command' -import type * as RecordFile from '../managed-server/install/orcad-remote-record-file' -import type * as InstallLock from '../managed-server/install/remote-install-lock' -import type * as VersionedInstall from '../managed-server/install/remote-versioned-install' +import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' +import type * as RecordFile from '../install/orcad-remote-record-file' +import type * as InstallLock from '../install/remote-install-lock' +import type * as VersionedInstall from '../install/remote-versioned-install' -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand: vi.fn() })) -vi.mock('../../shared/shell/launch/shell-argument-quoting', () => ({ +vi.mock('../../../shared/shell/launch/shell-argument-quoting', () => ({ quotePosixShell: (s: string) => `'${s}'` })) -vi.mock('../managed-server/install/remote-install-lock', async (importOriginal) => ({ +vi.mock('../install/remote-install-lock', async (importOriginal) => ({ ...(await importOriginal()), acquireInstallLock: vi.fn() })) -vi.mock('../managed-server/install/orcad-remote-record-file', async (importOriginal) => ({ +vi.mock('../install/orcad-remote-record-file', async (importOriginal) => ({ ...(await importOriginal()), writeAtomicOrcadRemoteRecord: vi.fn() })) -vi.mock('../managed-server/install/remote-versioned-install', async (importOriginal) => ({ +vi.mock('../install/remote-versioned-install', async (importOriginal) => ({ ...(await importOriginal()), readLocalFullVersion: () => '0.2.0+bb01' })) -vi.mock('../managed-server/install/orcad-remote-install', () => ({ installOrcadBundle: vi.fn() })) -vi.mock('../managed-server/install/orcad-remote-preflight', () => ({ +vi.mock('../install/orcad-remote-install', () => ({ installOrcadBundle: vi.fn() })) +vi.mock('../install/orcad-remote-preflight', () => ({ preflightInstalledOrcad: vi.fn(async () => ({})) })) -vi.mock('./orcad-local-build-hash', () => ({ +vi.mock('../install/orcad-local-build-hash', () => ({ computeLocalOrcadBuildHash: () => 'abc123def4567890' })) -import { execCommand } from './remote-exec/remote-exec-command' -import { acquireInstallLock } from '../managed-server/install/remote-install-lock' -import { writeAtomicOrcadRemoteRecord } from '../managed-server/install/orcad-remote-record-file' -import { deployOrcad } from './orcad-remote-deploy' -import { getRemoteHostPlatform } from './ssh-remote-platform' +import { execCommand } from '../../ssh/remote-exec/remote-exec-command' +import { acquireInstallLock } from '../install/remote-install-lock' +import { writeAtomicOrcadRemoteRecord } from '../install/orcad-remote-record-file' +import { deployOrcad } from '../install/orcad-remote-deploy' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { ORCAD_SNAPSHOT_SPACE_INSUFFICIENT_CODE } from './orcad-snapshot-room' -import { OrcadFenceLostError } from '../managed-server/activation/orcad-activation-fence-scope' +import { OrcadFenceLostError } from '../activation/orcad-activation-fence-scope' -import { - FakeOrcadHost, - NEW, - OLD -} from '../managed-server/activation/orcad-activation-host-test-harness' +import { FakeOrcadHost, NEW, OLD } from '../activation/orcad-activation-host-test-harness' let host = FakeOrcadHost.deployedOld() @@ -83,7 +79,7 @@ beforeEach(() => { vi.mocked(acquireInstallLock).mockImplementation(async (_conn, dir, _host, options) => { if (!host.acquireFence(options)) { const { RemoteInstallLockBusyError } = await vi.importActual( - '../managed-server/install/remote-install-lock' + '../install/remote-install-lock' ) throw new RemoteInstallLockBusyError(dir, 0) } @@ -113,20 +109,6 @@ describe('an update on a host without room for its snapshot (#30491)', () => { expect(host.fence).toBe(false) }) - it('measures room before the last terminal recount, so the scan cannot outdate it', async () => { - answerRoom(400_000, 0, 10_000_000) - const probedBeforeRecount: boolean[] = [] - const recountCensus = vi.fn(async () => { - probedBeforeRecount.push( - vi.mocked(execCommand).mock.calls.some(([, command]) => command.includes('SNAPSHOT_SPACE')) - ) - return { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 3 } - }) - - expect(await deploy({ recountCensus })).toMatchObject({ outcome: 'installed-and-activated' }) - expect(probedBeforeRecount).toEqual([true]) - }) - it('goes ahead when the room probe loses its channel, leaving the capture to decide', async () => { vi.mocked(execCommand).mockImplementation(async (_conn, command) => { if (command.includes('SNAPSHOT_SPACE')) { diff --git a/src/main/ssh/orcad-snapshot-room.ts b/src/main/managed-server/host-state/orcad-snapshot-room.ts similarity index 78% rename from src/main/ssh/orcad-snapshot-room.ts rename to src/main/managed-server/host-state/orcad-snapshot-room.ts index 1ea89843a51..fc5c0c51933 100644 --- a/src/main/ssh/orcad-snapshot-room.ts +++ b/src/main/managed-server/host-state/orcad-snapshot-room.ts @@ -1,19 +1,19 @@ /** Check snapshot room before stopping a serving incumbent (#30491). */ -import { orcadRemoteBaseDir } from '../managed-server/install/orcad-remote-windows-node' -import { execOrcadRemoteOr } from '../managed-server/install/orcad-remote-runtime-control' +import { orcadRemoteBaseDir } from '../install/orcad-remote-windows-node' +import { execOrcadRemoteOr } from '../install/orcad-remote-runtime-control' import { ORCAD_STATE_SNAPSHOT_DIR, type OrcadActivationRecord -} from '../managed-server/activation/orcad-activation-record' +} from '../activation/orcad-activation-record' import { orcadSnapshotShortfallKb, orcadSnapshotShortfallMessage, orcadSnapshotSpaceCommand, parseOrcadSnapshotSpace -} from '../managed-server/host-state/orcad-state-snapshot-space' -import { joinRemotePath } from './ssh-remote-platform' -import { isUnconfirmedSshCommandTermination } from './remote-exec/remote-exec-command' -import type { OrcadSlotOptions } from './orcad-recovery-slot' +} from './orcad-state-snapshot-space' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' +import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' +import type { OrcadSlotOptions } from '../activation/orcad-recovery-slot' export const ORCAD_SNAPSHOT_SPACE_INSUFFICIENT_CODE = 'orcad_snapshot_space_insufficient' diff --git a/src/main/managed-server/host-state/orcad-state-newest-mtime.ts b/src/main/managed-server/host-state/orcad-state-newest-mtime.ts index 352169e6d7e..254141b6541 100644 --- a/src/main/managed-server/host-state/orcad-state-newest-mtime.ts +++ b/src/main/managed-server/host-state/orcad-state-newest-mtime.ts @@ -1,5 +1,8 @@ import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' import { orcadWindowsHostOpCommand } from '../install/orcad-remote-windows-node' import { ORCAD_SNAPSHOT_MEMBERS } from './orcad-state-snapshot-members' diff --git a/src/main/managed-server/host-state/orcad-state-snapshot-shell.test.ts b/src/main/managed-server/host-state/orcad-state-snapshot-shell.test.ts index a919f91e835..229a5a0fb7e 100644 --- a/src/main/managed-server/host-state/orcad-state-snapshot-shell.test.ts +++ b/src/main/managed-server/host-state/orcad-state-snapshot-shell.test.ts @@ -19,7 +19,7 @@ import { restoreOrcadStateSnapshotCommand } from './orcad-state-snapshot' import { posixProcessGroupCommand } from './orcad-state-mutation-owner-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const posix = getRemoteHostPlatform('linux-x64') diff --git a/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts b/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts index 0c70421bb0b..9f84dc1df89 100644 --- a/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts +++ b/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts @@ -13,7 +13,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' import { captureOrcadStateSnapshotCommand, parseOrcadSnapshotCapture } from './orcad-state-snapshot' import { orcadSnapshotFailureReason } from './orcad-state-snapshot-space' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const posix = getRemoteHostPlatform('linux-x64') const SHELL = process.env.ORCA_TEST_POSIX_SHELL ?? '/bin/sh' diff --git a/src/main/managed-server/host-state/orcad-state-snapshot-space.ts b/src/main/managed-server/host-state/orcad-state-snapshot-space.ts index 9de5c62f850..05d2881beb5 100644 --- a/src/main/managed-server/host-state/orcad-state-snapshot-space.ts +++ b/src/main/managed-server/host-state/orcad-state-snapshot-space.ts @@ -1,6 +1,9 @@ // Prune unreferenced captures and check disk space before stopping the incumbent, preserving service when no snapshot fits (#30491). import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' import { ORCAD_SNAPSHOT_FAILURE, ORCAD_SNAPSHOT_MEMBERS } from './orcad-state-snapshot-members' import { dfAvailableKb, formatKb } from './remote-filesystem-space' diff --git a/src/main/managed-server/host-state/orcad-state-snapshot.test.ts b/src/main/managed-server/host-state/orcad-state-snapshot.test.ts index 7217666d207..c82a2211a37 100644 --- a/src/main/managed-server/host-state/orcad-state-snapshot.test.ts +++ b/src/main/managed-server/host-state/orcad-state-snapshot.test.ts @@ -7,7 +7,7 @@ import { restoreOrcadStateSnapshotCommand } from './orcad-state-snapshot' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const posix = getRemoteHostPlatform('linux-x64') diff --git a/src/main/managed-server/host-state/orcad-state-snapshot.ts b/src/main/managed-server/host-state/orcad-state-snapshot.ts index f1abb1753b7..aed120fd5af 100644 --- a/src/main/managed-server/host-state/orcad-state-snapshot.ts +++ b/src/main/managed-server/host-state/orcad-state-snapshot.ts @@ -12,7 +12,7 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import type { OrcadWindowsHostStateOp } from './orcad-windows-host-state-ops' import { pruneOrcadSnapshotsScript } from './orcad-state-snapshot-space' import { diff --git a/src/main/managed-server/host-state/orcad-windows-host-lane.test.ts b/src/main/managed-server/host-state/orcad-windows-host-lane.test.ts index 43a809db29d..979801fef9e 100644 --- a/src/main/managed-server/host-state/orcad-windows-host-lane.test.ts +++ b/src/main/managed-server/host-state/orcad-windows-host-lane.test.ts @@ -11,21 +11,21 @@ import { installHostileHostAppEnvironment } from '../../ssh/hostile-host-test-support/ssh-hostile-host-test-harness' import { resolveOrcadRemoteContext } from '../install/orcad-remote-context' -import { proveWindowsStdioBridge } from '../../ssh/orcad-windows-stdio-bridge-test-cell' -import { deployOrcad } from '../../ssh/orcad-remote-deploy' +import { proveWindowsStdioBridge } from '../lifecycle/testing/orcad-windows-stdio-bridge-test-cell' +import { deployOrcad } from '../install/orcad-remote-deploy' import { orcadLivenessProbeCommand, parseOrcadLiveness } from '../install/orcad-remote-launch' -import { orcadSlotDir, type OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import { orcadSlotDir, type OrcadSlotOptions } from '../activation/orcad-recovery-slot' import { decommissionRemoteOrcad } from '../install/orcad-remote-decommission' import { readOrcadActivationRecord } from '../activation/orcad-activation-record-store' import { gcOldOrcadVersions } from '../install/orcad-remote-gc' import { execOrcadRemote } from '../install/orcad-remote-runtime-control' import { orcadWindowsNodeCommandLine } from '../install/orcad-remote-windows-node' -import { joinRemotePath } from '../../ssh/ssh-remote-platform' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { isWindowsOrcadCellId, readWindowsHostCellDescriptor, windowsHostSshTarget -} from '../../ssh/ssh-windows-host-cells' +} from '../../ssh/hostile-host-test-support/ssh-windows-host-cells' const RUN = process.env.ORCA_RUN_SSH_WINDOWS_HOST === '1' const CELL_TIMEOUT_MS = 20 * 60_000 diff --git a/src/main/managed-server/host-state/orcad-windows-host-preparation.ts b/src/main/managed-server/host-state/orcad-windows-host-preparation.ts index 8d79ded1ef9..fc674a9bc3c 100644 --- a/src/main/managed-server/host-state/orcad-windows-host-preparation.ts +++ b/src/main/managed-server/host-state/orcad-windows-host-preparation.ts @@ -8,8 +8,8 @@ import { orcadRemoteBaseDir } from '../install/orcad-remote-windows-node' import { materializeNodeRuntimeArchive } from '../../node-runtime/pinned-runtime-materializer' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { OrcadHostTransport } from '../install/orcad-host-transport' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' export async function prepareWindowsOrcadHost(options: { conn: OrcadHostTransport diff --git a/src/main/ssh/orcad-deployment-target.ts b/src/main/managed-server/install/orcad-deployment-target.ts similarity index 75% rename from src/main/ssh/orcad-deployment-target.ts rename to src/main/managed-server/install/orcad-deployment-target.ts index f11318e3df3..3252fcf3690 100644 --- a/src/main/ssh/orcad-deployment-target.ts +++ b/src/main/managed-server/install/orcad-deployment-target.ts @@ -4,12 +4,12 @@ import { isNodeRuntimeTarget, type NodeRuntimeTarget, type ServerTarget -} from '../../shared/node-runtime-pin' -import { ORCAD_SERVER_TARGET_FILENAME } from '../../shared/orcad-artifacts' -import type { RemoteInstallTransport } from '../managed-server/install/remote-install-transport' -import { probeLinuxLibc, type GlibcVersion } from '../node-runtime/linux-libc-probe' -import { execCommand } from './remote-exec/remote-exec-command' -import type { RemoteHostPlatform } from './ssh-remote-platform' +} from '../../../shared/node-runtime-pin' +import { ORCAD_SERVER_TARGET_FILENAME } from '../../../shared/orcad-artifacts' +import type { RemoteInstallTransport } from './remote-install-transport' +import { probeLinuxLibc, type GlibcVersion } from '../../node-runtime/linux-libc-probe' +import { execCommand } from '../../ssh/remote-exec/remote-exec-command' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' type OrcadDeploymentTargetFacts = { target: ServerTarget diff --git a/src/main/ssh/orcad-host-transport.ts b/src/main/managed-server/install/orcad-host-transport.ts similarity index 76% rename from src/main/ssh/orcad-host-transport.ts rename to src/main/managed-server/install/orcad-host-transport.ts index 1c044a0c173..1ad96fa9ffd 100644 --- a/src/main/ssh/orcad-host-transport.ts +++ b/src/main/managed-server/install/orcad-host-transport.ts @@ -1,7 +1,7 @@ -import type { SshTarget } from '../../shared/ssh-types' -import type { WslOrcadHostTarget } from '../wsl/orcad/wsl-orcad-host-target' -import type { RemoteInstallTransport } from '../managed-server/install/remote-install-transport' -import type { OrcadLaunchDetach } from '../managed-server/install/orcad-remote-launch' +import type { SshTarget } from '../../../shared/ssh-types' +import type { WslOrcadHostTarget } from '../../wsl/orcad/wsl-orcad-host-target' +import type { RemoteInstallTransport } from './remote-install-transport' +import type { OrcadLaunchDetach } from './orcad-remote-launch' /** Only id/label have the same meaning across host kinds. */ export type OrcadHostTarget = SshTarget | WslOrcadHostTarget diff --git a/src/main/ssh/orcad-launch-ssh-session.test.ts b/src/main/managed-server/install/orcad-launch-ssh-session.test.ts similarity index 97% rename from src/main/ssh/orcad-launch-ssh-session.test.ts rename to src/main/managed-server/install/orcad-launch-ssh-session.test.ts index 141234d27ff..227a61144ea 100644 --- a/src/main/ssh/orcad-launch-ssh-session.test.ts +++ b/src/main/managed-server/install/orcad-launch-ssh-session.test.ts @@ -12,9 +12,9 @@ import { parseOrcadLaunchSshSession, writeOrcadLaunchSshSessionCommand } from './orcad-launch-ssh-session' -import { orcadLaunchCommand } from '../managed-server/install/orcad-remote-launch' -import { ORCAD_PID_FILENAME } from '../managed-server/install/orcad-remote-host-support' -import { getRemoteHostPlatform } from './ssh-remote-platform' +import { orcadLaunchCommand } from './orcad-remote-launch' +import { ORCAD_PID_FILENAME } from './orcad-remote-host-support' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const mac = getRemoteHostPlatform('darwin-arm64') diff --git a/src/main/ssh/orcad-launch-ssh-session.ts b/src/main/managed-server/install/orcad-launch-ssh-session.ts similarity index 95% rename from src/main/ssh/orcad-launch-ssh-session.ts rename to src/main/managed-server/install/orcad-launch-ssh-session.ts index 29d6fb5e0bb..9cca9585892 100644 --- a/src/main/ssh/orcad-launch-ssh-session.ts +++ b/src/main/managed-server/install/orcad-launch-ssh-session.ts @@ -1,7 +1,7 @@ /** macOS pins Local Network attribution at spawn: SSH-launched terminals can lose LAN access after sshd-session exits (#25934; Apple TN3179). Record the nearest session plus start time and matching slot PID; preserve earlier attribution while a live terminal daemon survives orcad restarts. */ -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { joinRemotePath, type RemoteHostPlatform } from './ssh-remote-platform' -import { ORCAD_PID_FILENAME } from '../managed-server/install/orcad-remote-host-support' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { ORCAD_PID_FILENAME } from './orcad-remote-host-support' export const ORCAD_LAUNCH_SSH_SESSION_FILENAME = '.orcad-launch-ssh-session' diff --git a/src/main/ssh/orcad-local-build-hash.ts b/src/main/managed-server/install/orcad-local-build-hash.ts similarity index 55% rename from src/main/ssh/orcad-local-build-hash.ts rename to src/main/managed-server/install/orcad-local-build-hash.ts index 8a48b013ede..d7a319a1973 100644 --- a/src/main/ssh/orcad-local-build-hash.ts +++ b/src/main/managed-server/install/orcad-local-build-hash.ts @@ -1,6 +1,6 @@ import { join } from 'node:path' -import { hashOrcadLauncher } from '../../shared/orcad-build-identity' -import { ORCAD_LAUNCHER_FILENAME } from '../../shared/orcad-artifacts' +import { hashOrcadLauncher } from '../../../shared/orcad-build-identity' +import { ORCAD_LAUNCHER_FILENAME } from '../../../shared/orcad-artifacts' export function computeLocalOrcadBuildHash(localOrcadDir: string): string { return hashOrcadLauncher(join(localOrcadDir, ORCAD_LAUNCHER_FILENAME)) diff --git a/src/main/managed-server/install/orcad-node-runtime-globs.ts b/src/main/managed-server/install/orcad-node-runtime-globs.ts index 2ef95bca5b3..7ede2a3ca89 100644 --- a/src/main/managed-server/install/orcad-node-runtime-globs.ts +++ b/src/main/managed-server/install/orcad-node-runtime-globs.ts @@ -4,7 +4,7 @@ import { ORCAD_RUNTIMES_DIRNAME } from '../../../shared/orcad-artifacts' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import { RELAY_REMOTE_DIR } from './remote-install-root' import { ORCAD_MACHINE_HOMES_DIRNAME } from '../host-state/orcad-machine-home' /** POSIX shell glob words for orcad's pinned Node runtimes; machine homes may hold other architectures, so callers must self-test each match. */ diff --git a/src/main/ssh/orcad-node-runtime-install-options.ts b/src/main/managed-server/install/orcad-node-runtime-install-options.ts similarity index 88% rename from src/main/ssh/orcad-node-runtime-install-options.ts rename to src/main/managed-server/install/orcad-node-runtime-install-options.ts index aee92cde526..bb98edcd5bd 100644 --- a/src/main/ssh/orcad-node-runtime-install-options.ts +++ b/src/main/managed-server/install/orcad-node-runtime-install-options.ts @@ -1,8 +1,8 @@ -import type { NodeRuntimeTarget } from '../../shared/node-runtime-pin' +import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { materializeNodeRuntimeArchive, nodeRuntimeArchiveCachePath -} from '../node-runtime/pinned-runtime-materializer' +} from '../../node-runtime/pinned-runtime-materializer' /** WSL only: bounded Node runtime downloads. SSH passes none and keeps the default timing. */ export type NodeRuntimeDownloadBudget = { diff --git a/src/main/managed-server/install/orcad-remote-build-hash.ts b/src/main/managed-server/install/orcad-remote-build-hash.ts index 69298daf332..26259666d5a 100644 --- a/src/main/managed-server/install/orcad-remote-build-hash.ts +++ b/src/main/managed-server/install/orcad-remote-build-hash.ts @@ -7,7 +7,7 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' export async function readRemoteOrcadBuildHash( target: OrcadRemoteExecTarget, diff --git a/src/main/managed-server/install/orcad-remote-context.ts b/src/main/managed-server/install/orcad-remote-context.ts index 9f1b9e45b6c..931d935d5cb 100644 --- a/src/main/managed-server/install/orcad-remote-context.ts +++ b/src/main/managed-server/install/orcad-remote-context.ts @@ -10,7 +10,7 @@ import { isWslOrcadHostTarget, type OrcadHostTarget, type OrcadHostTransport -} from '../../ssh/orcad-host-transport' +} from './orcad-host-transport' import { decideOrcadMachineHome, orcadMachineDataRoot, @@ -24,7 +24,7 @@ import { readOrcadMachineClaimAnswer } from '../host-state/orcad-machine-claim-command' import { execOrcadRemote, type OrcadRemoteExecTarget } from './orcad-remote-runtime-control' -import { readRemoteHomeCommand } from '../../ssh/ssh-remote-commands' +import { readRemoteHomeCommand } from '../../ssh/remote-exec/ssh-remote-commands' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { isWindowsRemoteHost, @@ -32,10 +32,10 @@ import { normalizeRemoteHome, validateRemoteHome, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' -import { detectRemoteHostPlatform } from '../../ssh/ssh-remote-platform-detection' +} from '../../ssh/remote-host/ssh-remote-platform' +import { detectRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform-detection' import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' -import { rememberSshHostPlatform } from '../../ssh/ssh-host-platform-memo' +import { rememberSshHostPlatform } from '../../ssh/remote-host/ssh-host-platform-memo' /** Default SSH generic retains compatibility with lifecycle consumers requiring SSH-only fields. */ export type OrcadRemoteContext = { diff --git a/src/main/managed-server/install/orcad-remote-decommission.test.ts b/src/main/managed-server/install/orcad-remote-decommission.test.ts index 5749006261a..754a011be01 100644 --- a/src/main/managed-server/install/orcad-remote-decommission.test.ts +++ b/src/main/managed-server/install/orcad-remote-decommission.test.ts @@ -25,7 +25,7 @@ import { writeAtomicOrcadRemoteRecord } from './orcad-remote-record-file' import { decommissionRemoteOrcad } from './orcad-remote-decommission' import { recoverInterruptedOrcadActivation } from '../activation/orcad-activation-recovery' import { parseOrcadActivationRecord } from '../activation/orcad-activation-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' import { FakeOrcadHost, diff --git a/src/main/managed-server/install/orcad-remote-decommission.ts b/src/main/managed-server/install/orcad-remote-decommission.ts index b34821da065..74bb872f7df 100644 --- a/src/main/managed-server/install/orcad-remote-decommission.ts +++ b/src/main/managed-server/install/orcad-remote-decommission.ts @@ -17,7 +17,7 @@ import { } from '../lifecycle/orcad-decommission-transaction' import { readRemoteOrcadManagedStopTarget } from '../lifecycle/orcad-managed-remote-stop' import { settleOrcadDecommissionStop } from '../lifecycle/orcad-decommission-stop' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import type { OrcadSlotOptions } from '../activation/orcad-recovery-slot' import type { OrcadDecommissionResult } from '../../../shared/orcad-decommission' import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' diff --git a/src/main/ssh/orcad-remote-deploy.test.ts b/src/main/managed-server/install/orcad-remote-deploy.test.ts similarity index 53% rename from src/main/ssh/orcad-remote-deploy.test.ts rename to src/main/managed-server/install/orcad-remote-deploy.test.ts index f4b77cc1a30..f1ef744bc00 100644 --- a/src/main/ssh/orcad-remote-deploy.test.ts +++ b/src/main/managed-server/install/orcad-remote-deploy.test.ts @@ -1,73 +1,63 @@ -import type * as ExecCommandModule from './remote-exec/remote-exec-command' +import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs' -import type * as RecordFile from '../managed-server/install/orcad-remote-record-file' +import type * as RecordFile from './orcad-remote-record-file' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand: vi.fn() })) -vi.mock('../../shared/shell/launch/shell-argument-quoting', () => ({ +vi.mock('../../../shared/shell/launch/shell-argument-quoting', () => ({ quotePosixShell: (s: string) => `'${s}'` })) -vi.mock('../managed-server/install/remote-install-lock', () => ({ +vi.mock('./remote-install-lock', () => ({ acquireInstallLock: vi.fn().mockResolvedValue(undefined), isRelayInstallLockStale: vi.fn().mockResolvedValue(false), RemoteInstallLockBusyError: class extends Error {}, RELAY_INSTALL_LOCK_NAME: '.install-lock' })) -vi.mock('../managed-server/install/remote-install-transfers', () => ({ +vi.mock('./remote-install-transfers', () => ({ uploadRemoteInstallDirectory: vi.fn().mockResolvedValue(undefined), writeRemoteInstallFile: vi.fn().mockResolvedValue(undefined) })) -vi.mock('../managed-server/install/orcad-remote-record-file', async (importOriginal) => ({ +vi.mock('./orcad-remote-record-file', async (importOriginal) => ({ ...(await importOriginal()), writeAtomicOrcadRemoteRecord: vi.fn().mockResolvedValue(undefined) })) -vi.mock('../managed-server/install/orcad-remote-node-runtime', () => ({ +vi.mock('./orcad-remote-node-runtime', () => ({ ensureRemoteOrcadNodeRuntime: vi.fn().mockResolvedValue(undefined) })) vi.mock('./orcad-local-build-hash', () => ({ computeLocalOrcadBuildHash: () => 'abc123def4567890' })) -import { execCommand } from './remote-exec/remote-exec-command' -import { - acquireInstallLock, - isRelayInstallLockStale -} from '../managed-server/install/remote-install-lock' -import { uploadRemoteInstallDirectory } from '../managed-server/install/remote-install-transfers' -import { writeAtomicOrcadRemoteRecord } from '../managed-server/install/orcad-remote-record-file' +import { execCommand } from '../../ssh/remote-exec/remote-exec-command' +import { isRelayInstallLockStale } from './remote-install-lock' +import { uploadRemoteInstallDirectory } from './remote-install-transfers' +import { writeAtomicOrcadRemoteRecord } from './orcad-remote-record-file' import { deployOrcad, type OrcadDeployOptions } from './orcad-remote-deploy' -import { installOrcadBundle } from '../managed-server/install/orcad-remote-install' -import { ensureRemoteOrcadNodeRuntime } from '../managed-server/install/orcad-remote-node-runtime' -import { - abandonInstall, - finalizeInstall, - isRemoteInstallComplete -} from '../managed-server/install/remote-versioned-install' +import { installOrcadBundle } from './orcad-remote-install' +import { finalizeInstall } from './remote-versioned-install' import { emptyOrcadActivationRecord, - withActivatedVersion, - withDeactivatedVersionCommitted, - type OrcadActivationRecord -} from '../managed-server/activation/orcad-activation-record' -import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from './orcad-installed-activation' -import { getRemoteHostPlatform } from './ssh-remote-platform' -import { isReadinessRead } from '../managed-server/activation/orcad-activation-host-test-harness' -import { isSnapshotCaptureCommand } from './orcad-snapshot-capture-command' -import { NODE_RUNTIME_PIN } from '../../shared/node-runtime-pin' -import { serializeOrcadActivationTransaction } from '../managed-server/activation/orcad-activation-transaction' -import { createOrcadActivationTransaction } from '../managed-server/activation/orcad-activation-transaction-transitions' + withActivatedVersion +} from '../activation/orcad-activation-record' + +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { isReadinessRead } from '../activation/orcad-activation-host-test-harness' +import { isSnapshotCaptureCommand } from '../activation/testing/orcad-snapshot-capture-command' +import { NODE_RUNTIME_PIN } from '../../../shared/node-runtime-pin' +import { serializeOrcadActivationTransaction } from '../activation/orcad-activation-transaction' +import { createOrcadActivationTransaction } from '../activation/orcad-activation-transaction-transitions' const mockExec = vi.mocked(execCommand) const NEW_VERSION = '0.2.0+bb0100000000' const OLD_VERSION = '0.1.0+aa01' -vi.mock('../managed-server/install/remote-versioned-install', async (importOriginal) => ({ +vi.mock('./remote-versioned-install', async (importOriginal) => ({ ...(await importOriginal>()), readLocalFullVersion: () => '0.2.0+bb0100000000', isRemoteInstallComplete: vi.fn().mockResolvedValue(false), @@ -123,7 +113,6 @@ type HostScript = { snapshotResult?: string comparisonResult?: string candidateStopResult?: string - readinessAtMs?: number orcadLog?: string } @@ -148,9 +137,6 @@ function scriptHost(script: HostScript): void { return 'CLEAR' } if (text.includes('.orcad-readiness') && isReadinessRead(text)) { - if (script.readinessAtMs !== undefined && Date.now() < script.readinessAtMs) { - return '' - } const version = Object.keys(script.readiness).find((v) => text.includes(v)) return version ? script.readiness[version] : '' } @@ -220,86 +206,6 @@ const ACTIVE_OLD = JSON.stringify( withActivatedVersion(emptyOrcadActivationRecord(), OLD_VERSION, null, new Date(0)) ) -describe('orcad install lock ownership', () => { - const remoteDir = `/home/u/.orca-remote/orcad-${NEW_VERSION}` - const install = (signal?: AbortSignal) => - installOrcadBundle( - { - ...options({ signal }), - localOrcadDir: '/local/out/orcad', - target: 'linux-x64-glibc', - nodeRuntimeArchive: async () => '/cache/node.tar.gz' - }, - NEW_VERSION, - remoteDir - ) - - beforeEach(() => { - vi.clearAllMocks() - vi.mocked(isRemoteInstallComplete).mockReset().mockResolvedValue(false) - }) - - it('leaves another install lock alone when the initial probe is complete', async () => { - vi.mocked(isRemoteInstallComplete).mockResolvedValueOnce(true) - await install() - expect(acquireInstallLock).not.toHaveBeenCalled() - expect(abandonInstall).not.toHaveBeenCalled() - expect(uploadRemoteInstallDirectory).not.toHaveBeenCalled() - }) - - it('releases its lock when another installer completed while acquisition waited', async () => { - vi.mocked(isRemoteInstallComplete).mockResolvedValueOnce(false).mockResolvedValueOnce(true) - await install() - expect(acquireInstallLock).toHaveBeenCalledOnce() - expect(abandonInstall).toHaveBeenCalledOnce() - expect(abandonInstall).toHaveBeenCalledWith(expect.anything(), remoteDir, options().host) - expect(uploadRemoteInstallDirectory).not.toHaveBeenCalled() - expect(finalizeInstall).not.toHaveBeenCalled() - }) - - it('publishes a complete install before releasing its lock once', async () => { - await install() - expect(uploadRemoteInstallDirectory).toHaveBeenCalledOnce() - expect(finalizeInstall).toHaveBeenCalledWith(expect.anything(), remoteDir, options().host, { - signal: undefined, - releaseLock: false - }) - expect(abandonInstall).toHaveBeenCalledOnce() - expect(vi.mocked(finalizeInstall).mock.invocationCallOrder[0]).toBeLessThan( - vi.mocked(abandonInstall).mock.invocationCallOrder[0] - ) - }) - - it('releases a failed upload without publishing it or replacing its error', async () => { - const error = new Error('upload interrupted') - vi.mocked(uploadRemoteInstallDirectory).mockRejectedValueOnce(error) - await expect(install()).rejects.toBe(error) - expect(abandonInstall).toHaveBeenCalledOnce() - expect(finalizeInstall).not.toHaveBeenCalled() - }) - - it('releases its lock without reusing an aborted operation signal', async () => { - const controller = new AbortController() - const error = new Error('deployment canceled') - vi.mocked(uploadRemoteInstallDirectory).mockImplementationOnce(async () => { - controller.abort(error) - controller.signal.throwIfAborted() - }) - await expect(install(controller.signal)).rejects.toBe(error) - expect(abandonInstall).toHaveBeenCalledOnce() - expect(abandonInstall).toHaveBeenCalledWith(expect.anything(), remoteDir, options().host) - expect(finalizeInstall).not.toHaveBeenCalled() - }) - - it('does not release a lock when acquisition failed', async () => { - const error = new Error('lock held by another client') - vi.mocked(acquireInstallLock).mockRejectedValueOnce(error) - await expect(install()).rejects.toBe(error) - expect(abandonInstall).not.toHaveBeenCalled() - expect(uploadRemoteInstallDirectory).not.toHaveBeenCalled() - }) -}) - describe('deployOrcad', () => { it.each(['', '{"type":"orca_profile_state_ready","revision":0}'])( 'leaves the incumbent and shared state alone when preflight returns %j', @@ -329,83 +235,6 @@ describe('deployOrcad', () => { vi.clearAllMocks() }) - it.each([ - ['linux-arm64', 'linux-arm64-glibc'], - ['darwin-x64', 'darwin-x64'] - ] as const)( - 'marks the %s search binary executable before completing the install', - async (platform, target) => { - scriptHost({ activationRecord: '', readiness: {}, log: [] }) - await deployOrcad( - options({ - host: getRemoteHostPlatform(platform), - target, - census: { liveSessions: 1, startedSinceActivation: 0, daemonProtocolVersion: 3 } - }) - ) - const chmod = mockExec.mock.calls.findIndex(([, command]) => - String(command).startsWith('chmod 755 ') - ) - expect(chmod).toBeGreaterThanOrEqual(0) - expect(mockExec.mock.calls[chmod]?.[1]).toContain(`/ripgrep/${platform}/rg'`) - expect(mockExec.mock.calls[chmod]?.[1]).not.toContain('bun-runtime') - expect(String(mockExec.mock.calls[chmod]?.[1]).includes('/spawn-helper')).toBe( - platform === 'darwin-x64' - ) - expect(ensureRemoteOrcadNodeRuntime).toHaveBeenCalledWith( - expect.objectContaining({ target, slotDir: `/home/u/.orca-remote/orcad-${NEW_VERSION}` }) - ) - expect(vi.mocked(uploadRemoteInstallDirectory).mock.invocationCallOrder[0]).toBeLessThan( - mockExec.mock.invocationCallOrder[chmod] - ) - expect(mockExec.mock.invocationCallOrder[chmod]).toBeLessThan( - vi.mocked(finalizeInstall).mock.invocationCallOrder[0] - ) - } - ) - - it('skips only the pre-upload record and fence reads a WSL connect already made', async () => { - const reads = async (preRead?: OrcadDeployOptions['preRead']) => { - vi.clearAllMocks() - scriptHost({ activationRecord: '', readiness: { [NEW_VERSION]: readyLine({}) }, log: [] }) - await deployOrcad(options(preRead ? { preRead } : {})) - const commands = mockExec.mock.calls.map(([, command]) => String(command)) - const count = (needle: string) => commands.filter((c) => c.includes(needle)).length - return { - record: count("[ ! -e '/home/u/.orca-remote/orcad-active.json'"), - fence: count('LOCKED') - } - } - const plain = await reads() - const record = emptyOrcadActivationRecord() - expect(await reads({ record, fenceOpen: true })).toEqual({ - record: plain.record - 1, - fence: plain.fence - 1 - }) - // A fence the connect saw held is probed again. - expect((await reads({ record, fenceOpen: false })).fence).toBe(plain.fence) - }) - - it('does not run chmod on a Windows remote', async () => { - scriptHost({ activationRecord: '', readiness: {}, log: [] }) - await installOrcadBundle( - { - conn: options().conn, - host: getRemoteHostPlatform('win32-x64'), - localOrcadDir: '/local/out/orcad', - target: 'win32-x64', - nodeRuntimeArchive: async () => '/cache/node.zip' - }, - NEW_VERSION, - `C:/Users/u/.orca-remote/orcad-${NEW_VERSION}` - ) - expect(uploadRemoteInstallDirectory).toHaveBeenCalledOnce() - expect(finalizeInstall).toHaveBeenCalledOnce() - expect(mockExec.mock.calls.some(([, command]) => String(command).startsWith('chmod '))).toBe( - false - ) - }) - it.each([ ['a fresh fence with no journal', false, false, 'orcad_activation_fence_busy'], ['a stale fence over a journal', true, true, 'orcad_activation_recovery_required'], @@ -438,38 +267,6 @@ describe('deployOrcad', () => { expect(uploadRemoteInstallDirectory).not.toHaveBeenCalled() }) - // BUG-21: interrupted wakes left bare stale fences that blocked every later update. - it('clears a stale fence no journal backs and goes on with the update', async () => { - vi.mocked(isRelayInstallLockStale).mockResolvedValueOnce(true) - let fenced = true - mockExec.mockImplementation(async (_conn, command) => { - const text = String(command) - if (text.includes('echo LOCKED || echo OPEN')) { - return fenced ? 'LOCKED\n' : 'OPEN\n' - } - if (text.includes('echo RELEASED')) { - fenced = false - } - return text.includes('__ORCAD_RECORD_ABSENT__') ? '__ORCAD_RECORD_ABSENT__\n' : '' - }) - await deployOrcad(options()).catch(() => undefined) - expect(vi.mocked(acquireInstallLock).mock.calls[0]?.[3]).toMatchObject({ - allowStaleTakeover: true - }) - expect(uploadRemoteInstallDirectory).toHaveBeenCalled() - }) - - it('leaves an upload incomplete when the remote cannot make search executable', async () => { - mockExec.mockImplementation(async (_conn, command) => { - if (String(command).startsWith('chmod 755 ')) { - throw new Error('chmod failed') - } - return String(command).includes('__ORCAD_RECORD_ABSENT__') ? '__ORCAD_RECORD_ABSENT__\n' : '' - }) - await expect(deployOrcad(options())).rejects.toThrow('chmod failed') - expect(vi.mocked(finalizeInstall)).not.toHaveBeenCalled() - }) - it.skipIf(process.platform === 'win32').each([undefined, 'linux-x64', 'linux-musl-x64'])( 'restores uploaded executable modes with optional browser %s', async (browserTarget) => { @@ -514,31 +311,6 @@ describe('deployOrcad', () => { } ) - it('allows startup time after a slow bundled preflight', async () => { - let elapsedMs = 0 - const clock = vi.spyOn(Date, 'now').mockImplementation(() => elapsedMs) - scriptHost({ - activationRecord: '', - readiness: { [NEW_VERSION]: readyLine({}) }, - readinessAtMs: 100_000, - log: [] - }) - try { - const result = await deployOrcad( - options({ - readinessTimeoutMs: undefined, - sleep: async () => { - elapsedMs += 50_000 - } - }) - ) - expect(result.outcome).toBe('installed-and-activated') - expect(elapsedMs).toBe(100_000) - } finally { - clock.mockRestore() - } - }) - it('activates a healthy candidate and records the outgoing version as the rollback target', async () => { const script: HostScript = { activationRecord: ACTIVE_OLD, @@ -557,50 +329,6 @@ describe('deployOrcad', () => { }) }) - it.each([ - ['activates', 'mid-upload', (r: OrcadActivationRecord) => r], - ['activates then stops', 'mid-upload', withDeactivatedVersionCommitted], - ['activates', 'before the upload', (r: OrcadActivationRecord) => r], - ['activates then stops', 'before the upload', withDeactivatedVersionCommitted] - ])( - 'applies the caller policy under the fence when another desktop %s a newer build %s', - async (_name, when, settle) => { - const newer = withActivatedVersion( - emptyOrcadActivationRecord(), - '0.3.0+cc01', - null, - new Date(1), - '1.6.0' - ) - const script: HostScript = { - activationRecord: when === 'mid-upload' ? ACTIVE_OLD : JSON.stringify(settle(newer)), - readiness: { [NEW_VERSION]: readyLine({}) }, - log: [] - } - scriptHost(script) - vi.mocked(uploadRemoteInstallDirectory).mockImplementationOnce(async () => { - script.activationRecord = JSON.stringify(settle(newer)) - }) - const admitRecord = vi.fn((record: OrcadActivationRecord) => - record.activeAppVersion === '1.6.0' ? 'host-newer' : null - ) - expect(await deployOrcad(options({ admitRecord }))).toMatchObject({ - outcome: 'installed-not-activated', - code: ORCAD_ACTIVATION_POLICY_REFUSED_CODE - }) - expect(admitRecord).toHaveBeenCalledWith( - expect.objectContaining({ activeAppVersion: '1.6.0' }), - NEW_VERSION - ) - expect(script.log).toEqual([]) - expect( - vi - .mocked(writeAtomicOrcadRemoteRecord) - .mock.calls.some(([, path]) => path.includes('orcad-active.json')) - ).toBe(false) - } - ) - it('treats the census as unverifiable when another incumbent lands mid-upload', async () => { const script: HostScript = { activationRecord: ACTIVE_OLD, @@ -623,48 +351,6 @@ describe('deployOrcad', () => { expect(script.log).toEqual([]) }) - it('keeps the census when the incumbent under the fence is the one it counted', async () => { - const script: HostScript = { - activationRecord: ACTIVE_OLD, - readiness: { [NEW_VERSION]: readyLine({}) }, - log: [] - } - scriptHost(script) - expect(await deployOrcad(options({ censusRecord: JSON.parse(ACTIVE_OLD) }))).toMatchObject({ - outcome: 'installed-and-activated' - }) - }) - - it('stops the incumbent before snapshotting, so SQLite WAL files are quiescent', async () => { - const script: HostScript = { - activationRecord: ACTIVE_OLD, - readiness: { [NEW_VERSION]: readyLine({}) }, - log: [] - } - scriptHost(script) - await deployOrcad(options()) - expect(script.log.indexOf('snapshot')).toBeGreaterThan(-1) - expect(script.log.indexOf('snapshot')).toBeLessThan(script.log.indexOf(`launch:${NEW_VERSION}`)) - expect(script.log.indexOf(`stop:${OLD_VERSION}`)).toBeLessThan(script.log.indexOf('snapshot')) - }) - - it('never recounts an incumbent other than the one it counted', async () => { - const script: HostScript = { - activationRecord: ACTIVE_OLD, - readiness: { [NEW_VERSION]: readyLine({}) }, - log: [] - } - scriptHost(script) - const counted = JSON.parse(ACTIVE_OLD) - const peer = withActivatedVersion(counted, '0.1.5+dd01', null, new Date(5), '1.4.0') - vi.mocked(uploadRemoteInstallDirectory).mockImplementationOnce(async () => { - script.activationRecord = JSON.stringify(peer) - }) - const recountCensus = vi.fn() - await deployOrcad(options({ censusRecord: counted, admitRecord: () => null, recountCensus })) - expect(recountCensus).not.toHaveBeenCalled() - }) - it('installs but does not activate when terminals are running', async () => { const script: HostScript = { activationRecord: ACTIVE_OLD, @@ -788,29 +474,6 @@ describe('deployOrcad', () => { ]) }) - it.each(['NO_PID', 'STILL_RUNNING', 'SIGNAL_FAILED', ''])( - 'does not inspect or replace state without confirmed candidate exit: %s', - async (candidateStopResult) => { - const script: HostScript = { - activationRecord: ACTIVE_OLD, - readiness: { [NEW_VERSION]: readyLine({ selfTestOk: false }) }, - log: [], - candidateStopResult - } - scriptHost(script) - - await deployOrcad(options()) - - expect(script.log).toEqual([ - 'preflight', - `stop:${OLD_VERSION}`, - 'snapshot', - `launch:${NEW_VERSION}`, - `stop:${NEW_VERSION}` - ]) - } - ) - it('refuses to activate when a different build answered the port', async () => { const script: HostScript = { activationRecord: ACTIVE_OLD, diff --git a/src/main/ssh/orcad-remote-deploy.ts b/src/main/managed-server/install/orcad-remote-deploy.ts similarity index 79% rename from src/main/ssh/orcad-remote-deploy.ts rename to src/main/managed-server/install/orcad-remote-deploy.ts index 8d09253142d..b949851b3d4 100644 --- a/src/main/ssh/orcad-remote-deploy.ts +++ b/src/main/managed-server/install/orcad-remote-deploy.ts @@ -1,25 +1,22 @@ /** Activate under a durable host fence/journal only after candidate readiness. Recover the incumbent only with safe profile state; retain changed state/snapshot for explicit recovery. */ -import { logOrcadActivationOutcome } from '../managed-server/activation/orcad-activation-outcome-log' +import { logOrcadActivationOutcome } from '../activation/orcad-activation-outcome-log' import { join } from 'node:path' import type { OrcadHostTransport } from './orcad-host-transport' -import type { OrcadUpdateForce } from './orcad-update-plan' -import { ORCAD_INSTALL_MODEL } from '../managed-server/install/remote-install-model' -import { - computeRemoteInstallDir, - readLocalFullVersion -} from '../managed-server/install/remote-versioned-install' -import { readOrcadActivationRecord } from '../managed-server/activation/orcad-activation-record-store' -import type { OrcadActivationRecord } from '../managed-server/activation/orcad-activation-record' -import type { OrcadActivationVerdict } from '../managed-server/activation/orcad-activation-gate' -import type { OrcadTerminalCensus } from '../../shared/orcad-terminal-census' -import type { RemoteHostPlatform } from './ssh-remote-platform' -import { installOrcadBundle } from '../managed-server/install/orcad-remote-install' -import { getAppEnvironment } from '../../shared/app-environment' -import type { NodeRuntimeTarget } from '../../shared/node-runtime-pin' -import { ORCAD_STARTUP_READINESS_TIMEOUT_MS } from '../../shared/orcad-profile-preflight' -import { materializeOrcadArtifact } from '../orcad/orcad-artifact-materializer' +import type { OrcadUpdateForce } from '../activation/orcad-update-plan' +import { ORCAD_INSTALL_MODEL } from './remote-install-model' +import { computeRemoteInstallDir, readLocalFullVersion } from './remote-versioned-install' +import { readOrcadActivationRecord } from '../activation/orcad-activation-record-store' +import type { OrcadActivationRecord } from '../activation/orcad-activation-record' +import type { OrcadActivationVerdict } from '../activation/orcad-activation-gate' +import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { installOrcadBundle } from './orcad-remote-install' +import { getAppEnvironment } from '../../../shared/app-environment' +import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' +import { ORCAD_STARTUP_READINESS_TIMEOUT_MS } from '../../../shared/orcad-profile-preflight' +import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' import { readOrcadBundleTarget } from './orcad-deployment-target' -import { resolveOrcadRuntimeTarget } from '../managed-server/lifecycle/orcad-runtime-target' +import { resolveOrcadRuntimeTarget } from '../lifecycle/orcad-runtime-target' import { orcadNodeRuntimeInstallOptions, type NodeRuntimeDownloadBudget @@ -28,9 +25,9 @@ import { orcadActivationFenceExists, resolveOrcadActivationReadinessTimeout, withOrcadActivationLock -} from '../managed-server/activation/orcad-activation-lock' -import { activateInstalledOrcad } from './orcad-installed-activation' -import { orcadActivationFenceRefusal } from '../managed-server/activation/orcad-activation-fence-hold' +} from '../activation/orcad-activation-lock' +import { activateInstalledOrcad } from '../activation/orcad-installed-activation' +import { orcadActivationFenceRefusal } from '../activation/orcad-activation-fence-hold' export type OrcadDeployOptions = { conn: OrcadHostTransport diff --git a/src/main/managed-server/install/orcad-remote-gc.ts b/src/main/managed-server/install/orcad-remote-gc.ts index 0cd1c2d5d71..b3a157973e1 100644 --- a/src/main/managed-server/install/orcad-remote-gc.ts +++ b/src/main/managed-server/install/orcad-remote-gc.ts @@ -1,5 +1,5 @@ // GC only orcad-owned slots; pin active, rollback, live-daemon and journal versions, skipping collection when recovery state is unreadable. -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from './orcad-host-transport' import { execCommand, isUnconfirmedSshCommandTermination @@ -16,13 +16,13 @@ import { orcadLivenessProbeCommand } from './orcad-remote-launch' import { gcRemoteNodeRuntimeStore } from './remote-node-runtime-store-gc' -import { readOrcadGcTransactionPins } from '../../ssh/orcad-gc-transaction-pins' +import { readOrcadGcTransactionPins } from '../activation/orcad-gc-transaction-pins' import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +} from '../../ssh/remote-host/ssh-remote-platform' +import { RELAY_REMOTE_DIR } from './remote-install-root' import { orcadWindowsHomeOpCommand } from './orcad-remote-windows-node' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { ORCAD_INSTALL_COMPLETE_FILENAME } from '../../../shared/orcad-artifacts' diff --git a/src/main/managed-server/install/orcad-remote-host-support.ts b/src/main/managed-server/install/orcad-remote-host-support.ts index 5c16d29ec82..c5ba1a79a36 100644 --- a/src/main/managed-server/install/orcad-remote-host-support.ts +++ b/src/main/managed-server/install/orcad-remote-host-support.ts @@ -1,5 +1,8 @@ // Windows operations use the host script; only POSIX command builders use this guard. -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' export class OrcadRemoteLaunchUnsupportedError extends Error { readonly code = 'orcad_remote_launch_unsupported_host' diff --git a/src/main/managed-server/install/orcad-remote-install-cached-probe.ts b/src/main/managed-server/install/orcad-remote-install-cached-probe.ts index e66a7d4d1af..f354d500e77 100644 --- a/src/main/managed-server/install/orcad-remote-install-cached-probe.ts +++ b/src/main/managed-server/install/orcad-remote-install-cached-probe.ts @@ -1,13 +1,16 @@ // WSL opt-in: one exec asks both "is the pinned runtime cached?" and "is this slot complete?". import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { REMOTE_NODE_RUNTIME_READY } from '../../ssh/orcad-remote-node-runtime-report' -import { probeRemoteInstallCompleteCommand } from '../../ssh/ssh-remote-commands' +import type { OrcadHostTransport } from './orcad-host-transport' +import { REMOTE_NODE_RUNTIME_READY } from './orcad-remote-node-runtime-report' +import { probeRemoteInstallCompleteCommand } from './remote-install-completeness-command' import { execCommand, isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' import { NODE_RUNTIME_PROMOTE_TIMEOUT_MS, remoteNodeRuntimeDir } from './orcad-remote-node-runtime' import { recordedRemoteNodeRuntimeProbeCommand } from './orcad-remote-node-runtime-recorded-probe' import { ORCAD_INSTALL_MODEL } from './remote-install-model' diff --git a/src/main/managed-server/install/orcad-remote-install.ts b/src/main/managed-server/install/orcad-remote-install.ts index feefecb2f93..c7d1ac525f5 100644 --- a/src/main/managed-server/install/orcad-remote-install.ts +++ b/src/main/managed-server/install/orcad-remote-install.ts @@ -10,13 +10,13 @@ import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { OrcadHostTransport } from './orcad-host-transport' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { ORCAD_INSTALL_MODEL } from './remote-install-model' import { acquireInstallLock } from './remote-install-lock' import { ORCAD_FENCE_OWNER_FILENAME } from '../activation/orcad-activation-fence-scope' -import { forgetHeldOrcadFence, rememberHeldOrcadFence } from '../../ssh/orcad-held-fence-tokens' -import { exitedOwnLockProof } from '../../ssh/orcad-exited-own-lock' +import { forgetHeldOrcadFence, rememberHeldOrcadFence } from '../activation/orcad-held-fence-tokens' +import { exitedOwnLockProof } from '../activation/orcad-exited-own-lock' import { orcadWindowsBaseDir } from './orcad-remote-windows-node' import { uploadRemoteInstallDirectory, writeRemoteInstallFile } from './remote-install-transfers' import { diff --git a/src/main/managed-server/install/orcad-remote-launch-file-modes.test.ts b/src/main/managed-server/install/orcad-remote-launch-file-modes.test.ts index 886d4a4815e..65572fa583d 100644 --- a/src/main/managed-server/install/orcad-remote-launch-file-modes.test.ts +++ b/src/main/managed-server/install/orcad-remote-launch-file-modes.test.ts @@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' import { ORCAD_LOG_FILENAME, ORCAD_READINESS_FILENAME } from './orcad-remote-host-support' import { orcadLaunchCommand } from './orcad-remote-launch' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' // Pairing tokens in readiness require owner-only launch artifacts even under login umask 022. diff --git a/src/main/managed-server/install/orcad-remote-launch-setsid.test.ts b/src/main/managed-server/install/orcad-remote-launch-setsid.test.ts index 07442416329..b3d2c5b7d71 100644 --- a/src/main/managed-server/install/orcad-remote-launch-setsid.test.ts +++ b/src/main/managed-server/install/orcad-remote-launch-setsid.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { ORCAD_PID_FILENAME, ORCAD_READINESS_FILENAME } from './orcad-remote-host-support' import { orcadLaunchCommand, type OrcadLaunchSpec } from './orcad-remote-launch' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const host = getRemoteHostPlatform('linux-x64') diff --git a/src/main/managed-server/install/orcad-remote-launch-windows.ts b/src/main/managed-server/install/orcad-remote-launch-windows.ts index fb80ee61436..6659d0e6899 100644 --- a/src/main/managed-server/install/orcad-remote-launch-windows.ts +++ b/src/main/managed-server/install/orcad-remote-launch-windows.ts @@ -9,7 +9,7 @@ import { WINDOWS_BREAKAWAY_STDERR_KEEP_PREVIOUS_FLAG, WINDOWS_BREAKAWAY_STDOUT_FLAG } from '../../../shared/windows-breakaway-launch' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { orcadWindowsNodeCommandLine, orcadWindowsSlotOpCommand, diff --git a/src/main/managed-server/install/orcad-remote-launch.test.ts b/src/main/managed-server/install/orcad-remote-launch.test.ts index 884befd335e..5bc4f00b664 100644 --- a/src/main/managed-server/install/orcad-remote-launch.test.ts +++ b/src/main/managed-server/install/orcad-remote-launch.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { orcadLivenessProbeCommand, parseOrcadLiveness } from './orcad-remote-launch' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const posix = getRemoteHostPlatform('linux-x64') getRemoteHostPlatform('win32-x64') diff --git a/src/main/managed-server/install/orcad-remote-launch.ts b/src/main/managed-server/install/orcad-remote-launch.ts index f7ec6249cdf..ec87174a628 100644 --- a/src/main/managed-server/install/orcad-remote-launch.ts +++ b/src/main/managed-server/install/orcad-remote-launch.ts @@ -1,5 +1,5 @@ // Redirect detached candidate stdout to its version directory so readiness does not hold SSH open. -import type { OrcadLaunchEnvEntry } from '../../ssh/orcad-host-transport' +import type { OrcadLaunchEnvEntry } from './orcad-host-transport' import { ORCAD_LAUNCHER_FILENAME, ORCAD_SERVER_ENTRY_FILENAME @@ -11,8 +11,8 @@ import { remoteBasename, remoteDirname, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +} from '../../ssh/remote-host/ssh-remote-platform' +import { RELAY_REMOTE_DIR } from './remote-install-root' import { ORCAD_WSL_HOST_ENV } from '../../ipc/wsl-guest-windows-drive-path' import { assertPosixOrcadHost as assertPosixHost, @@ -33,7 +33,7 @@ import { captureOrcadLaunchSshSessionCommand, recordsOrcadLaunchSshSession, writeOrcadLaunchSshSessionCommand -} from '../../ssh/orcad-launch-ssh-session' +} from './orcad-launch-ssh-session' import { ORCAD_E2E_IDLE_TIMEOUT_ENV, readOrcadE2EIdleTimeoutMs diff --git a/src/main/managed-server/install/orcad-remote-log-tail.ts b/src/main/managed-server/install/orcad-remote-log-tail.ts index 5e72c5e6555..bbe270ee646 100644 --- a/src/main/managed-server/install/orcad-remote-log-tail.ts +++ b/src/main/managed-server/install/orcad-remote-log-tail.ts @@ -7,7 +7,7 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { orcadWindowsSlotOpCommand, readOrcadWindowsEncodedAnswer diff --git a/src/main/managed-server/install/orcad-remote-node-runtime-recorded-probe.ts b/src/main/managed-server/install/orcad-remote-node-runtime-recorded-probe.ts index b73e29b1fc3..2106c4d324d 100644 --- a/src/main/managed-server/install/orcad-remote-node-runtime-recorded-probe.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime-recorded-probe.ts @@ -1,13 +1,13 @@ // WSL opt-in reuses verified runtime stat signatures; inode replacement or in-place ctime change forces a full hash. import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { assertPosixOrcadHost } from './orcad-remote-host-support' import { REMOTE_NODE_RUNTIME_MISSING, REMOTE_NODE_RUNTIME_READY, REMOTE_NODE_RUNTIME_VERIFIED_MARKER -} from '../../ssh/orcad-remote-node-runtime-report' +} from './orcad-remote-node-runtime-report' import { posixNodeRuntimeExecutable } from './orcad-remote-node-runtime' import { remoteSha256Command } from './remote-sha256-command' diff --git a/src/main/ssh/orcad-remote-node-runtime-report.ts b/src/main/managed-server/install/orcad-remote-node-runtime-report.ts similarity index 97% rename from src/main/ssh/orcad-remote-node-runtime-report.ts rename to src/main/managed-server/install/orcad-remote-node-runtime-report.ts index f408d482aa8..4dd8663c0a7 100644 --- a/src/main/ssh/orcad-remote-node-runtime-report.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime-report.ts @@ -1,5 +1,5 @@ -import { parseMissingSharedLibrary } from '../orcad/native-host-abi' -import { RelayHostAnsweredError } from './remote-exec/remote-host-answered-failure' +import { parseMissingSharedLibrary } from '../../orcad/native-host-abi' +import { RelayHostAnsweredError } from '../../ssh/remote-exec/remote-host-answered-failure' export const REMOTE_NODE_RUNTIME_READY = 'ORCA_NODE_RUNTIME_READY' export const REMOTE_NODE_RUNTIME_MISSING = 'ORCA_NODE_RUNTIME_MISSING' diff --git a/src/main/managed-server/install/orcad-remote-node-runtime-windows.ts b/src/main/managed-server/install/orcad-remote-node-runtime-windows.ts index 2544d953bc6..282f6c85f17 100644 --- a/src/main/managed-server/install/orcad-remote-node-runtime-windows.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime-windows.ts @@ -16,8 +16,8 @@ import { REMOTE_NODE_RUNTIME_SELFTEST_FAILED, REMOTE_NODE_RUNTIME_VERIFIED_MARKER, REMOTE_WINDOWS_BUILD_UNSUPPORTED -} from '../../ssh/orcad-remote-node-runtime-report' -import { powerShellCommand } from '../../ssh/ssh-remote-powershell' +} from './orcad-remote-node-runtime-report' +import { powerShellCommand } from '../../ssh/remote-exec/ssh-remote-powershell' import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' function windowsPath(...segments: string[]): string { diff --git a/src/main/managed-server/install/orcad-remote-node-runtime.test.ts b/src/main/managed-server/install/orcad-remote-node-runtime.test.ts index 9cfdb33dfb6..da0d5213e43 100644 --- a/src/main/managed-server/install/orcad-remote-node-runtime.test.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime.test.ts @@ -23,9 +23,9 @@ import { import { REMOTE_NODE_RUNTIME_MISSING, REMOTE_NODE_RUNTIME_READY -} from '../../ssh/orcad-remote-node-runtime-report' +} from './orcad-remote-node-runtime-report' import { orcadNodeSlotRuntimeCommand } from './orcad-remote-runtime' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const directories: string[] = [] afterEach(() => { diff --git a/src/main/managed-server/install/orcad-remote-node-runtime.ts b/src/main/managed-server/install/orcad-remote-node-runtime.ts index f03cdbddc5f..d0fbe620250 100644 --- a/src/main/managed-server/install/orcad-remote-node-runtime.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime.ts @@ -14,7 +14,7 @@ import { ORCAD_RUNTIMES_DIRNAME, orcadNodeRuntimeExecutable } from '../../../shared/orcad-artifacts' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from './orcad-host-transport' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { execCommand, @@ -28,7 +28,7 @@ import { joinRemotePath, remoteDirname, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { assertPosixOrcadHost } from './orcad-remote-host-support' import { withRuntimeStoreLock, type HeldRuntimeStoreLock } from './remote-node-runtime-store-lock' import { @@ -41,7 +41,7 @@ import { REMOTE_NODE_RUNTIME_READY, REMOTE_NODE_RUNTIME_SELFTEST_FAILED, REMOTE_NODE_RUNTIME_VERIFIED_MARKER -} from '../../ssh/orcad-remote-node-runtime-report' +} from './orcad-remote-node-runtime-report' import { windowsNodeRuntimePresentCommand, windowsNodeRuntimeProbeCommand, diff --git a/src/main/managed-server/install/orcad-remote-preflight.ts b/src/main/managed-server/install/orcad-remote-preflight.ts index 977ec9c460b..5ea74f4386a 100644 --- a/src/main/managed-server/install/orcad-remote-preflight.ts +++ b/src/main/managed-server/install/orcad-remote-preflight.ts @@ -22,8 +22,8 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +} from '../../ssh/remote-host/ssh-remote-platform' +import type { OrcadHostTransport } from './orcad-host-transport' export function orcadProfilePreflightCommand( host: RemoteHostPlatform, diff --git a/src/main/managed-server/install/orcad-remote-primitives.test.ts b/src/main/managed-server/install/orcad-remote-primitives.test.ts index 81d628a6c0b..3bd4bebda74 100644 --- a/src/main/managed-server/install/orcad-remote-primitives.test.ts +++ b/src/main/managed-server/install/orcad-remote-primitives.test.ts @@ -8,13 +8,15 @@ vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ( error instanceof Error && error.message === 'channel lost' })) -vi.mock('../../ssh/ssh-remote-platform-detection', () => ({ detectRemoteHostPlatform: vi.fn() })) +vi.mock('../../ssh/remote-host/ssh-remote-platform-detection', () => ({ + detectRemoteHostPlatform: vi.fn() +})) vi.mock('../host-state/orcad-windows-host-preparation', () => ({ prepareWindowsOrcadHost: vi.fn() })) import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { parseOrcadReadinessOutput } from './orcad-remote-launch' const mockExec = vi.mocked(execCommand) diff --git a/src/main/managed-server/install/orcad-remote-process-control.ts b/src/main/managed-server/install/orcad-remote-process-control.ts index 544ca65f611..9b430e9d764 100644 --- a/src/main/managed-server/install/orcad-remote-process-control.ts +++ b/src/main/managed-server/install/orcad-remote-process-control.ts @@ -4,7 +4,7 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { ORCAD_READINESS_FILENAME, ORCAD_PID_FILENAME, diff --git a/src/main/managed-server/install/orcad-remote-readiness-wait.test.ts b/src/main/managed-server/install/orcad-remote-readiness-wait.test.ts index c21885b6e0c..d0a3ed6583a 100644 --- a/src/main/managed-server/install/orcad-remote-readiness-wait.test.ts +++ b/src/main/managed-server/install/orcad-remote-readiness-wait.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' import { orcadReadinessWaitCommand } from './orcad-remote-readiness-wait' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { ORCAD_LAUNCH_MACHINE_COMMAND } from './orcad-remote-host-support' diff --git a/src/main/managed-server/install/orcad-remote-readiness-wait.ts b/src/main/managed-server/install/orcad-remote-readiness-wait.ts index e066e110b60..ad5909abfe3 100644 --- a/src/main/managed-server/install/orcad-remote-readiness-wait.ts +++ b/src/main/managed-server/install/orcad-remote-readiness-wait.ts @@ -4,7 +4,7 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { ORCAD_PID_FILENAME, ORCAD_PID_MACHINE_FILENAME, diff --git a/src/main/managed-server/install/orcad-remote-record-file.ts b/src/main/managed-server/install/orcad-remote-record-file.ts index 537d05247a1..9581c0468d0 100644 --- a/src/main/managed-server/install/orcad-remote-record-file.ts +++ b/src/main/managed-server/install/orcad-remote-record-file.ts @@ -1,10 +1,10 @@ // Unreadable host records must not look absent: deploying over an unknown live install is unsafe. import { randomUUID } from 'node:crypto' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { removeRemoteFileCommand } from '../../ssh/ssh-remote-commands' +import { removeRemoteFileCommand } from '../../ssh/remote-exec/ssh-remote-commands' import { execOrcadRemote, type OrcadRemoteExecTarget } from './orcad-remote-runtime-control' import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' -import { isWindowsRemoteHost } from '../../ssh/ssh-remote-platform' +import { isWindowsRemoteHost } from '../../ssh/remote-host/ssh-remote-platform' import { orcadRemoteBaseDir, orcadWindowsHostOpCommand, diff --git a/src/main/managed-server/install/orcad-remote-rollback.ts b/src/main/managed-server/install/orcad-remote-rollback.ts index 4c13b2f4b93..0a1faffa952 100644 --- a/src/main/managed-server/install/orcad-remote-rollback.ts +++ b/src/main/managed-server/install/orcad-remote-rollback.ts @@ -1,14 +1,14 @@ // Rollback restores a pre-activation snapshot: older builds may not understand newer state. // Stop, rescue, restore, then launch; the rescue and fenced journal allow recovery of interrupted steps. import { logOrcadActivationOutcome } from '../activation/orcad-activation-outcome-log' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from './orcad-host-transport' import type { OrcadActivationRecord } from '../activation/orcad-activation-record' import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' import type { OrcadActivationVerdict } from '../activation/orcad-activation-gate' -import type { OrcadDaemonProtocolFacts } from '../../ssh/orcad-daemon-protocol-crossing' +import type { OrcadDaemonProtocolFacts } from '../activation/orcad-daemon-protocol-crossing' import { readOrcadActivationRecord } from '../activation/orcad-activation-record-store' import { sameOrcadActivationRecord } from '../activation/orcad-activation-transaction' -import type { RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { resolveOrcadActivationReadinessTimeout, withOrcadActivationLock diff --git a/src/main/managed-server/install/orcad-remote-runtime-control.ts b/src/main/managed-server/install/orcad-remote-runtime-control.ts index 44743737943..6f194d1ce73 100644 --- a/src/main/managed-server/install/orcad-remote-runtime-control.ts +++ b/src/main/managed-server/install/orcad-remote-runtime-control.ts @@ -19,7 +19,7 @@ import { orcadReadinessWaitCommand, parseOrcadReadinessWaitOutput } from './orcad-remote-readiness-wait' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from './orcad-host-transport' import { errorMessage } from '../../../shared/error-message' import { execCommand, @@ -34,7 +34,10 @@ import { } from '../activation/orcad-activation-fence-scope' import { orcadWindowsHomeOpCommand } from './orcad-remote-windows-node' import { ORCAD_WINDOWS_FENCE_ARG } from '../host-state/orcad-windows-host-fence-ops' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' // Pause even after early host answers to avoid a tight retry loop. const READINESS_RETRY_PAUSE_MS = 1_000 diff --git a/src/main/managed-server/install/orcad-remote-runtime.test.ts b/src/main/managed-server/install/orcad-remote-runtime.test.ts index f9ce9487c76..972fa867fae 100644 --- a/src/main/managed-server/install/orcad-remote-runtime.test.ts +++ b/src/main/managed-server/install/orcad-remote-runtime.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { runProcessSync } from '@orca/process-host' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { selectOrcadSlotRuntimeCommand } from './orcad-remote-runtime' import { stopOrcadCommand } from './orcad-remote-process-control' diff --git a/src/main/managed-server/install/orcad-remote-runtime.ts b/src/main/managed-server/install/orcad-remote-runtime.ts index 097b353b3ca..45340fef431 100644 --- a/src/main/managed-server/install/orcad-remote-runtime.ts +++ b/src/main/managed-server/install/orcad-remote-runtime.ts @@ -10,7 +10,7 @@ import { } from '../../../shared/orcad-artifacts' import { assertPosixOrcadHost } from './orcad-remote-host-support' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' // Assign the long slot path once to reduce command size on the wire. function assignOrcadSlot(directory: string): string { diff --git a/src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts b/src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts index b9222012f2b..b7a9e0f6a3e 100644 --- a/src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts +++ b/src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts @@ -28,7 +28,7 @@ import { parseOrcadSnapshotRestore, restoreOrcadStateSnapshotCommand } from '../host-state/orcad-state-snapshot' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const host = getRemoteHostPlatform('linux-x64') let root = '' diff --git a/src/main/managed-server/install/orcad-remote-windows-node.ts b/src/main/managed-server/install/orcad-remote-windows-node.ts index 267430577db..b5ba4157128 100644 --- a/src/main/managed-server/install/orcad-remote-windows-node.ts +++ b/src/main/managed-server/install/orcad-remote-windows-node.ts @@ -8,17 +8,17 @@ import { } from '../../../shared/orcad-artifacts' import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { randomUUID } from 'node:crypto' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from './orcad-host-transport' import { execCommand, isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import { RELAY_REMOTE_DIR } from './remote-install-root' import { joinRemotePath, remoteDirname, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' import { ORCAD_WINDOWS_COMMAND_LINE_UNSAFE_CODE } from '../../orcad/orcad-host-unavailable' import { diff --git a/src/main/managed-server/install/pinned-runtime-host-target.test.ts b/src/main/managed-server/install/pinned-runtime-host-target.test.ts new file mode 100644 index 00000000000..c2f5b5c45ee --- /dev/null +++ b/src/main/managed-server/install/pinned-runtime-host-target.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' + +import { pinnedRuntimeTargetForHost } from './pinned-runtime-host-target' + +describe('pinned runtime host target', () => { + it('names the runtime a host can run by glibc alone', () => { + expect( + pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 28 } }) + ).toBe('linux-x64-glibc') + expect( + pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 27 } }) + ).toBe('linux-x64-glibc217') + expect( + pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 17 } }) + ).toBe('linux-x64-glibc217') + expect( + pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 12 } }) + ).toBeNull() + expect( + pinnedRuntimeTargetForHost({ target: 'linux-arm64-glibc', glibc: { major: 2, minor: 17 } }) + ).toBeNull() + expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: null })).toBe( + 'linux-x64-glibc' + ) + expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-musl', glibc: null })).toBe( + 'linux-x64-musl' + ) + }) +}) diff --git a/src/main/ssh/pinned-runtime-host-target.ts b/src/main/managed-server/install/pinned-runtime-host-target.ts similarity index 94% rename from src/main/ssh/pinned-runtime-host-target.ts rename to src/main/managed-server/install/pinned-runtime-host-target.ts index 49882c8f7d0..a592d9ca6e2 100644 --- a/src/main/ssh/pinned-runtime-host-target.ts +++ b/src/main/managed-server/install/pinned-runtime-host-target.ts @@ -6,8 +6,8 @@ import { type CompatServerTarget, type NodeRuntimeTarget, type ServerTarget -} from '../../shared/node-runtime-pin' -import type { GlibcVersion } from '../node-runtime/linux-libc-probe' +} from '../../../shared/node-runtime-pin' +import type { GlibcVersion } from '../../node-runtime/linux-libc-probe' /** Official linux builds of the pinned Node need glibc 2.28. */ export const PINNED_NODE_GLIBC_FLOOR: GlibcVersion = { major: 2, minor: 28 } diff --git a/src/main/managed-server/install/remote-install-completeness-command.ts b/src/main/managed-server/install/remote-install-completeness-command.ts new file mode 100644 index 00000000000..6372be4b1ed --- /dev/null +++ b/src/main/managed-server/install/remote-install-completeness-command.ts @@ -0,0 +1,33 @@ +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { isWindowsRemoteHost, joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' + +import { powerShellCommand } from '../../ssh/remote-exec/ssh-remote-powershell' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' + +/** Require the directory and every declared regular-file artifact; incomplete installs must report missing. */ +export function probeRemoteInstallCompleteCommand( + host: RemoteHostPlatform, + remoteInstallDir: string, + requiredFilenames: readonly string[] +): string { + if (!isWindowsRemoteHost(host)) { + // Use relative artifacts inside a subshell to fit gateway exec budgets without leaking cd (#30491). + const fileTests = requiredFilenames + .map((filename) => `&& test -f ${quotePosixShell(filename)} `) + .join('') + return `(cd ${quotePosixShell(remoteInstallDir)} 2>/dev/null ${fileTests}) && echo OK || echo MISSING` + } + const required = requiredFilenames.map((filename) => + joinRemotePath(host, remoteInstallDir, filename) + ) + return powerShellCommand( + [ + `$dir = ${powerShellLiteral(remoteInstallDir)}`, + `$required = @(${required.map((path) => powerShellLiteral(path)).join(', ')})`, + '$ok = Test-Path -LiteralPath $dir -PathType Container', + 'foreach ($f in $required) { if (-not (Test-Path -LiteralPath $f -PathType Leaf)) { $ok = $false } }', + "if ($ok) { 'OK' } else { 'MISSING' }" + ].join('; ') + ) +} diff --git a/src/main/managed-server/install/remote-install-gc-claim-termination.test.ts b/src/main/managed-server/install/remote-install-gc-claim-termination.test.ts index 10940f6efeb..c487f82020e 100644 --- a/src/main/managed-server/install/remote-install-gc-claim-termination.test.ts +++ b/src/main/managed-server/install/remote-install-gc-claim-termination.test.ts @@ -12,8 +12,8 @@ import { releaseRelayGcClaimWithRetry, tryAcquireRelayGcClaim } from './remote-install-gc-claim' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import { unusedSshConnection } from '../../ssh/unused-host-transport.test-fixture' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { unusedSshConnection } from '../testing/managed-host-transport.test-fixture' const conn = unusedSshConnection() const mockExec = vi.mocked(execCommand) diff --git a/src/main/managed-server/install/remote-install-gc-claim.ts b/src/main/managed-server/install/remote-install-gc-claim.ts index 6b1e1a9e7d6..99c4e49e5cf 100644 --- a/src/main/managed-server/install/remote-install-gc-claim.ts +++ b/src/main/managed-server/install/remote-install-gc-claim.ts @@ -8,15 +8,15 @@ import { tryCreateInstallLockCommand, tryStealInstallLockCommand } from './remote-install-lock-commands' -import { removeRemoteTreeCommand } from '../../ssh/ssh-remote-commands' -import { powerShellCommand } from '../../ssh/ssh-remote-powershell' +import { removeRemoteTreeCommand } from '../../ssh/remote-exec/ssh-remote-commands' +import { powerShellCommand } from '../../ssh/remote-exec/ssh-remote-powershell' import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' import { getRemoteHostPlatform, isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' const DEFAULT_REMOTE_HOST = getRemoteHostPlatform('linux-x64') const RELAY_GC_CLAIM_SUFFIX = '.gc-claim' diff --git a/src/main/managed-server/install/remote-install-gc-listing-command.ts b/src/main/managed-server/install/remote-install-gc-listing-command.ts new file mode 100644 index 00000000000..9511b560ae1 --- /dev/null +++ b/src/main/managed-server/install/remote-install-gc-listing-command.ts @@ -0,0 +1,37 @@ +import { remoteInstallListingRegexSource } from './remote-install-model' +import type { RemoteInstallModel } from './remote-install-model' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { isWindowsRemoteHost } from '../../ssh/remote-host/ssh-remote-platform' +import { powerShellCommand } from '../../ssh/remote-exec/ssh-remote-powershell' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' + +export const MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES = 64 + +/** Scope both listing glob and validation regex by install model so orcad GC never even receives legacy relay directory names. */ +export function listRemoteInstallBaseDirsCommand( + host: RemoteHostPlatform, + baseDir: string, + model: RemoteInstallModel +): string { + const namePattern = remoteInstallListingRegexSource(model) + if (!isWindowsRemoteHost(host)) { + const statusPrefix = '__ORCA_RELAY_GC_FIND_STATUS__' + return [ + `base=${quotePosixShell(baseDir)}; [ -d "$base" ] || exit 0;`, + `{ find "$base" -mindepth 1 -maxdepth 1 -type d -name '${model.dirPrefix}-*' -print; status=$?; printf '\n${statusPrefix}%s\n' "$status"; } |`, + String.raw`awk 'BEGIN { count=0; status=-1 } /^${statusPrefix}[0-9]+$/ { status=substr($0, ${statusPrefix.length + 1}); next } { name=$0; sub(/^.*\//, "", name); if (name ~ /${namePattern}/ && count < ${MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES}) { entries[count++]=name } } END { if (status != 0) exit 1; for (i=0; i() - - constructor(private readonly child: PipedChildProcess) { - super({ autoDestroy: false, emitClose: false }) - this.stderr = child.stderr - child.stdout.pipe(this) - child.stdout.on('error', (error) => this.emit('error', error)) - child.on('error', (error) => { - this.exited.resolve() - this.emit('error', error) - }) - child.on('close', (code) => { - this.exited.resolve() - this.emit('close', code) - }) - child.stdin.end() - } - - async dispose(): Promise { - this.close() - await this.exited.promise - this.destroy() - } - - close(): void { - this.child.kill() - } - - eof(): void { - this.end() - } - - setWindow(): void { - throw new Error('GC listing does not resize a terminal') - } - - signal(): void { - throw new Error('GC listing does not signal a terminal') - } - - exit(): void { - throw new Error('GC listing does not set a remote exit status') - } -} - -export async function runCappedRelayGcShellCommand(command: string): Promise { - let channel: RelayGcShellChannel | undefined - const connection: Pick = { - exec: async (shellCommand) => { - channel = new RelayGcShellChannel( - spawnProcess({ program: '/bin/sh', args: ['-c', shellCommand] }) - ) - return channel - }, - usesSystemSshTransport: () => false - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: execCommand only reads exec and usesSystemSshTransport; both methods are checked above. - const sshConnection = connection as SshConnection - try { - return await execCommand(sshConnection, command) - } finally { - await channel?.dispose() - } -} - -export function createRelayGcListingFixture(): { - root: string - findCommand: string - validNames: string[] - fillValidEntryBoundary: () => void - dispose: () => void -} { - const workspace = mkdtempSync(join(tmpdir(), 'orca-relay-gc-scale-')) - let root = workspace - try { - // Long Unicode paths cross the SSH character cap with fewer real directories. - for (let index = 0; index < 4; index += 1) { - root = join(root, `gc-context-${index}-ü-${'x'.repeat(150)}`) - mkdirSync(root) - } - const validNames = ['relay-0.1.0+aaa', 'relay-0.1.0+bbb'] - const stageName = (index: number): string => - `relay-9.9.9+abc.upload-${String(index).padStart(12, '0')}` - const stageCount = - Math.ceil(SSH_EXEC_OUTPUT_CAP_CHARS / (join(root, stageName(0)).length + 1)) + 1 - for (let index = 0; index < stageCount; index += 1) { - mkdirSync(join(root, stageName(index))) - } - for (const name of validNames) { - mkdirSync(join(root, name)) - } - mkdirSync(join(root, 'relay-0.1.0+abc.upload-000000000000')) - mkdirSync(join(root, 'relay-0.1.0+ggg')) - mkdirSync(join(root, 'orcad-0.1.0+aaa')) - mkdirSync(join(root, stageName(0), 'relay-0.1.0+ccc')) - writeFileSync(join(root, 'relay-0.1.0+ddd'), '') - symlinkSync(join(root, validNames[0]), join(root, 'relay-0.1.0+eee'), 'dir') - return { - root, - findCommand: `find ${quotePosixShell(root)} -mindepth 1 -maxdepth 1 -type d -name 'relay-*' -print`, - validNames, - fillValidEntryBoundary: () => { - for (let index = 0; index < 63; index += 1) { - const name = `relay-0.1.0+${index.toString(16)}` - validNames.push(name) - mkdirSync(join(root, name)) - } - }, - dispose: () => rmSync(workspace, { recursive: true, force: true }) - } - } catch (error) { - rmSync(workspace, { recursive: true, force: true }) - throw error - } -} - -export async function readUncappedRelayGcPaths(command: string): Promise { - const result = await runProcess({ - program: '/bin/sh', - args: ['-c', command], - maxOutputBytes: 4 * SSH_EXEC_OUTPUT_CAP_CHARS - }) - if (result.code !== 0 || result.timedOut || result.outputTruncated) { - throw new Error(`GC fixture enumeration failed: ${result.code}: ${result.stderr}`) - } - return result.stdout.trim().split('\n') -} diff --git a/src/main/managed-server/install/remote-install-gc-tombstone.ts b/src/main/managed-server/install/remote-install-gc-tombstone.ts index 9b64384396e..8bfdc3b5b71 100644 --- a/src/main/managed-server/install/remote-install-gc-tombstone.ts +++ b/src/main/managed-server/install/remote-install-gc-tombstone.ts @@ -4,13 +4,13 @@ import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' import { remoteInstallGcTombstoneRegex, type RemoteInstallModel } from './remote-install-model' -import { removeRemoteTreeCommand } from '../../ssh/ssh-remote-commands' +import { removeRemoteTreeCommand } from '../../ssh/remote-exec/ssh-remote-commands' import { getRemoteHostPlatform, isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' const DEFAULT_REMOTE_HOST = getRemoteHostPlatform('linux-x64') diff --git a/src/main/managed-server/install/remote-install-gc.ts b/src/main/managed-server/install/remote-install-gc.ts index a23a21b08e6..6986c218397 100644 --- a/src/main/managed-server/install/remote-install-gc.ts +++ b/src/main/managed-server/install/remote-install-gc.ts @@ -1,6 +1,6 @@ // Preserve legacy relay directories until the relay-era upgrade window closes. import type { RemoteInstallTransport } from './remote-install-transport' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import { RELAY_REMOTE_DIR } from './remote-install-root' import { execHostCommand } from '../../ssh/remote-exec/remote-host-exec' import { probeInstallLockExistsCommand } from './remote-install-lock-commands' import { RELAY_INSTALL_LOCK_NAME } from '../../../shared/relay-install-lock-name' @@ -18,17 +18,19 @@ import { import { cleanupRemoteInstallGcTombstones } from './remote-install-gc-tombstone' import { listRemoteInstallBaseDirsCommand, - MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES, + MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES +} from './remote-install-gc-listing-command' +import { moveRemoteTreeCommand, probeFileExistsCommand, removeRemoteTreeCommand -} from '../../ssh/ssh-remote-commands' +} from '../../ssh/remote-exec/ssh-remote-commands' import { getRemoteHostPlatform, joinRemotePath, remoteBasename, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' const DEFAULT_REMOTE_HOST = getRemoteHostPlatform('linux-x64') diff --git a/src/main/managed-server/install/remote-install-lock-commands.ts b/src/main/managed-server/install/remote-install-lock-commands.ts index e8236256725..2b82847f41d 100644 --- a/src/main/managed-server/install/remote-install-lock-commands.ts +++ b/src/main/managed-server/install/remote-install-lock-commands.ts @@ -1,7 +1,10 @@ import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { powerShellCommand } from '../../ssh/ssh-remote-powershell' +import { powerShellCommand } from '../../ssh/remote-exec/ssh-remote-powershell' import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' import * as exitedOwnerSteal from './remote-install-lock-exited-owner' const INSTALL_LOCK_BOOT_ID_NAME = '.boot-id' diff --git a/src/main/managed-server/install/remote-install-lock-exited-owner.test.ts b/src/main/managed-server/install/remote-install-lock-exited-owner.test.ts index 0d67de04bc8..4578bd559a7 100644 --- a/src/main/managed-server/install/remote-install-lock-exited-owner.test.ts +++ b/src/main/managed-server/install/remote-install-lock-exited-owner.test.ts @@ -13,8 +13,11 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' import { tryStealInstallLockCommand } from './remote-install-lock-commands' -import { decodeRemotePowerShellScript } from '../../ssh/ssh-remote-powershell' -import { getRemoteHostPlatform, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { decodeRemotePowerShellScript } from '../../ssh/remote-exec/ssh-remote-powershell' +import { + getRemoteHostPlatform, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' const OWNER = '.orca-fence-owner' const successor = { fileName: OWNER, token: 't-relaunch' } diff --git a/src/main/managed-server/install/remote-install-lock-termination.test.ts b/src/main/managed-server/install/remote-install-lock-termination.test.ts index 9a8780920e5..da282da7ad2 100644 --- a/src/main/managed-server/install/remote-install-lock-termination.test.ts +++ b/src/main/managed-server/install/remote-install-lock-termination.test.ts @@ -8,8 +8,8 @@ vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ( import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { acquireInstallLock, isRelayInstallLockStale } from './remote-install-lock' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import { unusedSshConnection } from '../../ssh/unused-host-transport.test-fixture' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { unusedSshConnection } from '../testing/managed-host-transport.test-fixture' const conn = unusedSshConnection() const mockExec = vi.mocked(execCommand) diff --git a/src/main/managed-server/install/remote-install-lock.ts b/src/main/managed-server/install/remote-install-lock.ts index 6c6b9b2cddb..5f83dd047ef 100644 --- a/src/main/managed-server/install/remote-install-lock.ts +++ b/src/main/managed-server/install/remote-install-lock.ts @@ -15,8 +15,8 @@ import { getRemoteHostPlatform, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' -import { removeRemoteTreeCommand } from '../../ssh/ssh-remote-commands' +} from '../../ssh/remote-host/ssh-remote-platform' +import { removeRemoteTreeCommand } from '../../ssh/remote-exec/ssh-remote-commands' import { RELAY_INSTALL_LOCK_NAME } from '../../../shared/relay-install-lock-name' const INSTALL_LOCK_POLL_MS = 1_000 diff --git a/src/main/managed-server/install/remote-install-model.test.ts b/src/main/managed-server/install/remote-install-model.test.ts index 4a3d0aa2f20..be5488040b6 100644 --- a/src/main/managed-server/install/remote-install-model.test.ts +++ b/src/main/managed-server/install/remote-install-model.test.ts @@ -4,11 +4,9 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { describe, expect, it } from 'vitest' import { orcadRipgrepArtifact } from '../../../shared/orcad-artifacts' -import { - listRemoteInstallBaseDirsCommand, - probeRemoteInstallCompleteCommand -} from '../../ssh/ssh-remote-commands' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { listRemoteInstallBaseDirsCommand } from './remote-install-gc-listing-command' +import { probeRemoteInstallCompleteCommand } from './remote-install-completeness-command' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { inventoryRemoteInstallDirs, diff --git a/src/main/managed-server/install/remote-install-model.ts b/src/main/managed-server/install/remote-install-model.ts index 16c899ea691..b7bcef88941 100644 --- a/src/main/managed-server/install/remote-install-model.ts +++ b/src/main/managed-server/install/remote-install-model.ts @@ -3,14 +3,17 @@ import { relayArtifactFilenames, RELAY_INSTALL_COMPLETE_FILENAME, RELAY_VERSION_FILENAME -} from '../../ssh/relay-install-artifacts' +} from '../../ssh/legacy-relay/endpoints/relay-install-artifacts' import { orcadArtifactFilenames, ORCAD_INSTALL_COMPLETE_FILENAME, ORCAD_RUNTIMES_DIRNAME, ORCAD_VERSION_FILENAME } from '../../../shared/orcad-artifacts' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' type RemoteInstallModelId = 'relay' | 'orcad' diff --git a/src/main/managed-server/install/remote-install-noisy-sftp-wire.test.ts b/src/main/managed-server/install/remote-install-noisy-sftp-wire.test.ts index 1fb4d0c43e6..d24a2b8906d 100644 --- a/src/main/managed-server/install/remote-install-noisy-sftp-wire.test.ts +++ b/src/main/managed-server/install/remote-install-noisy-sftp-wire.test.ts @@ -7,7 +7,7 @@ import type { SshTarget } from '../../../shared/ssh-types' import { spawnProcess } from '@orca/process-host' import { SshConnection } from '../../ssh/connection/ssh-connection' import { uploadRemoteInstallDirectory, writeRemoteInstallFile } from './remote-install-transfers' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' type NoisyHost = { port: number; subsystems: number; execs: number; close: () => Promise } diff --git a/src/main/managed-server/install/remote-install-out-of-space.ts b/src/main/managed-server/install/remote-install-out-of-space.ts index 7c9a73b2026..0fac7c5e863 100644 --- a/src/main/managed-server/install/remote-install-out-of-space.ts +++ b/src/main/managed-server/install/remote-install-out-of-space.ts @@ -6,7 +6,10 @@ import type { RemoteInstallTransport } from './remote-install-transport' import { dfAvailableKb, formatKb } from '../host-state/remote-filesystem-space' import { execHostCommand } from '../../ssh/remote-exec/remote-host-exec' import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' const DIAGNOSIS_TIMEOUT_MS = 15_000 diff --git a/src/main/managed-server/install/remote-install-root.ts b/src/main/managed-server/install/remote-install-root.ts new file mode 100644 index 00000000000..ee14fb690b9 --- /dev/null +++ b/src/main/managed-server/install/remote-install-root.ts @@ -0,0 +1 @@ +export const RELAY_REMOTE_DIR = '.orca-remote' diff --git a/src/main/managed-server/install/remote-install-transfers.ts b/src/main/managed-server/install/remote-install-transfers.ts index 40da2538fc2..3eca9725481 100644 --- a/src/main/managed-server/install/remote-install-transfers.ts +++ b/src/main/managed-server/install/remote-install-transfers.ts @@ -1,16 +1,19 @@ import type { RemoteInstallTransport } from './remote-install-transport' -import type { SftpNamespacePathMapping } from '../../ssh/sftp-namespace-resolution' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { SftpNamespacePathMapping } from '../../ssh/file-transfer/sftp/sftp-namespace-resolution' +import { + isWindowsRemoteHost, + type RemoteHostPlatform +} from '../../ssh/remote-host/ssh-remote-platform' import { uploadDirectoryViaExecStdin, writeStringViaExecStdin -} from '../../ssh/ssh-exec-stdin-file-transfer' +} from '../../ssh/file-transfer/ssh-exec-stdin-file-transfer' import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' import { describeSandboxedSftpFailure, isSandboxedSftpNamespaceError -} from '../../ssh/sftp-stream-late-error' -import { isSftpHandshakeCorruption } from '../../ssh/sftp-handshake-corruption' +} from '../../ssh/file-transfer/sftp/sftp-stream-late-error' +import { isSftpHandshakeCorruption } from '../../ssh/file-transfer/sftp/sftp-handshake-corruption' import { explainRemoteInstallWriteFailure, localTreeBytes } from './remote-install-out-of-space' type RemoteInstallTransferOptions = { diff --git a/src/main/managed-server/install/remote-install-transport.ts b/src/main/managed-server/install/remote-install-transport.ts index f3a6d0fec36..5dc3f0f9918 100644 --- a/src/main/managed-server/install/remote-install-transport.ts +++ b/src/main/managed-server/install/remote-install-transport.ts @@ -1,5 +1,5 @@ import type { Duplex, Readable, Writable } from 'node:stream' -import type { SshRemoteFileOptions } from '../../ssh/connection/ssh-connection-file-transfers' +import type { SshRemoteFileOptions } from '../../ssh/file-transfer/ssh-connection-file-transfers' import type { SshExecOptions } from '../../ssh/connection/ssh-exec-options' type RemoteFileWriteOptions = SshRemoteFileOptions & { signal?: AbortSignal } diff --git a/src/main/managed-server/install/remote-node-runtime-host-download.ts b/src/main/managed-server/install/remote-node-runtime-host-download.ts index 5c92ce084c6..0a9a56b5520 100644 --- a/src/main/managed-server/install/remote-node-runtime-host-download.ts +++ b/src/main/managed-server/install/remote-node-runtime-host-download.ts @@ -13,7 +13,7 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { configuredNodeDistMirror } from '../../node-runtime/node-dist-mirror-setting' import { DesktopDownloadUnreachableError } from '../../node-runtime/pinned-runtime-materializer' import { remoteSha256Command } from './remote-sha256-command' diff --git a/src/main/managed-server/install/remote-node-runtime-store-gc.test.ts b/src/main/managed-server/install/remote-node-runtime-store-gc.test.ts index 101b22aee43..ce88a0d8fb6 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-gc.test.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-gc.test.ts @@ -27,8 +27,8 @@ import { import { RUNTIME_STORE_LOCK_NAME } from './remote-node-runtime-store-lock' import { RUNTIME_REF_NODE_PREFIX } from './remote-node-runtime-store-inventory' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import { unusedSshConnection } from '../../ssh/unused-host-transport.test-fixture' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { unusedSshConnection } from '../testing/managed-host-transport.test-fixture' const conn = unusedSshConnection() const host = getRemoteHostPlatform('linux-x64') diff --git a/src/main/managed-server/install/remote-node-runtime-store-gc.ts b/src/main/managed-server/install/remote-node-runtime-store-gc.ts index ab1a7a37a6b..66ad8d60306 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-gc.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-gc.ts @@ -25,12 +25,12 @@ import { moveRemoteTreeCommand, removeRemoteTreeCommand, restoreRemoteTreeCommand -} from '../../ssh/ssh-remote-commands' +} from '../../ssh/remote-exec/ssh-remote-commands' import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' import { hostRuntimeStoreInventoryCommand, windowsSweepStaleRuntimeStagesCommand diff --git a/src/main/managed-server/install/remote-node-runtime-store-inventory.ts b/src/main/managed-server/install/remote-node-runtime-store-inventory.ts index 74c5fff3ed8..92443d151bc 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-inventory.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-inventory.ts @@ -4,8 +4,8 @@ import { ORCAD_RUNTIMES_DIRNAME } from '../../../shared/orcad-artifacts' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { RELAY_REMOTE_DIR } from './remote-install-root' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' /** Empty per-version reference files protect runtimes from GC. */ export const RUNTIME_REF_NODE_PREFIX = '.runtime-ref-node-' diff --git a/src/main/managed-server/install/remote-node-runtime-store-lock-host-release.test.ts b/src/main/managed-server/install/remote-node-runtime-store-lock-host-release.test.ts index 2d24708a9d9..c8aeb8405fe 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-lock-host-release.test.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-lock-host-release.test.ts @@ -11,8 +11,8 @@ import { } from './remote-node-runtime-store-lock' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { tryCreateInstallLockCommand } from './remote-install-lock-commands' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import { unusedSshConnection } from '../../ssh/unused-host-transport.test-fixture' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { unusedSshConnection } from '../testing/managed-host-transport.test-fixture' vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), diff --git a/src/main/managed-server/install/remote-node-runtime-store-lock.ts b/src/main/managed-server/install/remote-node-runtime-store-lock.ts index e5ba1bd9032..45cae8b25e1 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-lock.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-lock.ts @@ -11,13 +11,13 @@ import { tryStealInstallLockCommand, type InstallLockOwnerFile } from './remote-install-lock-commands' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' -import { removeRemoteTreeCommand } from '../../ssh/ssh-remote-commands' +import { RELAY_REMOTE_DIR } from './remote-install-root' +import { removeRemoteTreeCommand } from '../../ssh/remote-exec/ssh-remote-commands' import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' export const RUNTIME_STORE_LOCK_NAME = '.store-lock' // Owner tokens prevent late releases from deleting successor locks. diff --git a/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts b/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts index c51fb77d026..220042ea2ef 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { parseRuntimeStoreInventory } from './remote-node-runtime-store-inventory' import { windowsRuntimeStoreInventoryCommand } from './remote-node-runtime-store-windows' -import { decodeRemotePowerShellScript } from '../../ssh/ssh-remote-powershell' +import { decodeRemotePowerShellScript } from '../../ssh/remote-exec/ssh-remote-powershell' import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' const sha = (c: string): string => c.repeat(64) diff --git a/src/main/managed-server/install/remote-node-runtime-store-windows.ts b/src/main/managed-server/install/remote-node-runtime-store-windows.ts index fa14997b17d..fa42c73ab31 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-windows.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-windows.ts @@ -14,13 +14,13 @@ import { RUNTIME_STORE_TOMBSTONE_PREFIX, runtimeStoreInventoryCommand } from './remote-node-runtime-store-inventory' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import { RELAY_REMOTE_DIR } from './remote-install-root' import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' -import { powerShellCommand } from '../../ssh/ssh-remote-powershell' +} from '../../ssh/remote-host/ssh-remote-platform' +import { powerShellCommand } from '../../ssh/remote-exec/ssh-remote-powershell' import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' const REPARSE = '[IO.FileAttributes]::ReparsePoint' diff --git a/src/main/managed-server/install/remote-versioned-install.ts b/src/main/managed-server/install/remote-versioned-install.ts index b8e71a5e4be..420c09dd471 100644 --- a/src/main/managed-server/install/remote-versioned-install.ts +++ b/src/main/managed-server/install/remote-versioned-install.ts @@ -6,21 +6,21 @@ import type { RemoteInstallTransport } from './remote-install-transport' import { execHostCommand } from '../../ssh/remote-exec/remote-host-exec' import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' import { RELAY_INSTALL_LOCK_NAME } from '../../../shared/relay-install-lock-name' -import { RELAY_REMOTE_DIR } from '../../ssh/remote-exec/remote-frame-protocol' +import { RELAY_REMOTE_DIR } from './remote-install-root' import { remoteInstallDirName, type RemoteInstallModel } from './remote-install-model' +import { probeRemoteInstallCompleteCommand } from './remote-install-completeness-command' import { - probeRemoteInstallCompleteCommand, removeRemoteTreeCommand, writeRemoteEmptyFileCommand -} from '../../ssh/ssh-remote-commands' +} from '../../ssh/remote-exec/ssh-remote-commands' import { assertSafeRemotePathSegment, getRemoteHostPlatform, joinRemotePath, type RemoteHostPlatform, type RemotePathFlavor -} from '../../ssh/ssh-remote-platform' -import { isSshSessionLimitError } from '../../ssh/ssh-session-limit-error' +} from '../../ssh/remote-host/ssh-remote-platform' +import { isSshSessionLimitError } from '../../ssh/connection/ssh-session-limit-error' const INSTALL_COMPLETE_NAME = '.install-complete' const DEFAULT_REMOTE_HOST = getRemoteHostPlatform('linux-x64') diff --git a/src/main/ssh/orcad-already-active-wake.ts b/src/main/managed-server/lifecycle/orcad-already-active-wake.ts similarity index 72% rename from src/main/ssh/orcad-already-active-wake.ts rename to src/main/managed-server/lifecycle/orcad-already-active-wake.ts index 6f665bf5619..b0be0fcc83b 100644 --- a/src/main/ssh/orcad-already-active-wake.ts +++ b/src/main/managed-server/lifecycle/orcad-already-active-wake.ts @@ -1,9 +1,6 @@ -import { - OrcadCrashLoopError, - wakeManagedOrcadUnlessCrashLooping -} from '../managed-server/lifecycle/orcad-managed-crash-loop' -import { wakeStoppedManagedOrcad } from '../managed-server/lifecycle/orcad-managed-wake' -import type { OrcadSlotOptions } from './orcad-recovery-slot' +import { OrcadCrashLoopError, wakeManagedOrcadUnlessCrashLooping } from './orcad-managed-crash-loop' +import { wakeStoppedManagedOrcad } from './orcad-managed-wake' +import type { OrcadSlotOptions } from '../activation/orcad-recovery-slot' /** Already-active deploys launch nothing; wake that slot only on proven exit, including after reboot. Return whether it was started. */ export async function wakeAlreadyActiveOrcad( diff --git a/src/main/ssh/orcad-bash-stdio-bridge.test.ts b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts similarity index 62% rename from src/main/ssh/orcad-bash-stdio-bridge.test.ts rename to src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts index 51e5c681f1d..918193203a8 100644 --- a/src/main/ssh/orcad-bash-stdio-bridge.test.ts +++ b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts @@ -6,38 +6,25 @@ import { join } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' import type { PipedChildProcess as Bridge } from '@orca/process-host/process-spec' -import { OrcadStdioBridgeUnavailableError } from '../orcad/orcad-host-unavailable' +import { OrcadStdioBridgeUnavailableError } from '../../orcad/orcad-host-unavailable' import { checkOrcadStdioBridge, type OrcadStdioBridge } from './orcad-stdio-bridge' -import { - ORCAD_STDIO_BRIDGE_REFUSED, - orcadBashStdioBridgeCommand -} from '../managed-server/lifecycle/orcad-stdio-bridge-script' -import { OrcadStdioBridgeDecoder } from '../managed-server/lifecycle/orcad-stdio-bridge-stream' -import { - spawnLocalBridgeChannel, - startEchoServer -} from '../managed-server/lifecycle/orcad-stdio-bridge-test-channel' -import type { OrcadHostTransport } from './orcad-host-transport' +import { orcadBashStdioBridgeCommand } from './orcad-stdio-bridge-script' +import { OrcadStdioBridgeDecoder } from './orcad-stdio-bridge-stream' +import { spawnLocalBridgeChannel, startEchoServer } from './orcad-stdio-bridge-test-channel' +import type { OrcadHostTransport } from '../install/orcad-host-transport' import { bashSupportsRelay, guestHome, isAlive, pathWithoutBash, - processTree, - treeRssMb -} from './orcad-bash-stdio-bridge-test-host' + processTree +} from './testing/orcad-bash-stdio-bridge-test-host' const POSIX = process.platform !== 'win32' // macOS ships bash 3.2, which takes the Node fallback this suite checks separately. const RELAY = POSIX && bashSupportsRelay() // Every byte value, repeated into a multi-megabyte frame. const PAYLOAD = Buffer.from(Array.from({ length: 4 * 1024 * 1024 }, (_, index) => index % 256)) -// More than every pipe and socket buffer on the path can hold, so a stalled side must push back. -const FLOOD_CHUNK = Buffer.from(Array.from({ length: 1024 * 1024 }, (_, index) => index % 256)) -const FLOOD_BYTES = 128 * FLOOD_CHUNK.length -const STALL_MS = 1_000 -// A Node bridge holds ~45-50 MB; the relay is bash plus two cats. -const RELAY_RSS_CEILING_MB = 15 let echo: { server: Server; port: number } let scratch: string @@ -68,21 +55,6 @@ function exitOf(child: Bridge): Promise { return new Promise((resolve) => child.once('exit', (code) => resolve(code))) } -function firstLine(stream: NodeJS.ReadableStream): Promise { - let text = '' - return new Promise((resolve) => { - const onData = (chunk: Buffer): void => { - text += chunk.toString('latin1') - const end = text.indexOf('\n') - if (end !== -1) { - stream.off('data', onData) - resolve(text.slice(0, end)) - } - } - stream.on('data', onData) - }) -} - /** Decodes the bridge's stdout, discarding payload bytes; resolves `ready` on the sentinel. */ function decode(stream: NodeJS.ReadableStream) { const decoder = new OrcadStdioBridgeDecoder('raw') @@ -108,37 +80,6 @@ function received(decoder: OrcadStdioBridgeDecoder, expected: number): Promise number; done: Promise } { - let accepted = 0 - const done = (async () => { - while (accepted < FLOOD_BYTES) { - const more = stream.write(FLOOD_CHUNK) - accepted += FLOOD_CHUNK.length - if (!more) { - await new Promise((resolve) => stream.once('drain', resolve)) - } - } - })() - return { accepted: () => accepted, done } -} - -/** Counts flood bytes and checks each one against its position, without holding the flood. */ -function floodCheck() { - let count = 0 - let intact = true - return { - push: (chunk: Buffer): void => { - for (let index = 0; index < chunk.length; index += 1) { - intact &&= chunk[index] === (count + index) % 256 - } - count += chunk.length - }, - count: () => count, - intact: () => intact - } -} - async function listen(server: Server): Promise { await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) const address = server.address() @@ -167,73 +108,6 @@ function transportRunning(env: Partial): OrcadHostTransport { } describe.runIf(RELAY)('the bash stdio bridge', () => { - it('carries every byte value both ways in a multi-megabyte frame, without Node', async () => { - const child = spawnBridge(echo.port) - const { decoder, ready } = decode(child.stdout) - const bytes = received(decoder, PAYLOAD.length) - await ready - const pids = processTree(child.pid!) - child.stdin.write(PAYLOAD) - expect((await bytes).equals(PAYLOAD)).toBe(true) - if (process.platform === 'linux') { - expect(treeRssMb(pids)).toBeLessThan(RELAY_RSS_CEILING_MB) - } - const exited = exitOf(child) - child.stdin.end() - await expect(exited).resolves.toBe(0) - await expectNoSurvivors(pids) - }) - - it('holds the desktop back, without buffering, while the desktop reads slowly', async () => { - const child = spawnBridge(echo.port) - const { decoder, ready } = decode(child.stdout) - await ready - decoder.pause() - const writer = flood(child.stdin) - // ast-grep-ignore: test-no-real-time-wait -- backpressure is an absence of progress; only a bounded stall shows it - await new Promise((resolve) => setTimeout(resolve, STALL_MS)) - expect(writer.accepted()).toBeLessThan(FLOOD_BYTES) - if (process.platform === 'linux') { - expect(treeRssMb(processTree(child.pid!))).toBeLessThan(RELAY_RSS_CEILING_MB) - } - const check = floodCheck() - decoder.on('data', check.push) - decoder.resume() - await writer.done - await expect.poll(check.count, { timeout: 30_000 }).toBe(FLOOD_BYTES) - expect(check.intact()).toBe(true) - child.stdin.end() - await exitOf(child) - }) - - it('holds the desktop back while orcad reads slowly, then delivers everything', async () => { - let accepted: Socket | null = null - const check = floodCheck() - const server = createServer((socket) => { - accepted = socket - socket.pause() - socket.on('data', check.push) - }) - const port = await listen(server) - try { - const child = spawnBridge(port) - await decode(child.stdout).ready - const writer = flood(child.stdin) - await expect.poll(() => accepted).not.toBeNull() - // ast-grep-ignore: test-no-real-time-wait -- backpressure is an absence of progress; only a bounded stall shows it - await new Promise((resolve) => setTimeout(resolve, STALL_MS)) - expect(writer.accepted()).toBeLessThan(FLOOD_BYTES) - accepted!.resume() - await writer.done - await expect.poll(check.count, { timeout: 30_000 }).toBe(FLOOD_BYTES) - expect(check.intact()).toBe(true) - child.stdin.end() - await exitOf(child) - } finally { - server.close() - } - }) - it('exits 0 and leaves nothing running when orcad closes while the desktop holds stdin', async () => { let accepted: Socket | null = null const server = createServer((socket) => { @@ -348,16 +222,6 @@ describe.runIf(POSIX)('the bash stdio bridge’s Node fallback', () => { await exited }) - it('reports a refused dial with the unchanged refusal sentinel', async () => { - const closed = await startEchoServer() - closed.server.close() - const child = spawnBridge(closed.port, { HOME: guestHome(scratch, true) }) - await expect(firstLine(child.stdout)).resolves.toBe( - `${ORCAD_STDIO_BRIDGE_REFUSED} ECONNREFUSED` - ) - await expect(exitOf(child)).resolves.toBe(0) - }) - it('still proves the bridge runs when orcad refuses the dial', async () => { const closed = await startEchoServer() closed.server.close() diff --git a/src/main/managed-server/lifecycle/orcad-decommission-recovery.ts b/src/main/managed-server/lifecycle/orcad-decommission-recovery.ts index 4c619a91a2e..dd62d944af7 100644 --- a/src/main/managed-server/lifecycle/orcad-decommission-recovery.ts +++ b/src/main/managed-server/lifecycle/orcad-decommission-recovery.ts @@ -13,7 +13,7 @@ import { orcadSlotDir, resolveOrcadSlotIdentity, type OrcadSlotOptions -} from '../../ssh/orcad-recovery-slot' +} from '../activation/orcad-recovery-slot' /** Only proven exit clears an interrupted decommission journal. */ export async function reconcileOrcadDecommission( diff --git a/src/main/managed-server/lifecycle/orcad-decommission-stop.ts b/src/main/managed-server/lifecycle/orcad-decommission-stop.ts index c4478682521..9d7f88a397f 100644 --- a/src/main/managed-server/lifecycle/orcad-decommission-stop.ts +++ b/src/main/managed-server/lifecycle/orcad-decommission-stop.ts @@ -4,7 +4,7 @@ import { cancelRemoteOrcadManagedStop, completeRemoteOrcadManagedStop } from './orcad-managed-remote-stop' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import type { OrcadSlotOptions } from '../activation/orcad-recovery-slot' import type { OrcadDaemonRetirementVerdict, OrcadManagedStopRequest diff --git a/src/main/ssh/orcad-maintenance-pairing-refresh.ts b/src/main/managed-server/lifecycle/orcad-maintenance-pairing-refresh.ts similarity index 73% rename from src/main/ssh/orcad-maintenance-pairing-refresh.ts rename to src/main/managed-server/lifecycle/orcad-maintenance-pairing-refresh.ts index 2500a177e91..9a81e9141b5 100644 --- a/src/main/ssh/orcad-maintenance-pairing-refresh.ts +++ b/src/main/managed-server/lifecycle/orcad-maintenance-pairing-refresh.ts @@ -1,11 +1,11 @@ -import { refreshManagedOrcadPairing } from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { refreshManagedOrcadPairing } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { getOrcadSshDeployment, getPreferredPairingOffer, type KnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { ServeReadiness } from '../server/serve-readiness' +} from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { ServeReadiness } from '../../server/serve-readiness' import { tunneledOrcadPairingCode } from './orcad-tunneled-pairing' /** Saves the pairing a managed server published after an update, rollback or restart. */ diff --git a/src/main/managed-server/lifecycle/orcad-managed-auto-update.test.ts b/src/main/managed-server/lifecycle/orcad-managed-auto-update.test.ts index 2437c267c6a..3a7df50f535 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-auto-update.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-auto-update.test.ts @@ -14,12 +14,14 @@ const mocks = vi.hoisted(() => { } }) -vi.mock('../../ssh/orcad-runtime-maintenance', () => ({ +vi.mock('./orcad-managed-lifecycle', () => ({ withManagedOrcadLifecycle: ( _userData: string, _selector: string, run: (managed: unknown) => Promise - ) => run({ environment: { id: 'env-1' }, deployment: {} }), + ) => run({ environment: { id: 'env-1' }, deployment: {} }) +})) +vi.mock('./orcad-runtime-maintenance', () => ({ runManagedOrcadUpdate: mocks.runUpdate })) vi.mock('./orcad-managed-runtime-context', () => ({ diff --git a/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts b/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts index 6718a826c34..ecc3569effe 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts @@ -11,11 +11,9 @@ import { import { findIncompleteManagedOrcadMigration } from './orcad-managed-migration-status' import { ORCAD_ACTIVATION_FENCE_BUSY_CODE } from '../activation/orcad-activation-fence-hold' import { resolveLinkedOrcadContext } from './orcad-managed-runtime-context' -import { - runManagedOrcadUpdate, - withManagedOrcadLifecycle -} from '../../ssh/orcad-runtime-maintenance' -import type { OrcadUpdateDeferCode } from '../../ssh/orcad-update-plan' +import { runManagedOrcadUpdate } from './orcad-runtime-maintenance' +import { withManagedOrcadLifecycle } from './orcad-managed-lifecycle' +import type { OrcadUpdateDeferCode } from '../activation/orcad-update-plan' import { readLocalFullVersion } from '../install/remote-versioned-install' export type ManagedOrcadAutoUpdateOutcome = diff --git a/src/main/managed-server/lifecycle/orcad-managed-bound-port.ts b/src/main/managed-server/lifecycle/orcad-managed-bound-port.ts index 5964dd85ac2..e9b91ace4e0 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-bound-port.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-bound-port.ts @@ -15,7 +15,7 @@ import { execOrcadRemote, type OrcadRemoteExecTarget } from '../install/orcad-remote-runtime-control' -import type { OrcadHostTarget, OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTarget, OrcadHostTransport } from '../install/orcad-host-transport' import { parsePairingCode } from '../../../shared/remote-runtime/pairing/pairing' export type OrcadTunnelPortInput = { diff --git a/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts b/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts index 2e2383a925f..bb7b888516a 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts @@ -2,9 +2,12 @@ import { OrcadUnexpectedExitSchema } from '../../../shared/orcad-unexpected-exit' import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' import type { OrcadHealth } from '../../orcad/orcad-health' -import { isOrcadLaunchFailure, orcadLaunchFailureRanProcess } from '../../ssh/orcad-launch-failure' -import { orcadSlotDir, type OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' -import { isWindowsRemoteHost, joinRemotePath } from '../../ssh/ssh-remote-platform' +import { + isOrcadLaunchFailure, + orcadLaunchFailureRanProcess +} from '../activation/orcad-launch-failure' +import { orcadSlotDir, type OrcadSlotOptions } from '../activation/orcad-recovery-slot' +import { isWindowsRemoteHost, joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { execOrcadRemote } from '../install/orcad-remote-runtime-control' import { readOrcadActivationRecord } from '../activation/orcad-activation-record-store' import { ORCAD_LOG_FILENAME } from '../install/orcad-remote-host-support' diff --git a/src/main/managed-server/lifecycle/orcad-managed-launch-session.ts b/src/main/managed-server/lifecycle/orcad-managed-launch-session.ts index a06286b5878..91504113f53 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-launch-session.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-launch-session.ts @@ -10,8 +10,8 @@ import { parseOrcadLaunchSshSession, recordsOrcadLaunchSshSession, type OrcadLaunchSshSession -} from '../../ssh/orcad-launch-ssh-session' -import { withManagedOrcadLifecycle } from '../../ssh/orcad-runtime-maintenance' +} from '../install/orcad-launch-ssh-session' +import { withManagedOrcadLifecycle } from './orcad-managed-lifecycle' import { managedOrcadInstallDir, managedOrcadSlot, @@ -20,15 +20,15 @@ import { resolveLinkedOrcadContext } from './orcad-managed-runtime-context' import { resolveOrcadRemoteContext } from '../install/orcad-remote-context' -import { sshOrcadHostTransport } from '../../ssh/orcad-ssh-host-transport' + import { rebuildOrcadManagedTunnel } from './orcad-managed-tunnel' import { wakeStoppedManagedOrcad } from './orcad-managed-wake' import { readRemoteOrcadManagedStopTarget } from './orcad-managed-remote-stop' -import { orcadSlotDir, type OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import { orcadSlotDir, type OrcadSlotOptions } from '../activation/orcad-recovery-slot' import { stopIncumbentBehindTerminalBarrier } from './orcad-rollback-terminal-barrier' import { execOrcadRemote } from '../install/orcad-remote-runtime-control' -import { collectManagedTerminalCensus } from '../../ssh/orcad-terminal-census-client' -import { runFencedStop, updateTerminalCounts } from '../../ssh/orcad-fenced-stop' +import { collectManagedTerminalCensus } from './orcad-terminal-census-client' +import { runFencedStop, updateTerminalCounts } from '../activation/orcad-fenced-stop' export async function readManagedOrcadLaunchSshSession( userDataPath: string, @@ -45,7 +45,7 @@ export async function readManagedOrcadLaunchSshSession( if (!target || !connection) { return 'unverifiable' } - const context = await resolveOrcadRemoteContext(target, sshOrcadHostTransport(connection)) + const context = await resolveOrcadRemoteContext(target, connection) if (!recordsOrcadLaunchSshSession(context.host)) { return 'not-applicable' } diff --git a/src/main/managed-server/lifecycle/orcad-managed-lifecycle-test-fixture.ts b/src/main/managed-server/lifecycle/orcad-managed-lifecycle-test-fixture.ts index 4abde3d4b72..87f388bb652 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-lifecycle-test-fixture.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-lifecycle-test-fixture.ts @@ -6,9 +6,9 @@ import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mo import { addManagedOrcadEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' import type { SshTarget } from '../../../shared/ssh-types' import type { ServeReadiness } from '../../server/serve-readiness' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { SshTargetOrcadClaims } from '../../ssh/targets/ssh-target-orcad-claims' -import { emptyDependentStateStore } from '../../ssh/targets/ssh-target-orcad-dependents-fixture' +import { emptyDependentStateStore } from '../../ssh/targets/testing/ssh-target-orcad-dependents-fixture' export const MANAGED_VERSION = '0.2.0+abc' export const MANAGED_PREVIOUS_VERSION = '0.1.0+def' diff --git a/src/main/managed-server/lifecycle/orcad-managed-lifecycle.ts b/src/main/managed-server/lifecycle/orcad-managed-lifecycle.ts new file mode 100644 index 00000000000..4bca14b1b70 --- /dev/null +++ b/src/main/managed-server/lifecycle/orcad-managed-lifecycle.ts @@ -0,0 +1,33 @@ +import { assertRuntimeEnvironmentNotReconciling } from '../../../shared/remote-runtime/host-catalog/runtime-environment-reconciliation-record' +import { runTargetLifecycle } from '../../ipc/ssh/ssh-target-lifecycle-queue' +import { rebuildOrcadManagedTunnel } from './orcad-managed-tunnel' +import { requireManagedOrcadEnvironment } from './orcad-managed-runtime-context' + +export type LifecycleArgs = { selector: string; signal?: AbortSignal } + +export function withManagedOrcadLifecycle( + userDataPath: string, + selector: string, + run: (managed: ReturnType) => Promise +): Promise { + const { environment, deployment } = requireManagedOrcadEnvironment(userDataPath, selector) + return runTargetLifecycle(deployment.sshTargetId, async () => { + // Re-read in the lifecycle queue because reconciliation/stop may have won first. + const current = requireManagedOrcadEnvironment(userDataPath, environment.id) + assertRuntimeEnvironmentNotReconciling(current.environment) + return run(current) + }) +} + +/** Rebuild forwarding when a launched slot binds a different port. */ +export async function followLaunchedServerPort( + userDataPath: string, + environmentId: string +): Promise { + try { + await rebuildOrcadManagedTunnel(userDataPath, environmentId) + } catch (error) { + // Server already launched; if tunnel rebuild fails, the next connect can forward its bound port. + console.warn('[ssh] Could not forward to the relaunched managed Orca server:', error) + } +} diff --git a/src/main/managed-server/lifecycle/orcad-managed-migration-status.ts b/src/main/managed-server/lifecycle/orcad-managed-migration-status.ts index 79d0715a5f2..7a95c32e6d0 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-migration-status.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-migration-status.ts @@ -6,7 +6,7 @@ import { getOrcadSshDeployment, type KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { listOrcadMigrationSourceCutovers } from '../../ssh/orcad-migration-cutover-journal' +import { listOrcadMigrationSourceCutovers } from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' type OrcadManagedPendingMigration = { migrationId: string diff --git a/src/main/managed-server/lifecycle/orcad-managed-pairing-repair-restart.test.ts b/src/main/managed-server/lifecycle/orcad-managed-pairing-repair-restart.test.ts index 63f61faf0bf..51d30fd56c7 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-pairing-repair-restart.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-pairing-repair-restart.test.ts @@ -23,7 +23,7 @@ import { OrcadManagedIdentityError, verifyManagedOrcadTunnelIdentity } from './orcad-managed-tunnel-identity' -import { unusedOrcadHostTransport } from '../../ssh/unused-host-transport.test-fixture' +import { unusedOrcadHostTransport } from '../testing/managed-host-transport.test-fixture' vi.mock('../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { const facade = getWorktreeListingMocks() diff --git a/src/main/managed-server/lifecycle/orcad-managed-pairing-repair.ts b/src/main/managed-server/lifecycle/orcad-managed-pairing-repair.ts index e09bc88e41d..08bf410819a 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-pairing-repair.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-pairing-repair.ts @@ -11,8 +11,8 @@ import { type KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import type { ServeReadiness } from '../../server/serve-readiness' -import type { OrcadHostTarget, OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { tunneledOrcadPairingCode } from '../../ssh/orcad-tunneled-pairing' +import type { OrcadHostTarget, OrcadHostTransport } from '../install/orcad-host-transport' +import { tunneledOrcadPairingCode } from './orcad-tunneled-pairing' import { getSshConnectionManager, getSshTargetRegistryStore diff --git a/src/main/managed-server/lifecycle/orcad-managed-recovery.ts b/src/main/managed-server/lifecycle/orcad-managed-recovery.ts new file mode 100644 index 00000000000..86d8fe8a75f --- /dev/null +++ b/src/main/managed-server/lifecycle/orcad-managed-recovery.ts @@ -0,0 +1,40 @@ +import { redactRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { OrcadManagedRecoveryResult } from '../../../shared/orcad-managed-runtime' +import { recoverInterruptedOrcadActivation } from '../activation/orcad-activation-recovery' +import { managedOrcadSlot, resolveLinkedOrcadContext } from './orcad-managed-runtime-context' + +import { refreshMaintainedOrcadPairing } from './orcad-maintenance-pairing-refresh' +import type { LifecycleArgs } from './orcad-managed-lifecycle' +import { withManagedOrcadLifecycle, followLaunchedServerPort } from './orcad-managed-lifecycle' + +export function recoverManagedOrcadEnvironment( + userDataPath: string, + args: LifecycleArgs & { acceptChangedState?: boolean } +): Promise { + return withManagedOrcadLifecycle( + userDataPath, + args.selector, + async ({ environment, deployment }) => { + const context = await resolveLinkedOrcadContext(environment, deployment, args.signal) + const result = await recoverInterruptedOrcadActivation({ + ...managedOrcadSlot(context, deployment.remotePort, args.signal), + acceptChangedState: args.acceptChangedState === true + }) + if (result.outcome !== 'recovered') { + return result + } + const updated = result.readiness + ? refreshMaintainedOrcadPairing(userDataPath, environment.id, result.readiness) + : environment + if (result.activeVersion) { + await followLaunchedServerPort(userDataPath, environment.id) + } + return { + outcome: 'recovered', + resolution: result.resolution, + activeVersion: result.activeVersion, + environment: redactRuntimeEnvironment(updated) + } + } + ) +} diff --git a/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts b/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts index e9bbdd7d767..8a21c5cfc79 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts @@ -8,8 +8,8 @@ import { } from '../install/orcad-remote-readiness-wait' import { execOrcadRemote } from '../install/orcad-remote-runtime-control' import { readBoundedOrcadRemoteRecord } from '../install/orcad-remote-record-file' -import { orcadSlotDir, type OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' -import { isWindowsRemoteHost, joinRemotePath } from '../../ssh/ssh-remote-platform' +import { orcadSlotDir, type OrcadSlotOptions } from '../activation/orcad-recovery-slot' +import { isWindowsRemoteHost, joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' import { orcadWindowsNodeCommandLine, diff --git a/src/main/managed-server/lifecycle/orcad-managed-rollback.ts b/src/main/managed-server/lifecycle/orcad-managed-rollback.ts new file mode 100644 index 00000000000..09615a1ac26 --- /dev/null +++ b/src/main/managed-server/lifecycle/orcad-managed-rollback.ts @@ -0,0 +1,117 @@ +import { redactRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { OrcadManagedRollbackResult } from '../../../shared/orcad-managed-runtime' +import { probeActiveOrcadReadiness } from '../activation/orcad-active-readiness' +import { CURRENT_ORCAD_DAEMON_PROTOCOL } from '../activation/orcad-daemon-protocol-crossing' +import { + managedOrcadInstallDir, + managedOrcadSlot, + resolveLinkedOrcadContext +} from './orcad-managed-runtime-context' + +import { readRemoteOrcadBuildHash } from '../install/orcad-remote-build-hash' +import { rollbackOrcad } from '../install/orcad-remote-rollback' +import { collectManagedTerminalCensus } from './orcad-terminal-census-client' +import { updateTerminalCounts } from '../activation/orcad-fenced-stop' +import { findIncompleteManagedOrcadMigration } from './orcad-managed-migration-status' +import { latestOrcadMigrationInto } from '../../persistence/migrating-orcad-catalog/orcad-migration-rollback-mark' +import { refreshMaintainedOrcadPairing } from './orcad-maintenance-pairing-refresh' +import type { LifecycleArgs } from './orcad-managed-lifecycle' +import { withManagedOrcadLifecycle, followLaunchedServerPort } from './orcad-managed-lifecycle' + +export function rollbackManagedOrcadEnvironment( + userDataPath: string, + args: LifecycleArgs +): Promise { + return withManagedOrcadLifecycle( + userDataPath, + args.selector, + async ({ environment, deployment }) => { + const context = await resolveLinkedOrcadContext(environment, deployment, args.signal) + const record = context.activationRecord + const target = record.previous + if (!target) { + return { + outcome: 'refused', + code: 'orcad_rollback_no_target', + reason: 'This server has no previous version to roll back to.' + } + } + const crossing = migrationRollbackRefusal(userDataPath, environment, record.activatedAt) + if (crossing) { + return crossing + } + const slot = managedOrcadSlot(context, deployment.remotePort, args.signal) + const targetDir = managedOrcadInstallDir(context, target) + const targetBuildHash = await readRemoteOrcadBuildHash(slot, targetDir) + const { countFirst, ...recount } = updateTerminalCounts((options) => + collectManagedTerminalCensus(userDataPath, environment, record, undefined, options) + ) + // Recount under lock before rollback stop; this initial census closes no admission. + const census = await countFirst() + // Require idle because this client cannot prove the older build's daemon protocol attaches to live terminals. + if (census.liveSessions !== 0) { + return { + outcome: 'refused', + code: + census.liveSessions === null + ? 'orcad_rollback_census_unavailable' + : 'orcad_rollback_terminals_running', + reason: + census.liveSessions === null + ? 'The server did not answer how many terminals it runs. Retry when it answers.' + : 'Close the terminals running on this server before rolling it back.' + } + } + const result = await rollbackOrcad({ + ...slot, + record, + census, + ...recount, + targetBuildHash, + targetDaemonProtocol: CURRENT_ORCAD_DAEMON_PROTOCOL + }) + if (result.outcome !== 'rolled-back') { + return result + } + const readiness = await probeActiveOrcadReadiness( + { ...slot, remoteInstallDir: targetDir }, + { buildHash: targetBuildHash, fullVersion: result.target } + ) + const updated = refreshMaintainedOrcadPairing(userDataPath, environment.id, readiness) + await followLaunchedServerPort(userDataPath, environment.id) + return { + outcome: 'rolled-back', + environment: redactRuntimeEnvironment(updated), + activeVersion: result.target, + discarded: result.discarded + } + } + ) +} + +/** A post-activation migration is absent from the rollback snapshot; restoring it would discard imported state. */ +function migrationRollbackRefusal( + userDataPath: string, + environment: KnownRuntimeEnvironment, + activatedAt: string | null +): OrcadManagedRollbackResult | null { + if (findIncompleteManagedOrcadMigration(userDataPath, environment.id)) { + return { + outcome: 'refused', + code: 'orcad_rollback_migration_in_progress', + reason: 'A migration into this server is still running. Finish it before rolling back.' + } + } + const migratedAt = latestOrcadMigrationInto(userDataPath, environment) + if (migratedAt && (activatedAt === null || Date.parse(activatedAt) < Date.parse(migratedAt))) { + return { + outcome: 'refused', + code: 'orcad_rollback_crosses_migration', + reason: + "The previous version's state predates the projects migrated onto this server; " + + 'rolling back would lose them. Deploy forward instead.' + } + } + return null +} diff --git a/src/main/managed-server/lifecycle/orcad-managed-runtime-context.ts b/src/main/managed-server/lifecycle/orcad-managed-runtime-context.ts index 1bedd767421..4225ad1c3a8 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-runtime-context.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-runtime-context.ts @@ -7,16 +7,16 @@ import { } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' import type { ServeReadiness } from '../../server/serve-readiness' -import { computeLocalOrcadBuildHash } from '../../ssh/orcad-local-build-hash' -import { sshOrcadHostTransport } from '../../ssh/orcad-ssh-host-transport' -import type { OrcadHostTarget } from '../../ssh/orcad-host-transport' +import { computeLocalOrcadBuildHash } from '../install/orcad-local-build-hash' + +import type { OrcadHostTarget } from '../install/orcad-host-transport' import type { OrcadActivationRecord } from '../activation/orcad-activation-record' import { admitOrcadRecordForIntent, type OrcadUpdateIntent } from './orcad-managed-update-decision' import { type OrcadTerminalCensus, UNVERIFIABLE_ORCAD_TERMINAL_CENSUS } from '../../../shared/orcad-terminal-census' -import { probeActiveOrcadReadiness } from '../../ssh/orcad-active-readiness' +import { probeActiveOrcadReadiness } from '../activation/orcad-active-readiness' import { resolveOrcadRemoteContext, type OrcadRemoteContext } from '../install/orcad-remote-context' import { ORCAD_INSTALL_MODEL } from '../install/remote-install-model' import { computeRemoteInstallDir } from '../install/remote-versioned-install' @@ -74,7 +74,7 @@ export async function resolveLinkedOrcadContext( throw new Error('The SSH registration for this host’s Orca server is no longer valid.') } const connection = await connectionManager.connect(target) - return resolveOrcadRemoteContext(target, sshOrcadHostTransport(connection), signal) + return resolveOrcadRemoteContext(target, connection, signal) } export function managedOrcadSlot( diff --git a/src/main/managed-server/lifecycle/orcad-managed-serving.ts b/src/main/managed-server/lifecycle/orcad-managed-serving.ts index a27a222d693..e4fc2d9c6ca 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-serving.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-serving.ts @@ -4,7 +4,7 @@ import type { SshTarget } from '../../../shared/ssh-types' import { orcadBoundPort } from './orcad-managed-bound-port' import { managedOrcadSlot } from './orcad-managed-runtime-context' import { resolveOrcadRemoteContext } from '../install/orcad-remote-context' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../install/orcad-host-transport' import { getManagedOrcadCrashLoopBrake, wakeManagedOrcadUnlessCrashLooping diff --git a/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts b/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts index 8d367c5ebdb..1df1f92a431 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts @@ -16,15 +16,12 @@ import { } from '../../../shared/orcad-artifacts' import { withOrcadActivationLock } from '../activation/orcad-activation-lock' import { readOrcadActivationRecord } from '../activation/orcad-activation-record-store' -import { - followLaunchedServerPort, - withManagedOrcadLifecycle -} from '../../ssh/orcad-runtime-maintenance' +import { followLaunchedServerPort, withManagedOrcadLifecycle } from './orcad-managed-lifecycle' import { managedOrcadSlot, resolveLinkedOrcadContext } from './orcad-managed-runtime-context' import { selectOrcadSlotRuntimeCommand } from '../install/orcad-remote-runtime' import { execOrcadRemote } from '../install/orcad-remote-runtime-control' -import { orcadSlotDir, type OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' -import { joinRemotePath } from '../../ssh/ssh-remote-platform' +import { orcadSlotDir, type OrcadSlotOptions } from '../activation/orcad-recovery-slot' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { isSshCommandExitError } from '../../ssh/remote-exec/remote-exec-command' import { wakeStoppedManagedOrcad } from './orcad-managed-wake' import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-close-target.test.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-close-target.test.ts index 6a542184a33..6e5efada4e8 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-close-target.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-close-target.test.ts @@ -8,7 +8,7 @@ import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mo import type { SshTarget } from '../../../shared/ssh-types' import type { SshConnection } from '../../ssh/connection/ssh-connection' import type { SshConnectionManager } from '../../ssh/connection/ssh-connection-manager' -import type { SshConnectionStore } from '../../ssh/connection/ssh-connection-store' +import type { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' import { SshPortForwardManager } from '../../ssh/port-forwarding/ssh-port-forward' import type { PortForwardStartOptions, diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-identity.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-identity.ts index 144ee7dcc93..80c6c6c0645 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-identity.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-identity.ts @@ -17,7 +17,7 @@ import { import { verifyRuntimePairingIdentity } from '../../runtime/hosts/identity/runtime-environment-identity-verification' import type { ServeReadiness } from '../../server/serve-readiness' import { orcadBoundPort } from './orcad-managed-bound-port' -import { tunneledOrcadPairingCode } from '../../ssh/orcad-tunneled-pairing' +import { tunneledOrcadPairingCode } from './orcad-tunneled-pairing' import { OrcadManagedPairingRepairFailedError } from './orcad-managed-pairing-repair-failure' import { quotePosixShellUnlessPlain } from '../../../shared/shell/launch/shell-argument-quoting' import { RUNTIME_SERVER_REPLACED_STATUS_CODE } from '../../../shared/remote-runtime/host-status/runtime-host-status' diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.test.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.test.ts index 8e42f01bd52..2dccebeb05c 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.test.ts @@ -10,9 +10,9 @@ import { getRuntimeSshAccess } from '../../../shared/remote-runtime/host-catalog import type { SshTarget } from '../../../shared/ssh-types' import type { SshConnection } from '../../ssh/connection/ssh-connection' import type { SshConnectionManager } from '../../ssh/connection/ssh-connection-manager' -import type { SshConnectionStore } from '../../ssh/connection/ssh-connection-store' +import type { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' import type { SshPortForwardManager } from '../../ssh/port-forwarding/ssh-port-forward' -import { reserveLocalForwardPort } from '../../ssh/system-transport/system-ssh-forward-port-reservation' +import { reserveLocalForwardPort } from '../../ssh/system-transport/forwarding/system-ssh-forward-port-reservation' import { OrcadManagedTunnelManager } from './orcad-managed-tunnel-manager' import { buildOnBindableLocalPort } from './orcad-managed-tunnel-local-port' import { setManagedOrcadPairingRepairedListener } from './orcad-managed-pairing-repaired-listener' diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.ts index e82d28686d2..caabf87665e 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.ts @@ -2,7 +2,7 @@ import { moveManagedOrcadLocalPort } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' import { getOrcadSshDeployment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { reserveLocalForwardPort } from '../../ssh/system-transport/system-ssh-forward-port-reservation' +import { reserveLocalForwardPort } from '../../ssh/system-transport/forwarding/system-ssh-forward-port-reservation' import { notifyManagedOrcadPairingRepaired } from './orcad-managed-pairing-repaired-listener' // Reservation reports the bind error code as `cause`; Windows excluded ranges answer EACCES. diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-manager.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-manager.ts index d5e88fb7661..0f3664283c8 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-manager.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-manager.ts @@ -4,7 +4,7 @@ import { } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import type { SshTarget } from '../../../shared/ssh-types' import type { SshConnection } from '../../ssh/connection/ssh-connection' -import { isAuthError } from '../../ssh/ssh-reconnect-error-classification' +import { isAuthError } from '../../ssh/connection/reconnect/ssh-reconnect-error-classification' import type { SshConnectionManager } from '../../ssh/connection/ssh-connection-manager' import { SshPortForwardManager } from '../../ssh/port-forwarding/ssh-port-forward' import { OrcadManagedTunnelTransportProvider } from './orcad-managed-tunnel-transport' diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-peer-restart.test.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-peer-restart.test.ts index 284fa40c133..6996c167732 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-peer-restart.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-peer-restart.test.ts @@ -8,7 +8,7 @@ import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mo import type { SshTarget } from '../../../shared/ssh-types' import type { SshConnection } from '../../ssh/connection/ssh-connection' import type { SshConnectionManager } from '../../ssh/connection/ssh-connection-manager' -import type { SshConnectionStore } from '../../ssh/connection/ssh-connection-store' +import type { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' import { SshPortForwardManager } from '../../ssh/port-forwarding/ssh-port-forward' import type { PortForwardStartOptions, diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts index bd6a9a28c8a..48a608b6f4b 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import type { SshConnection } from '../../ssh/connection/ssh-connection' import type { SshExecOptions } from '../../ssh/connection/ssh-exec-options' -import { knownOrcadTunnelTransport } from '../../ssh/orcad-tunnel-transport-memo' +import { knownOrcadTunnelTransport } from './orcad-tunnel-transport-memo' import type { PortForwardStartOptions } from '../../ssh/port-forwarding/ssh-port-forward-provider' import { spawnSystemSshCommand } from '../../ssh/system-transport/system-ssh-command' import { @@ -15,7 +15,7 @@ import { freePort, startRealOpenSshFixture, type RealOpenSshFixture -} from '../../ssh/system-transport/real-openssh-sshd-fixture' +} from '../../ssh/system-transport/testing/real-openssh-sshd-fixture' import { OrcadManagedTunnelTransportProvider } from './orcad-managed-tunnel-transport' const GREETING = 'orcad-fixture' diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.test.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.test.ts index 27aeb7fa4c3..c3dc5dd59da 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.test.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it, vi } from 'vitest' import type { SshConnection } from '../../ssh/connection/ssh-connection' -import { knownOrcadTunnelTransport } from '../../ssh/orcad-tunnel-transport-memo' +import { knownOrcadTunnelTransport } from './orcad-tunnel-transport-memo' import type { PortForwardStartOptions, SshPortForwardProvider, StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' -import type { ForwardChannelVerdict } from '../../ssh/ssh-tcp-forwarding-probe' +import type { ForwardChannelVerdict } from '../../ssh/port-forwarding/ssh-tcp-forwarding-probe' import { OrcadManagedTunnelTransportProvider } from './orcad-managed-tunnel-transport' // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the transport reads only the connect generation here. diff --git a/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.ts b/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.ts index 035d03ead89..d11f3cdb58f 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-tunnel-transport.ts @@ -1,6 +1,6 @@ // Fall back to the exec bridge when sshd refuses forwarding or standalone forward login fails. import { OrcadStdioBridgePortForwardProvider } from './orcad-stdio-bridge-provider' -import { rememberOrcadTunnelTransport } from '../../ssh/orcad-tunnel-transport-memo' +import { rememberOrcadTunnelTransport } from './orcad-tunnel-transport-memo' import type { SshConnection } from '../../ssh/connection/ssh-connection' import type { PortForwardStartOptions, @@ -12,15 +12,15 @@ import { probeTcpForwarding, type ForwardChannelVerdict, type TcpForwardingVerdict -} from '../../ssh/ssh-tcp-forwarding-probe' +} from '../../ssh/port-forwarding/ssh-tcp-forwarding-probe' import { Ssh2PortForwardProvider } from '../../ssh/port-forwarding/ssh2-port-forward-provider' import { SystemSshPortForwardProvider, systemSshForwardBuildArgsOptions } from '../../ssh/port-forwarding/system-ssh-port-forward-provider' -import { buildSystemSshPortForwardArgs } from '../../ssh/system-transport/system-ssh-forward-process' -import { reserveLocalForwardPort } from '../../ssh/system-transport/system-ssh-forward-port-reservation' -import { cancelMuxedLocalForward } from '../../ssh/system-transport/system-ssh-muxed-forward-cancel' +import { buildSystemSshPortForwardArgs } from '../../ssh/system-transport/forwarding/system-ssh-forward-process' +import { reserveLocalForwardPort } from '../../ssh/system-transport/forwarding/system-ssh-forward-port-reservation' +import { cancelMuxedLocalForward } from '../../ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel' type OrcadManagedTunnelTransportDependencies = { forwards: SshPortForwardProvider[] diff --git a/src/main/managed-server/lifecycle/orcad-managed-update-decision.ts b/src/main/managed-server/lifecycle/orcad-managed-update-decision.ts index e6c2643dc32..4ca74175829 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-update-decision.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-update-decision.ts @@ -3,7 +3,7 @@ import type { OrcadActivationRecord } from '../activation/orcad-activation-recor import { refuseOrcadHostDowngrade, type OrcadHostVersionRefusal -} from '../../ssh/orcad-host-version-admission' +} from '../activation/orcad-host-version-admission' export type ManagedOrcadAutoUpdateSkip = | 'current' diff --git a/src/main/managed-server/lifecycle/orcad-managed-update-on-restore.ts b/src/main/managed-server/lifecycle/orcad-managed-update-on-restore.ts index 8920ed9138e..b1591a91beb 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-update-on-restore.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-update-on-restore.ts @@ -3,7 +3,7 @@ import type { SshManagedServerUpdateNote, SshTarget } from '../../../shared/ssh- import { checkManagedServerUpdate, type ManagedServerUpdateDeps -} from '../../ssh/managed-server-update-check' +} from '../../ssh/host-server/managed-server-update-check' export type ManagedOrcadRestoreUpdateDeps = ManagedServerUpdateDeps & { target: (environmentId: string) => SshTarget | null diff --git a/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts b/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts index 1dc10f2b8dd..c1d75a10777 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-version-gc.ts @@ -5,10 +5,10 @@ import { orcadSlotDir, resolveOrcadSlotIdentity, type OrcadSlotOptions -} from '../../ssh/orcad-recovery-slot' -import { probeActiveOrcadReadiness } from '../../ssh/orcad-active-readiness' +} from '../activation/orcad-recovery-slot' +import { probeActiveOrcadReadiness } from '../activation/orcad-active-readiness' import { gcOldOrcadVersions } from '../install/orcad-remote-gc' -import { nodeRuntimeStorePins } from '../../ssh/pinned-runtime-host-target' +import { nodeRuntimeStorePins } from '../install/pinned-runtime-host-target' /** null proves no daemon; undefined means its version is unknown. */ export function provenLiveDaemonVersion(readiness: ServeReadiness): string | null | undefined { diff --git a/src/main/managed-server/lifecycle/orcad-managed-wake.ts b/src/main/managed-server/lifecycle/orcad-managed-wake.ts index e256931bc2d..c367fcf8e80 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-wake.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-wake.ts @@ -11,7 +11,7 @@ import { import { orcadLivenessProvenExited } from '../install/orcad-remote-launch' import { readBoundedOrcadRemoteRecord } from '../install/orcad-remote-record-file' import { orcadActivationFenceLockDir } from '../activation/orcad-activation-transaction' -import { joinRemotePath } from '../../ssh/ssh-remote-platform' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { readOrcadActivationTransaction } from '../activation/orcad-activation-transaction-store' import { @@ -24,7 +24,7 @@ import { resolveOrcadSlotIdentity, slotLiveness, type OrcadSlotOptions -} from '../../ssh/orcad-recovery-slot' +} from '../activation/orcad-recovery-slot' type OrcadManagedWake = | { outcome: 'serving' | 'not-activated' | 'unverifiable' } diff --git a/src/main/managed-server/lifecycle/orcad-rollback-safety.ts b/src/main/managed-server/lifecycle/orcad-rollback-safety.ts new file mode 100644 index 00000000000..9bc01d710b7 --- /dev/null +++ b/src/main/managed-server/lifecycle/orcad-rollback-safety.ts @@ -0,0 +1,129 @@ +import type { OrcadActivationRecord } from '../activation/orcad-activation-record' +import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' +import { + assessOrcadLiveDaemonCrossing, + describeDaemonProtocols +} from '../activation/orcad-daemon-protocol-crossing' + +import type { OrcadDaemonProtocolFacts } from '../activation/orcad-daemon-protocol-crossing' + +type OrcadRollbackSafety = + | { safety: 'clean'; target: string; notes: string[] } + | { safety: 'lossy'; target: string; discards: string[] } + | { safety: 'unsafe'; code: OrcadRollbackUnsafeCode; reason: string } + +type OrcadRollbackUnsafeCode = + | 'orcad_rollback_no_target' + | 'orcad_rollback_snapshot_missing' + | 'orcad_rollback_orphans_live_terminals' + | 'orcad_rollback_census_unavailable' + | 'orcad_rollback_snapshot_unverifiable' + | 'orcad_rollback_strands_live_terminals' + | 'orcad_rollback_daemon_protocol_unverifiable' + +/** Restoring a pre-activation snapshot discards later state. Post-activation terminal creation makes rollback unsafe: the surviving daemon would own PTYs absent from restored rows. Settings/UI-only changes are merely lossy. */ +export function assessOrcadRollback(input: { + record: OrcadActivationRecord + /** Whether the snapshot is still on the host; `null` means the probe was unverifiable. */ + snapshotPresent: boolean | null + census: OrcadTerminalCensus + /** The rollback target's daemon protocol facts, from the client's copy of its bytes. */ + targetDaemonProtocol: OrcadDaemonProtocolFacts + /** Compare shared-store mtime to activation; unknown writes are treated as present rather than claiming unproven lossless rollback. */ + stateWritesSinceActivation: boolean | null +}): OrcadRollbackSafety { + const target = input.record.previous + if (!target) { + return { + safety: 'unsafe', + code: 'orcad_rollback_no_target', + reason: + 'This host has no previous orcad version recorded, so there is nothing to roll back ' + + 'to. Deploy a known-good build instead.' + } + } + if (input.record.snapshot && input.snapshotPresent === null) { + return { + safety: 'unsafe', + code: 'orcad_rollback_snapshot_unverifiable', + reason: + 'The host did not give a trustworthy answer about the pre-activation snapshot. Retry ' + + 'when the host is reachable; loss of contact is not evidence the snapshot is gone.' + } + } + if (!input.record.snapshot || !input.snapshotPresent) { + return { + safety: 'unsafe', + code: 'orcad_rollback_snapshot_missing', + reason: + `The pre-activation state snapshot for ${input.record.active ?? 'the active version'} ` + + 'is gone, and Orca state carries no schema version that could prove the older build ' + + 'can read what the newer one migrated. Switching the binary back would hand ' + + `${target} a store it may not understand. Deploy forward instead.` + } + } + const { startedSinceActivation } = input.census + if (startedSinceActivation === null) { + return { + safety: 'unsafe', + code: 'orcad_rollback_census_unavailable', + reason: + 'The daemon did not answer how many of its terminals started after this version was ' + + 'activated, so a snapshot restore might orphan running work. Retry when the host is ' + + 'reachable.' + } + } + if (startedSinceActivation > 0) { + return { + safety: 'unsafe', + code: 'orcad_rollback_orphans_live_terminals', + reason: + `${startedSinceActivation} terminal${startedSinceActivation === 1 ? '' : 's'} started ` + + 'after this version was activated. The daemon survives the rollback and would keep ' + + 'owning them, but the restored snapshot predates them, so nothing would be able to ' + + 'reattach. Close them (or let them exit) and roll back then.' + } + } + const crossing = assessOrcadLiveDaemonCrossing(input.census, input.targetDaemonProtocol) + if (crossing.state === 'unverifiable') { + return { + safety: 'unsafe', + code: 'orcad_rollback_daemon_protocol_unverifiable', + reason: + 'The terminal daemon did not report its protocol, so this rollback cannot show that ' + + `${target} would reach the terminals still running. Retry when the daemon answers.` + } + } + if (crossing.state === 'strands-live-terminals') { + return { + safety: 'unsafe', + code: 'orcad_rollback_strands_live_terminals', + reason: + `A terminal daemon on this host speaks ${describeDaemonProtocols(crossing.unattachable)}, ` + + `which ${target} does not list. Rolling back now would leave any terminals it runs ` + + 'unreachable. Roll back when no terminals are running, or deploy forward.' + } + } + if (input.stateWritesSinceActivation === false) { + return { + safety: 'clean', + target, + notes: [ + 'The pre-activation snapshot is intact, no terminals started since activation, and ' + + 'the store has not been written since. Restoring it changes nothing.' + ] + } + } + return { + safety: 'lossy', + target, + discards: [ + input.stateWritesSinceActivation === null + ? 'Any profile, settings and UI change written since activation — the store mtime ' + + 'could not be read, so assume there are some.' + : `Every profile, settings and UI change written since ${ + input.record.activatedAt ?? 'activation' + }, when ${input.record.active ?? 'the active version'} was activated.` + ] + } +} diff --git a/src/main/managed-server/lifecycle/orcad-rollback-terminal-barrier.ts b/src/main/managed-server/lifecycle/orcad-rollback-terminal-barrier.ts index af9ccbb031f..dc099a19d85 100644 --- a/src/main/managed-server/lifecycle/orcad-rollback-terminal-barrier.ts +++ b/src/main/managed-server/lifecycle/orcad-rollback-terminal-barrier.ts @@ -4,7 +4,7 @@ import { type OrcadManagedStopTarget } from './orcad-managed-remote-stop' import { settleOrcadDecommissionStop } from './orcad-decommission-stop' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import type { OrcadSlotOptions } from '../activation/orcad-recovery-slot' import type { OrcadManagedStopContext } from '../../../shared/orcad-stop-request' type OrcadRollbackBarrier = diff --git a/src/main/managed-server/lifecycle/orcad-rollback-transition.ts b/src/main/managed-server/lifecycle/orcad-rollback-transition.ts index e9a294a66ee..00d0e9b3498 100644 --- a/src/main/managed-server/lifecycle/orcad-rollback-transition.ts +++ b/src/main/managed-server/lifecycle/orcad-rollback-transition.ts @@ -4,8 +4,8 @@ import type { OrcadRollbackOptions, OrcadRollbackResult } from '../install/orcad import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' import { withRolledBackVersion } from '../activation/orcad-activation-record' import { writeOrcadActivationRecord } from '../activation/orcad-activation-record-store' -import { launchAndJudgeOrcadSlot } from '../../ssh/orcad-candidate-launch-verdict' -import { assessOrcadRollback } from '../../ssh/orcad-update-plan' +import { launchAndJudgeOrcadSlot } from '../activation/orcad-candidate-launch-verdict' +import { assessOrcadRollback } from './orcad-rollback-safety' import { ORCAD_LOG_FILENAME } from '../install/orcad-remote-host-support' import { captureOrcadStateSnapshotCommand, @@ -20,7 +20,7 @@ import { newestStateMtimeCommand, parseNewestStateMtimeSeconds } from '../host-state/orcad-state-newest-mtime' -import { joinRemotePath } from '../../ssh/ssh-remote-platform' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import type { OrcadActivationLockControl } from '../activation/orcad-activation-lock' import { rollbackStartingState, @@ -33,19 +33,19 @@ import { } from '../activation/orcad-activation-transaction-transitions' import { writeOrcadActivationTransaction } from '../activation/orcad-activation-transaction-store' import { ROLLBACK_STALE_COUNT, rollbackRecountRefusal } from './orcad-rollback-admission' -import { runFencedStop } from '../../ssh/orcad-fenced-stop' +import { runFencedStop } from '../activation/orcad-fenced-stop' import { execOrcadRemoteOr, withoutAbortSignal } from '../install/orcad-remote-runtime-control' import { execOrcadStateMutationOr } from '../host-state/orcad-state-mutation-exec' import { orcadSlotDir, resolveOrcadSlotIdentity, type OrcadSlotIdentity -} from '../../ssh/orcad-recovery-slot' -import { orcadSnapshotPath } from '../../ssh/orcad-incumbent-recovery' +} from '../activation/orcad-recovery-slot' +import { orcadSnapshotPath } from '../activation/orcad-incumbent-recovery' import { putTransactionIncumbentBack, restoreAfterRejectedCandidate -} from '../../ssh/orcad-transaction-incumbent' +} from '../activation/orcad-transaction-incumbent' import { readOrcadRollbackBarrierTarget, rollbackBarrierRefusal, diff --git a/src/main/managed-server/lifecycle/orcad-runtime-conversion-wiring.ts b/src/main/managed-server/lifecycle/orcad-runtime-conversion-wiring.ts index 681419fa3e4..2d507361fb4 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-conversion-wiring.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-conversion-wiring.ts @@ -4,30 +4,32 @@ import { type KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { disconnectRegisteredSshTarget } from '../../ipc/ssh/ssh-session-teardown' -import type { OrcadMigrationDestinationCatalog } from '../../ssh/orcad-migration-cutover-coordinator' +import type { OrcadMigrationDestinationCatalog } from '../migration/cutover/orcad-migration-cutover-coordinator' import { abortRemoteOrcadMigrationCatalog, commitRemoteOrcadMigrationCatalog, - listRemoteOrcadRepositories, readRemoteOrcadMigrationCatalogState, + stageRemoteOrcadMigrationCatalog +} from '../migration/catalog/orcad-migration-catalog-client' +import { listRemoteOrcadRepositories } from '../migration/linking/orcad-server-repositories' +import { stageRemoteOrcadMigrationBlobChunk, - stageRemoteOrcadMigrationCatalog, stageRemoteOrcadMigrationSnapshotChunk -} from '../../ssh/orcad-migration-catalog-client' -import { readRemoteOrcadMigrationCapabilities } from '../../ssh/orcad-migration-capabilities-client' -import { abortRemoteOrcadMigrationCatalogByReference } from '../../ssh/orcad-migration-catalog-reference-client' +} from '../migration/transfers/orcad-migration-chunk-client' +import { readRemoteOrcadMigrationCapabilities } from '../migration/catalog/orcad-migration-capabilities-client' +import { abortRemoteOrcadMigrationCatalogByReference } from '../migration/catalog/orcad-migration-catalog-reference-client' import { enableRemoteOrcadAutomation, type EnableServerAutomation -} from '../../ssh/orcad-migration-moved-automations' -import { censusHostRelayTerminalsFor } from '../../ssh/legacy-relay/ssh-host-relay-census-for-target' -import { isBridgeableLease } from '../../ssh/legacy-relay/legacy-relay-bridge-leases' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-moved-automations' +import { censusHostRelayTerminalsFor } from '../../ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target' +import { isBridgeableLease } from '../../ssh/legacy-relay/bridge/legacy-relay-bridge-leases' import type { OrcadManagedConversionArgs } from './orcad-runtime-conversion' -import type { OrcadServerRepository } from '../../ssh/orcad-migration-repository-link' +import type { OrcadServerRepository } from '../migration/linking/orcad-server-repositories' import { listRemoteOrcadFolderCatalog, type OrcadServerFolderCatalog -} from '../../ssh/orcad-server-folder-workspaces' +} from '../migration/linking/orcad-server-folder-workspaces' export function orcadMigrationDestinationFor( environment: KnownRuntimeEnvironment diff --git a/src/main/managed-server/lifecycle/orcad-runtime-conversion.ts b/src/main/managed-server/lifecycle/orcad-runtime-conversion.ts index f72e21a9863..881853a5fdd 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-conversion.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-conversion.ts @@ -17,33 +17,33 @@ import { ensureOrcadManagedTunnel } from './orcad-managed-tunnel' import { commitOrcadMigrationDestination, type OrcadMigrationDestinationCatalog -} from '../../ssh/orcad-migration-cutover-coordinator' +} from '../migration/cutover/orcad-migration-cutover-coordinator' import { findOrcadMigrationSourceCutoverForTarget, removeOrcadMigrationJournalsForDestination -} from '../../ssh/orcad-migration-cutover-journal' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import type { SshTarget } from '../../../shared/ssh-types' -import type { CensusHostRelayTerminals } from '../../ssh/orcad-migration-terminal-gate' +import type { CensusHostRelayTerminals } from '../../ssh/migration-source/orcad-migration-terminal-gate' import { createManagedOrcadEnvironment } from './orcad-runtime-deployment' -import { createSshRelayMigrationSource } from '../../ssh/orcad-migration-ssh-relay-source' +import { createSshRelayMigrationSource } from '../../ssh/migration-source/orcad-migration-ssh-relay-source' import { leaveBehindClearsOrcadMigrationBlockers, onlyLeavableOrcadMigrationBlockers } from '../../ssh/targets/ssh-target-orcad-preflight' -import { ORCAD_MIGRATION_LEAVE_BEHIND_TERMINALS_REASON } from '../../ssh/orcad-migration-source-fence' -import type { OrcadMigrationPaneLeasePredicate } from '../../ssh/orcad-migration-bridged-panes' -import { retainOrcadMigrationSource } from '../../ssh/orcad-migration-source-retention' +import { ORCAD_MIGRATION_LEAVE_BEHIND_TERMINALS_REASON } from '../../ssh/migration-source/orcad-migration-source-fence' +import type { OrcadMigrationPaneLeasePredicate } from '../../ssh/migration-source/orcad-migration-bridged-panes' +import { retainOrcadMigrationSource } from '../../persistence/migrating-orcad-catalog/orcad-migration-source-retention' import { enableMovedOrcadAutomations, type EnableServerAutomation -} from '../../ssh/orcad-migration-moved-automations' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-moved-automations' import { linkedOrcadMigrationCutoverPort, linkedOrcadMigrationProjects, - linkServerHeldRepositories, - type OrcadServerRepository -} from '../../ssh/orcad-migration-repository-link' -import type { OrcadServerFolderCatalog } from '../../ssh/orcad-server-folder-workspaces' + linkServerHeldRepositories +} from '../migration/linking/orcad-migration-repository-link' +import type { OrcadServerRepository } from '../migration/linking/orcad-server-repositories' +import type { OrcadServerFolderCatalog } from '../migration/linking/orcad-server-folder-workspaces' export type OrcadManagedConversionArgs = { sshTargetId: string diff --git a/src/main/managed-server/lifecycle/orcad-runtime-decommission.ts b/src/main/managed-server/lifecycle/orcad-runtime-decommission.ts index 135fc8f5248..998ee2cb6a3 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-decommission.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-decommission.ts @@ -24,10 +24,10 @@ import { } from './orcad-managed-runtime-context' import { closeOrcadManagedTunnel, ensureOrcadManagedTunnel } from './orcad-managed-tunnel' import { clearManagedOrcadUpdateDeferral } from './orcad-managed-update-deferrals' -import { removeOrcadMigrationJournalsForDestination } from '../../ssh/orcad-migration-cutover-journal' +import { removeOrcadMigrationJournalsForDestination } from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { decommissionRemoteOrcad } from '../install/orcad-remote-decommission' -import { withManagedOrcadLifecycle } from '../../ssh/orcad-runtime-maintenance' -import { collectManagedTerminalCensus } from '../../ssh/orcad-terminal-census-client' +import { withManagedOrcadLifecycle } from './orcad-managed-lifecycle' +import { collectManagedTerminalCensus } from './orcad-terminal-census-client' import { RemoteInstallLockBusyError } from '../install/remote-install-lock' type ManagedOrcadStopPolicy = { diff --git a/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts b/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts index ce3d1075f65..5787ab61cde 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts @@ -22,20 +22,20 @@ import { startOrcadManagedTunnel } from './orcad-managed-tunnel' import { recoverInterruptedOrcadActivation } from '../activation/orcad-activation-recovery' -import { wakeAlreadyActiveOrcad } from '../../ssh/orcad-already-active-wake' +import { wakeAlreadyActiveOrcad } from './orcad-already-active-wake' import { readOrcadActivationRecord } from '../activation/orcad-activation-record-store' import { resolveOrcadRemoteContext, type OrcadRemoteContext } from '../install/orcad-remote-context' -import { deployOrcad } from '../../ssh/orcad-remote-deploy' +import { deployOrcad } from '../install/orcad-remote-deploy' import { adoptRunningOrcadVersion, type OrcadRunningAdoption -} from '../../ssh/orcad-running-version-adoption' +} from '../activation/orcad-running-version-adoption' import { readLocalFullVersion } from '../install/remote-versioned-install' -import { sshOrcadHostTransport } from '../../ssh/orcad-ssh-host-transport' -import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../../ssh/orcad-installed-activation' + +import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../activation/orcad-installed-activation' import { pruneManagedOrcadVersions } from './orcad-managed-version-gc' -import { tunneledOrcadPairingCode } from '../../ssh/orcad-tunneled-pairing' -import { resolveOrcadMigrationFence } from '../../ssh/orcad-migration-source-fence' +import { tunneledOrcadPairingCode } from './orcad-tunneled-pairing' +import { resolveOrcadMigrationFence } from '../../ssh/migration-source/orcad-migration-source-fence' import type { SshTarget } from '../../../shared/ssh-types' import { findCollidingEnvironmentName } from '../../../shared/remote-runtime/host-catalog/runtime-environment-name-collision' import { deployedOrcadTunnelChecks } from './orcad-managed-tunnel-identity' @@ -97,11 +97,7 @@ export async function createManagedOrcadEnvironment( let environmentRegistered = false try { const connection = await connectionManager.connect(claimed) - let context = await resolveOrcadRemoteContext( - claimed, - sshOrcadHostTransport(connection), - args.signal - ) + let context = await resolveOrcadRemoteContext(claimed, connection, args.signal) const slot = managedOrcadSlot(context, ORCAD_MANAGED_REMOTE_PORT, args.signal) const recovery = await recoverInterruptedOrcadActivation(slot) if (recovery.outcome === 'pending' || recovery.outcome === 'refused') { diff --git a/src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts b/src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts index 8fc138e2d5c..7367a92ac0b 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts @@ -5,10 +5,10 @@ import { listEnvironments } from '../../../shared/remote-runtime/host-store/runt import { listOrcadMigrationSourceCutovers, writeOrcadMigrationSourceCutover -} from '../../ssh/orcad-migration-cutover-journal' -import { orcadMigrationCutoverFixture } from '../../ssh/orcad-migration-cutover-fixture' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { orcadMigrationCutoverFixture } from '../migration/cutover/testing/orcad-migration-cutover-fixture' import { createManagedLifecycleHarness } from './orcad-managed-lifecycle-test-fixture' -import { isManagedOrcadSshTarget } from '../../ssh/connection/ssh-connection-store' +import { isManagedOrcadSshTarget } from '../../ssh/targets/ssh-target-runtime-ownership' import { addManagedOrcadEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' diff --git a/src/main/ssh/orcad-runtime-maintenance.test.ts b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts similarity index 65% rename from src/main/ssh/orcad-runtime-maintenance.test.ts rename to src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts index 865d595518a..f71ba338df6 100644 --- a/src/main/ssh/orcad-runtime-maintenance.test.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts @@ -1,27 +1,24 @@ import { rmSync } from 'node:fs' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { ORCAD_UPDATE_ADMISSION_FENCE_MS } from '../../shared/orcad-terminal-census' +import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' + import { moveManagedOrcadLocalPort, recordManagedOrcadMigration, refreshManagedOrcadPairing -} from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { - orcadUpdateFailedThisLaunch, - recordOrcadUpdateFailedThisLaunch -} from '../managed-server/lifecycle/orcad-managed-update-failure-memory' -import { orcadMigrationCutoverFixture } from './orcad-migration-cutover-fixture' -import { writeOrcadMigrationSourceCutover } from './orcad-migration-cutover-journal' +} from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' + +import { orcadMigrationCutoverFixture } from '../migration/cutover/testing/orcad-migration-cutover-fixture' +import { writeOrcadMigrationSourceCutover } from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { createManagedLifecycleHarness, MANAGED_LOCAL_PORT, MANAGED_PREVIOUS_VERSION, MANAGED_VERSION, managedReadiness -} from '../managed-server/lifecycle/orcad-managed-lifecycle-test-fixture' +} from './orcad-managed-lifecycle-test-fixture' const mocks = vi.hoisted(() => { const state: { store: unknown } = { store: null } @@ -41,50 +38,49 @@ const mocks = vi.hoisted(() => { } }) -vi.mock('./targets/ssh-target-registry', () => ({ +vi.mock('../../ssh/targets/ssh-target-registry', () => ({ getSshConnectionManager: () => ({ connect: async () => ({}) }), getSshTargetRegistryStore: () => mocks.state.store })) -vi.mock('../managed-server/install/orcad-remote-context', () => ({ +vi.mock('../install/orcad-remote-context', () => ({ resolveOrcadRemoteContext: mocks.resolveContext })) vi.mock('./orcad-terminal-census-client', () => ({ collectManagedTerminalCensus: mocks.census })) -vi.mock('./orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) -vi.mock('../managed-server/install/orcad-remote-rollback', () => ({ +vi.mock('../install/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) +vi.mock('../install/orcad-remote-rollback', () => ({ rollbackOrcad: mocks.rollback })) -vi.mock('../managed-server/activation/orcad-activation-recovery', () => ({ +vi.mock('../activation/orcad-activation-recovery', () => ({ recoverInterruptedOrcadActivation: mocks.recover })) -vi.mock('./orcad-active-readiness', () => ({ probeActiveOrcadReadiness: mocks.probe })) -vi.mock('../managed-server/install/orcad-remote-build-hash', () => ({ +vi.mock('../activation/orcad-active-readiness', () => ({ probeActiveOrcadReadiness: mocks.probe })) +vi.mock('../install/orcad-remote-build-hash', () => ({ readRemoteOrcadBuildHash: mocks.buildHash })) -vi.mock('../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) -vi.mock('./orcad-local-build-hash', () => ({ computeLocalOrcadBuildHash: () => 'local-hash' })) -vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ +vi.mock('../install/orcad-local-build-hash', () => ({ + computeLocalOrcadBuildHash: () => 'local-hash' +})) +vi.mock('./orcad-managed-tunnel', () => ({ ensureOrcadManagedTunnel: mocks.ensureTunnel, rebuildOrcadManagedTunnel: mocks.rebuildTunnel })) -vi.mock('../managed-server/lifecycle/orcad-managed-wake', () => ({ +vi.mock('./orcad-managed-wake', () => ({ wakeStoppedManagedOrcad: mocks.wake })) -vi.mock('../managed-server/lifecycle/orcad-managed-migration-status', () => ({ +vi.mock('./orcad-managed-migration-status', () => ({ findIncompleteManagedOrcadMigration: mocks.pendingMigration })) -vi.mock('../managed-server/activation/orcad-activation-transaction-store', () => ({ +vi.mock('../activation/orcad-activation-transaction-store', () => ({ readOrcadActivationTransaction: async () => null })) -const { getManagedOrcadRuntimeStatus } = - await import('../managed-server/lifecycle/orcad-runtime-status') -const { - recoverManagedOrcadEnvironment, - rollbackManagedOrcadEnvironment, - updateManagedOrcadEnvironment -} = await import('./orcad-runtime-maintenance') +const { getManagedOrcadRuntimeStatus } = await import('./orcad-runtime-status') +const { updateManagedOrcadEnvironment } = await import('./orcad-runtime-maintenance') +const { recoverManagedOrcadEnvironment } = await import('./orcad-managed-recovery') +const { rollbackManagedOrcadEnvironment } = await import('./orcad-managed-rollback') const idle = { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 7 } let harness: ReturnType @@ -164,68 +160,6 @@ describe('updateManagedOrcadEnvironment', () => { expect(status.deferredUpdate).toBeNull() }) - it('refuses Update over a host a newer Orca runs, and lets Force take it', async () => { - const newer = { - ...harness.context().activationRecord, - active: '9.0.0+newer', - activeAppVersion: '99.0.0' - } - mocks.deploy.mockResolvedValue({ outcome: 'installed-and-activated', fullVersion: 'v3' }) - await updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - expect(mocks.deploy.mock.calls[0]?.[0].admitRecord(newer, 'v3')).toMatch(/last ran/) - await updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed', force: true }) - expect(mocks.deploy.mock.calls[1]?.[0].admitRecord(newer, 'v3')).toBeNull() - }) - - it('updates past live terminals only over the confirmed build, keeping the downgrade refusal', async () => { - const running = { - ...harness.context().activationRecord, - active: 'v1', - activeAppVersion: '0.0.0-test' - } - mocks.deploy.mockResolvedValue({ outcome: 'installed-and-activated', fullVersion: 'v3' }) - await updateManagedOrcadEnvironment(harness.userDataPath, { - selector: 'Managed', - pastLiveTerminals: { incumbentVersion: 'v1' } - }) - const deployed = mocks.deploy.mock.calls[0]?.[0] - expect(deployed.force).toBe('live-terminals') - expect(deployed.admitRecord(running, 'v3')).toBeNull() - expect(deployed.admitRecord({ ...running, active: 'v2' }, 'v3')).toMatch(/changed since/) - expect( - deployed.admitRecord({ ...running, active: 'v1', activeAppVersion: '99.0.0' }, 'v3') - ).toMatch(/last ran/) - }) - - it('lets an explicit Update retry a build a connect remembered as failed', async () => { - const host = { kind: 'ssh', id: 'ssh-1' } as const - recordOrcadUpdateFailedThisLaunch(host, { code: 'orcad_update_failed', reason: 'rejected' }) - mocks.deploy.mockResolvedValueOnce({ outcome: 'installed-and-activated', fullVersion: 'v3' }) - await updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - expect(orcadUpdateFailedThisLaunch(host)).toBe(false) - expect(mocks.deploy.mock.calls[0]?.[0]).toMatchObject({ census: idle }) - }) - - it('hands the deploy a recount that counts again, so a terminal opened during the upload counts', async () => { - const opened = { ...idle, liveSessions: 1, inProcessSessions: 1 } - mocks.census.mockResolvedValueOnce(idle).mockResolvedValue(opened) - mocks.deploy.mockResolvedValueOnce({ outcome: 'installed-and-activated', fullVersion: 'v3' }) - await updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - const deployed = mocks.deploy.mock.calls[0]?.[0] - expect(deployed?.recountCensus).toBeTypeOf('function') - await expect(deployed!.recountCensus()).resolves.toEqual(opened) - // Only final recount closes admission; initial counts can predate upload. - expect(mocks.census.mock.calls.map((call) => call[4])).toEqual([ - { releaseFinishedAutomationTerminals: true }, - { - releaseFinishedAutomationTerminals: true, - closeAdmissionForMs: ORCAD_UPDATE_ADMISSION_FENCE_MS - } - ]) - await deployed!.releaseIncumbentAdmission() - expect(mocks.census.mock.calls[2]?.[4]).toEqual({ closeAdmissionForMs: 0 }) - }) - it('still reports the activation when the new forward cannot be built yet', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) mocks.deploy.mockResolvedValueOnce({ outcome: 'installed-and-activated', fullVersion: 'v3' }) @@ -292,21 +226,6 @@ describe('updateManagedOrcadEnvironment on a host already running this build', ( expect(mocks.wake.mock.calls[0]?.[0]).toMatchObject({ port: 6_768 }) expect(mocks.rebuildTunnel).toHaveBeenCalledWith(harness.userDataPath, 'environment-1') }) - - it.each(['serving', 'unverifiable', 'fenced'] as const)( - 'leaves a %s slot alone and keeps the tunnel', - async (outcome) => { - mocks.wake.mockResolvedValueOnce({ outcome }) - await updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - expect(mocks.rebuildTunnel).not.toHaveBeenCalled() - } - ) - - it('does not wake after an activation, which launched the new slot itself', async () => { - mocks.deploy.mockResolvedValueOnce({ outcome: 'installed-and-activated', fullVersion: 'v3' }) - await updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - expect(mocks.wake).not.toHaveBeenCalled() - }) }) describe('rollbackManagedOrcadEnvironment', () => { @@ -394,24 +313,6 @@ describe('rollbackManagedOrcadEnvironment', () => { await rollbackManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) expectEnrolledPairing() }) - - it('hands the rollback a recount that closes admission, and a reopen that only reopens it', async () => { - mocks.rollback.mockResolvedValueOnce({ outcome: 'refused', code: 'x', reason: 'y' }) - await rollbackManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - const options = mocks.rollback.mock.calls[0]?.[0] - // Initial census is unfenced; rollback must recount under lock. - expect(mocks.census.mock.calls.map((call) => call[4]?.closeAdmissionForMs)).toEqual([undefined]) - await options.recountCensus() - await options.releaseIncumbentAdmission() - expect(mocks.census.mock.calls.map((call) => call[4])).toEqual([ - { releaseFinishedAutomationTerminals: true }, - { - releaseFinishedAutomationTerminals: true, - closeAdmissionForMs: ORCAD_UPDATE_ADMISSION_FENCE_MS - }, - { closeAdmissionForMs: 0 } - ]) - }) }) describe('recoverManagedOrcadEnvironment', () => { diff --git a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts new file mode 100644 index 00000000000..64a7ed4a312 --- /dev/null +++ b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts @@ -0,0 +1,152 @@ +import { getAppEnvironment } from '../../../shared/app-environment' +import { redactRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { + OrcadManagedDeployResult, + OrcadManagedPastLiveTerminals +} from '../../../shared/orcad-managed-runtime' + +import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { wakeAlreadyActiveOrcad } from './orcad-already-active-wake' +import { + clearManagedOrcadUpdateDeferral, + recordManagedOrcadUpdateDeferral +} from './orcad-managed-update-deferrals' + +import { + isForceableOrcadDeferral, + managedOrcadSlot, + probeManagedOrcadReadiness, + resolveLinkedOrcadContext +} from './orcad-managed-runtime-context' + +import type { requireManagedOrcadEnvironment } from './orcad-managed-runtime-context' + +import type { OrcadRemoteContext } from '../install/orcad-remote-context' +import { deployOrcad } from '../install/orcad-remote-deploy' +import type { OrcadDeployOptions } from '../install/orcad-remote-deploy' +import type { OrcadUpdateForce } from '../activation/orcad-update-plan' +import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../activation/orcad-installed-activation' +import { + pruneManagedOrcadVersions, + pruneSupersededOrcadCandidates +} from './orcad-managed-version-gc' + +import { clearOrcadUpdateFailedThisLaunch } from './orcad-managed-update-failure-memory' +import { admitOrcadRecordForIntent } from './orcad-managed-update-decision' +import { collectManagedTerminalCensus } from './orcad-terminal-census-client' +import { updateTerminalCounts } from '../activation/orcad-fenced-stop' +import { refreshMaintainedOrcadPairing } from './orcad-maintenance-pairing-refresh' +import type { LifecycleArgs } from './orcad-managed-lifecycle' +import { withManagedOrcadLifecycle, followLaunchedServerPort } from './orcad-managed-lifecycle' + +export function updateManagedOrcadEnvironment( + userDataPath: string, + args: LifecycleArgs & { force?: boolean; pastLiveTerminals?: OrcadManagedPastLiveTerminals } +): Promise { + const { pastLiveTerminals } = args + // Update anyway keeps Update's version admission even if a caller also passed force. + const intent = args.force && !pastLiveTerminals ? 'force' : 'update' + return withManagedOrcadLifecycle(userDataPath, args.selector, async (managed) => { + const admitIntent = admitOrcadRecordForIntent(intent, getAppEnvironment().getVersion()) + // Checked under the host fence: another desktop may have activated a build since the confirm. + const admitRecord: NonNullable = pastLiveTerminals + ? (record, candidateVersion) => + record.active !== pastLiveTerminals.incumbentVersion + ? "This host's server changed since the update was confirmed. Review it and update again." + : admitIntent(record, candidateVersion) + : admitIntent + const force: OrcadUpdateForce | undefined = pastLiveTerminals ? 'live-terminals' : args.force + const result = await runManagedOrcadUpdate( + userDataPath, + managed, + await resolveLinkedOrcadContext(managed.environment, managed.deployment, args.signal), + { signal: args.signal, force, admitRecord } + ) + // A completed manual update clears automatic failure suppression; deferred attempts do not. + if (result.outcome !== 'deferred') { + clearOrcadUpdateFailedThisLaunch({ kind: 'ssh', id: managed.deployment.sshTargetId }) + } + return result + }) +} + +export async function runManagedOrcadUpdate( + userDataPath: string, + { environment, deployment }: ReturnType, + context: OrcadRemoteContext, + args: { + force?: OrcadUpdateForce + signal?: AbortSignal + localOrcadDir?: string + admitRecord?: OrcadDeployOptions['admitRecord'] + } +): Promise { + const { countFirst, ...recount } = updateTerminalCounts((options) => + collectManagedTerminalCensus( + userDataPath, + environment, + context.activationRecord, + undefined, + options + ) + ) + const census = await countFirst() + const localOrcadDir = + args.localOrcadDir ?? + (await materializeOrcadArtifact(context.serverTarget, { signal: args.signal })) + const slot = managedOrcadSlot(context, deployment.remotePort, args.signal) + const result = await deployOrcad({ + ...slot, + localOrcadDir, + target: context.serverTarget, + census, + ...recount, + censusRecord: context.activationRecord, + force: args.force, + appVersion: getAppEnvironment().getVersion(), + ...(args.admitRecord ? { admitRecord: args.admitRecord } : {}) + }) + if (result.outcome === 'installed-not-activated') { + const deferral = { + outcome: 'deferred' as const, + candidateVersion: result.fullVersion, + code: result.code, + reason: result.reason, + // Force may override policy deferrals, including a newer host build. + forceable: + isForceableOrcadDeferral(result.code) || + result.code === ORCAD_ACTIVATION_POLICY_REFUSED_CODE + } + // Policy refusal is final for this host, not a transient update to retry. + if (result.code !== ORCAD_ACTIVATION_POLICY_REFUSED_CODE) { + recordManagedOrcadUpdateDeferral(environment.id, deferral, context.activationRecord) + } + await pruneSupersededOrcadCandidates(slot, context.serverTarget, result.fullVersion) + return deferral + } + clearManagedOrcadUpdateDeferral(environment.id) + const alreadyActive = result.outcome === 'already-active' + const managed = { environmentId: environment.id, hostLabel: context.target.label } + const started = alreadyActive && (await wakeAlreadyActiveOrcad(slot, managed)) + const readiness = await probeManagedOrcadReadiness( + context, + localOrcadDir, + result.fullVersion, + args.signal + ) + await pruneManagedOrcadVersions({ + slot, + serverTarget: context.serverTarget, + activeVersion: result.fullVersion, + readiness + }) + const updated = refreshMaintainedOrcadPairing(userDataPath, environment.id, readiness) + if (started || result.outcome !== 'already-active') { + await followLaunchedServerPort(userDataPath, environment.id) + } + return { + outcome: result.outcome === 'already-active' ? 'already-current' : 'updated', + environment: redactRuntimeEnvironment(updated), + activeVersion: result.fullVersion + } +} diff --git a/src/main/managed-server/lifecycle/orcad-runtime-status.ts b/src/main/managed-server/lifecycle/orcad-runtime-status.ts index e1d2cfeeaf2..f9cffd04f13 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-status.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-status.ts @@ -8,7 +8,7 @@ import { } from './orcad-managed-runtime-context' import { currentManagedOrcadUpdateDeferral } from './orcad-managed-update-deferrals' import { findIncompleteManagedOrcadMigration } from './orcad-managed-migration-status' -import { collectManagedTerminalCensus } from '../../ssh/orcad-terminal-census-client' +import { collectManagedTerminalCensus } from './orcad-terminal-census-client' import { getAppEnvironment } from '../../../shared/app-environment' import { bundledManagedOrcadVersion } from './orcad-managed-auto-update' import { availableManagedOrcadUpdate } from './orcad-managed-update-decision' diff --git a/src/main/managed-server/lifecycle/orcad-runtime-target.ts b/src/main/managed-server/lifecycle/orcad-runtime-target.ts index 347cbf9ac83..14f1f811f9e 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-target.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-target.ts @@ -1,9 +1,9 @@ import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' -import { resolveOrcadDeploymentTargetFacts } from '../../ssh/orcad-deployment-target' +import { resolveOrcadDeploymentTargetFacts } from '../install/orcad-deployment-target' import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { pinnedRuntimeTargetForHost } from '../../ssh/pinned-runtime-host-target' -import type { RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { OrcadHostTransport } from '../install/orcad-host-transport' +import { pinnedRuntimeTargetForHost } from '../install/pinned-runtime-host-target' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' /** Lets a caller that knows the host kind add its own fix; the message is the one SSH shows. */ export class OrcadHostGlibcUnsupportedError extends OrcadHostUnsupportedError { diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.test.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.test.ts index 7c85ca3aa2c..5377536f339 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.test.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import type { OrcadStdioBridge } from '../../ssh/orcad-stdio-bridge' +import type { OrcadStdioBridge } from './orcad-stdio-bridge' import { OrcadStdioBridgePortForwardProvider } from './orcad-stdio-bridge-provider' import { spawnLocalBridgeChannel, startEchoServer } from './orcad-stdio-bridge-test-channel' import { ORCAD_WINDOWS_HOST_SCRIPT } from '../host-state/orcad-windows-host-script' diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts index 70441208e7f..a1100294a84 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts @@ -1,14 +1,14 @@ // Lost channels drop their sockets but keep the listener; tunnel reconnect logic owns recovery. import { OrcadStdioBridgeUnavailableError } from '../../orcad/orcad-host-unavailable' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../install/orcad-host-transport' import { checkOrcadStdioBridge, openOrcadStdioBridgeChannel, resolveOrcadStdioBridge, type OrcadStdioBridge -} from '../../ssh/orcad-stdio-bridge' +} from './orcad-stdio-bridge' import { listenOrcadStdioBridge } from './orcad-stdio-bridge-listener' -import { sshOrcadHostTransport } from '../../ssh/orcad-ssh-host-transport' + import type { RemoteCommandChannel } from '../install/remote-install-transport' import type { SshConnection } from '../../ssh/connection/ssh-connection' import type { @@ -39,7 +39,7 @@ export class OrcadStdioBridgePortForwardProvider implements SshPortForwardProvid } start(conn: SshConnection, options: PortForwardStartOptions): Promise { - return startOrcadStdioBridge(sshOrcadHostTransport(conn), options, this.dependencies) + return startOrcadStdioBridge(conn, options, this.dependencies) } } diff --git a/src/main/ssh/orcad-stdio-bridge.test.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts similarity index 89% rename from src/main/ssh/orcad-stdio-bridge.test.ts rename to src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts index 1a79ed54477..858192ec5de 100644 --- a/src/main/ssh/orcad-stdio-bridge.test.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts @@ -5,23 +5,17 @@ import type { Server } from 'node:net' import { PassThrough } from 'node:stream' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import '../orcad/orcad-host-unavailable' +import '../../orcad/orcad-host-unavailable' import './orcad-stdio-bridge' import { orcadPosixStdioBridgeCommand, type OrcadStdioBridgeMode -} from '../managed-server/lifecycle/orcad-stdio-bridge-script' -import { - OrcadStdioBridgeBase64Encoder, - OrcadStdioBridgeDecoder -} from '../managed-server/lifecycle/orcad-stdio-bridge-stream' -import { - spawnLocalBridgeChannel, - startEchoServer -} from '../managed-server/lifecycle/orcad-stdio-bridge-test-channel' -import { ORCAD_WINDOWS_HOST_SCRIPT } from '../managed-server/host-state/orcad-windows-host-script' +} from './orcad-stdio-bridge-script' +import { OrcadStdioBridgeBase64Encoder, OrcadStdioBridgeDecoder } from './orcad-stdio-bridge-stream' +import { spawnLocalBridgeChannel, startEchoServer } from './orcad-stdio-bridge-test-channel' +import { ORCAD_WINDOWS_HOST_SCRIPT } from '../host-state/orcad-windows-host-script' -import type { RemoteCommandChannel } from '../managed-server/install/remote-install-transport' +import type { RemoteCommandChannel } from '../install/remote-install-transport' const POSIX = process.platform !== 'win32' let echo: { server: Server; port: number } diff --git a/src/main/ssh/orcad-stdio-bridge.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts similarity index 86% rename from src/main/ssh/orcad-stdio-bridge.ts rename to src/main/managed-server/lifecycle/orcad-stdio-bridge.ts index 4b214154c23..66c91199765 100644 --- a/src/main/ssh/orcad-stdio-bridge.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts @@ -1,22 +1,19 @@ import { OrcadHostUnsupportedError, OrcadStdioBridgeUnavailableError -} from '../orcad/orcad-host-unavailable' -import { resolveOrcadRemoteContext } from '../managed-server/install/orcad-remote-context' -import { orcadWindowsHomeOpCommand } from '../managed-server/install/orcad-remote-windows-node' +} from '../../orcad/orcad-host-unavailable' +import { resolveOrcadRemoteContext } from '../install/orcad-remote-context' +import { orcadWindowsHomeOpCommand } from '../install/orcad-remote-windows-node' import { orcadBashStdioBridgeCommand, orcadPosixStdioBridgeCommand, type OrcadStdioBridgeMode -} from '../managed-server/lifecycle/orcad-stdio-bridge-script' -import { - OrcadStdioBridgeDecoder, - type OrcadStdioBridgeSignal -} from '../managed-server/lifecycle/orcad-stdio-bridge-stream' -import { isWslOrcadHostTarget, type OrcadHostTransport } from './orcad-host-transport' -import type { RemoteCommandChannel } from '../managed-server/install/remote-install-transport' -import { isWindowsRemoteHost } from './ssh-remote-platform' -import { detectRemoteHostPlatform } from './ssh-remote-platform-detection' +} from './orcad-stdio-bridge-script' +import { OrcadStdioBridgeDecoder, type OrcadStdioBridgeSignal } from './orcad-stdio-bridge-stream' +import { isWslOrcadHostTarget, type OrcadHostTransport } from '../install/orcad-host-transport' +import type { RemoteCommandChannel } from '../install/remote-install-transport' +import { isWindowsRemoteHost } from '../../ssh/remote-host/ssh-remote-platform' +import { detectRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform-detection' export type OrcadStdioBridge = { command: string diff --git a/src/main/ssh/orcad-terminal-census-client.test.ts b/src/main/managed-server/lifecycle/orcad-terminal-census-client.test.ts similarity index 74% rename from src/main/ssh/orcad-terminal-census-client.test.ts rename to src/main/managed-server/lifecycle/orcad-terminal-census-client.test.ts index bef4f26a994..e363cd6c409 100644 --- a/src/main/ssh/orcad-terminal-census-client.test.ts +++ b/src/main/managed-server/lifecycle/orcad-terminal-census-client.test.ts @@ -1,22 +1,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCAD_TERMINAL_CENSUS_RUNTIME_CAPABILITY } from '../../shared/orcad-runtime-capabilities' +import { ORCAD_TERMINAL_CENSUS_RUNTIME_CAPABILITY } from '../../../shared/orcad-runtime-capabilities' import { createEnvironmentFromPairingOffer, type KnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { emptyOrcadActivationRecord, type OrcadActivationRecord -} from '../managed-server/activation/orcad-activation-record' +} from '../activation/orcad-activation-record' const mocks = vi.hoisted(() => ({ send: vi.fn(), ensure: vi.fn(), verify: vi.fn() })) -vi.mock('../../shared/remote-runtime/remote-runtime-client', () => ({ +vi.mock('../../../shared/remote-runtime/remote-runtime-client', () => ({ sendRemoteRuntimeRequestWithStatusPreflight: mocks.send })) -vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ +vi.mock('./orcad-managed-tunnel', () => ({ ensureOrcadManagedTunnel: mocks.ensure })) -vi.mock('../managed-server/lifecycle/orcad-managed-serving-verify', () => ({ +vi.mock('./orcad-managed-serving-verify', () => ({ verifyOrcadManagedServing: mocks.verify })) @@ -57,15 +57,6 @@ describe('managed orcad terminal census client', () => { mocks.verify.mockResolvedValue({ state: 'serving' }) }) - it('never starts a server just to reopen its terminal admission', async () => { - await collectManagedTerminalCensus('/profile', environment, active, undefined, { - closeAdmissionForMs: 0 - }) - // A server that stopped has nothing left to reopen; waking it could restart or recover it. - expect(mocks.verify).not.toHaveBeenCalled() - expect(mocks.send.mock.calls[0]?.[2]).toMatchObject({ closeAdmissionForMs: 0 }) - }) - it.each([ ['an older host without the capability', () => answerWith([], { ok: true, result: census })], [ diff --git a/src/main/ssh/orcad-terminal-census-client.ts b/src/main/managed-server/lifecycle/orcad-terminal-census-client.ts similarity index 83% rename from src/main/ssh/orcad-terminal-census-client.ts rename to src/main/managed-server/lifecycle/orcad-terminal-census-client.ts index d5ebd01938a..56927348bdd 100644 --- a/src/main/ssh/orcad-terminal-census-client.ts +++ b/src/main/managed-server/lifecycle/orcad-terminal-census-client.ts @@ -1,21 +1,21 @@ /** Unknown failures, including older hosts without census support, stay unverifiable and never mean zero live terminals. */ -import { ORCAD_TERMINAL_CENSUS_RUNTIME_CAPABILITY } from '../../shared/orcad-runtime-capabilities' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../shared/electron-remote-runtime-client-capabilities' -import type { PairedRuntimeConnection } from '../../shared/remote-runtime/pairing/paired-runtime-connection' +import { ORCAD_TERMINAL_CENSUS_RUNTIME_CAPABILITY } from '../../../shared/orcad-runtime-capabilities' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' +import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' import { getPreferredPairedRuntimeConnection, type KnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { ORCAD_TERMINAL_CENSUS_METHOD, OrcadTerminalCensusSchema, type OrcadTerminalCensus, UNVERIFIABLE_ORCAD_TERMINAL_CENSUS -} from '../../shared/orcad-terminal-census' -import { sendRemoteRuntimeRequestWithStatusPreflight } from '../../shared/remote-runtime/remote-runtime-client' -import type { OrcadActivationRecord } from '../managed-server/activation/orcad-activation-record' -import { ensureOrcadManagedTunnel } from '../managed-server/lifecycle/orcad-managed-tunnel' -import { verifyOrcadManagedServing } from '../managed-server/lifecycle/orcad-managed-serving-verify' +} from '../../../shared/orcad-terminal-census' +import { sendRemoteRuntimeRequestWithStatusPreflight } from '../../../shared/remote-runtime/remote-runtime-client' +import type { OrcadActivationRecord } from '../activation/orcad-activation-record' +import { ensureOrcadManagedTunnel } from './orcad-managed-tunnel' +import { verifyOrcadManagedServing } from './orcad-managed-serving-verify' export type OrcadTerminalCensusRequestOptions = { releaseFinishedAutomationTerminals?: boolean diff --git a/src/main/ssh/orcad-tunnel-transport-memo.ts b/src/main/managed-server/lifecycle/orcad-tunnel-transport-memo.ts similarity index 100% rename from src/main/ssh/orcad-tunnel-transport-memo.ts rename to src/main/managed-server/lifecycle/orcad-tunnel-transport-memo.ts diff --git a/src/main/ssh/orcad-tunneled-pairing.test.ts b/src/main/managed-server/lifecycle/orcad-tunneled-pairing.test.ts similarity index 83% rename from src/main/ssh/orcad-tunneled-pairing.test.ts rename to src/main/managed-server/lifecycle/orcad-tunneled-pairing.test.ts index c1a0f35c9c4..41ed44bbc7b 100644 --- a/src/main/ssh/orcad-tunneled-pairing.test.ts +++ b/src/main/managed-server/lifecycle/orcad-tunneled-pairing.test.ts @@ -1,7 +1,10 @@ import { describe, expect, it } from 'vitest' -import { encodePairingOffer, parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import type { ServeReadiness } from '../server/serve-readiness' +import { + encodePairingOffer, + parsePairingCode +} from '../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type { ServeReadiness } from '../../server/serve-readiness' import { tunneledOrcadPairingCode } from './orcad-tunneled-pairing' function readiness(endpoint = 'ws://[::1]:6768/runtime?mode=paired#fragment'): ServeReadiness { diff --git a/src/main/ssh/orcad-tunneled-pairing.ts b/src/main/managed-server/lifecycle/orcad-tunneled-pairing.ts similarity index 73% rename from src/main/ssh/orcad-tunneled-pairing.ts rename to src/main/managed-server/lifecycle/orcad-tunneled-pairing.ts index 516240a95ab..3107bce0105 100644 --- a/src/main/ssh/orcad-tunneled-pairing.ts +++ b/src/main/managed-server/lifecycle/orcad-tunneled-pairing.ts @@ -1,7 +1,10 @@ -import { encodePairingOffer, parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' -import type { PairingOffer } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { classifyRemotePairingHostname } from '../../shared/remote-runtime/pairing/remote-pairing-address' -import type { ServeReadiness } from '../server/serve-readiness' +import { + encodePairingOffer, + parsePairingCode +} from '../../../shared/remote-runtime/pairing/pairing' +import type { PairingOffer } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { classifyRemotePairingHostname } from '../../../shared/remote-runtime/pairing/remote-pairing-address' +import type { ServeReadiness } from '../../server/serve-readiness' export function tunneledOrcadPairingCode( readiness: ServeReadiness, diff --git a/src/main/ssh/ssh-host-server-on-connect-stopped-elsewhere.test.ts b/src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts similarity index 93% rename from src/main/ssh/ssh-host-server-on-connect-stopped-elsewhere.test.ts rename to src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts index 1443623950c..00130da15f5 100644 --- a/src/main/ssh/ssh-host-server-on-connect-stopped-elsewhere.test.ts +++ b/src/main/managed-server/lifecycle/ssh-host-server-on-connect-stopped-elsewhere.test.ts @@ -4,8 +4,8 @@ import { withDeactivatedVersion, withDeactivatedVersionCommitted, type OrcadActivationRecord -} from '../managed-server/activation/orcad-activation-record' -import { planManagedOrcadAutoUpdate } from '../managed-server/lifecycle/orcad-managed-update-decision' +} from '../activation/orcad-activation-record' +import { planManagedOrcadAutoUpdate } from './orcad-managed-update-decision' describe('redeploying a host another desktop stopped, across Orca versions', () => { const servedBy = (appVersion: string, active: string): OrcadActivationRecord => ({ diff --git a/src/main/ssh/orcad-bash-stdio-bridge-test-host.ts b/src/main/managed-server/lifecycle/testing/orcad-bash-stdio-bridge-test-host.ts similarity index 89% rename from src/main/ssh/orcad-bash-stdio-bridge-test-host.ts rename to src/main/managed-server/lifecycle/testing/orcad-bash-stdio-bridge-test-host.ts index b37456fa4d8..3351ad4ec83 100644 --- a/src/main/ssh/orcad-bash-stdio-bridge-test-host.ts +++ b/src/main/managed-server/lifecycle/testing/orcad-bash-stdio-bridge-test-host.ts @@ -2,7 +2,7 @@ import { spawnSync } from 'node:child_process' import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' function commandPath(name: string): string { return spawnSync('sh', ['-c', `command -v ${name}`], { encoding: 'utf8' }).stdout.trim() @@ -76,14 +76,6 @@ export function processTree(rootPid: number): number[] { return [...tree] } -export function treeRssMb(pids: readonly number[]): number { - const out = spawnSync('ps', ['-o', 'rss=', '-p', pids.join(',')], { encoding: 'utf8' }).stdout - return out - .trim() - .split('\n') - .reduce((sum, kb) => sum + Number(kb) / 1024, 0) -} - export function isAlive(pid: number): boolean { try { process.kill(pid, 0) diff --git a/src/main/ssh/orcad-windows-stdio-bridge-test-cell.ts b/src/main/managed-server/lifecycle/testing/orcad-windows-stdio-bridge-test-cell.ts similarity index 83% rename from src/main/ssh/orcad-windows-stdio-bridge-test-cell.ts rename to src/main/managed-server/lifecycle/testing/orcad-windows-stdio-bridge-test-cell.ts index 532216c7040..282e9a34079 100644 --- a/src/main/ssh/orcad-windows-stdio-bridge-test-cell.ts +++ b/src/main/managed-server/lifecycle/testing/orcad-windows-stdio-bridge-test-cell.ts @@ -1,14 +1,14 @@ /** Prove managed connectivity through stdio when the Windows lane's sshd refuses TCP forwarding. */ import { connect } from 'node:net' -import { OrcadManagedTunnelTransportProvider } from '../managed-server/lifecycle/orcad-managed-tunnel-transport' +import { OrcadManagedTunnelTransportProvider } from '../orcad-managed-tunnel-transport' import { parseOrcadReadinessWaitOutput, readOrcadReadinessNowCommand -} from '../managed-server/install/orcad-remote-readiness-wait' -import { execOrcadRemote } from '../managed-server/install/orcad-remote-runtime-control' -import type { SshConnection } from './connection/ssh-connection' -import type { RemoteHostPlatform } from './ssh-remote-platform' -import { probeTcpForwarding } from './ssh-tcp-forwarding-probe' +} from '../../install/orcad-remote-readiness-wait' +import { execOrcadRemote } from '../../install/orcad-remote-runtime-control' +import type { SshConnection } from '../../../ssh/connection/ssh-connection' +import type { RemoteHostPlatform } from '../../../ssh/remote-host/ssh-remote-platform' +import { probeTcpForwarding } from '../../../ssh/port-forwarding/ssh-tcp-forwarding-probe' const RESPONSE_TIMEOUT_MS = 60_000 diff --git a/src/main/ssh/orcad-migration-capabilities-client.ts b/src/main/managed-server/migration/catalog/orcad-migration-capabilities-client.ts similarity index 77% rename from src/main/ssh/orcad-migration-capabilities-client.ts rename to src/main/managed-server/migration/catalog/orcad-migration-capabilities-client.ts index 3b855738590..97971088521 100644 --- a/src/main/ssh/orcad-migration-capabilities-client.ts +++ b/src/main/managed-server/migration/catalog/orcad-migration-capabilities-client.ts @@ -1,5 +1,6 @@ import { z } from 'zod' -import { listServerRows, type CatalogRequestOptions } from './orcad-migration-catalog-client' +import { listServerRows } from './orcad-server-catalog-rows' +import type { CatalogRequestOptions } from './orcad-migration-request' /** The destination host's runtime capabilities, read before a migration transfers its blobs. */ export async function readRemoteOrcadMigrationCapabilities( diff --git a/src/main/ssh/orcad-migration-catalog-client-frame-budget.test.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-frame-budget.test.ts similarity index 83% rename from src/main/ssh/orcad-migration-catalog-client-frame-budget.test.ts rename to src/main/managed-server/migration/catalog/orcad-migration-catalog-client-frame-budget.test.ts index 3621aa6258b..94a054fa43a 100644 --- a/src/main/ssh/orcad-migration-catalog-client-frame-budget.test.ts +++ b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-frame-budget.test.ts @@ -1,20 +1,20 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcadMigrationBlobDescriptor } from '../../shared/orcad-migration/orcad-migration-blob-transfer' -import type { OrcadMigrationManifest } from '../../shared/orcad-migration/orcad-migration-manifest' +import type { OrcadMigrationBlobDescriptor } from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' +import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES, ORCAD_MIGRATION_MANIFEST_VERSION -} from '../../shared/orcad-migration/orcad-migration-manifest-validation' +} from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' import { ORCAD_MIGRATION_BLOB_CHANNEL_RUNTIME_CAPABILITY, ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY -} from '../../shared/orcad-runtime-capabilities' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +} from '../../../../shared/orcad-runtime-capabilities' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' const sendRequest = vi.hoisted(() => vi.fn()) const extraCapabilities = vi.hoisted((): string[] => []) -vi.mock('../../shared/remote-runtime/remote-runtime-client', () => ({ +vi.mock('../../../../shared/remote-runtime/remote-runtime-client', () => ({ sendRemoteRuntimeRequestWithStatusPreflight: async ( pairing: unknown, method: string, diff --git a/src/main/ssh/orcad-migration-catalog-client-source-kind.test.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts similarity index 54% rename from src/main/ssh/orcad-migration-catalog-client-source-kind.test.ts rename to src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts index 21ecc3d74fb..682beec4c67 100644 --- a/src/main/ssh/orcad-migration-catalog-client-source-kind.test.ts +++ b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts @@ -1,18 +1,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../shared/orcad-migration/orcad-migration-manifest-validation' -import type { OrcadMigrationManifest } from '../../shared/orcad-migration/orcad-migration-manifest' -import { ORCAD_MIGRATION_SOURCE_KIND_UNKNOWN } from '../../shared/orcad-migration/orcad-migration-source-kind' -import { - ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY, - ORCAD_MIGRATION_LOCAL_WSL_SOURCE_RUNTIME_CAPABILITY -} from '../../shared/orcad-runtime-capabilities' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { computeOrcadMigrationManifestSha256 } from '../orcad/orcad-migration-manifest-digest' +import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' +import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' + +import { ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY } from '../../../../shared/orcad-runtime-capabilities' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' const sendRequest = vi.hoisted(() => vi.fn()) const status = vi.hoisted((): { capabilities: string[] } => ({ capabilities: [] })) -vi.mock('../../shared/remote-runtime/remote-runtime-client', () => ({ +vi.mock('../../../../shared/remote-runtime/remote-runtime-client', () => ({ sendRemoteRuntimeRequestWithStatusPreflight: async ( pairing: unknown, method: string, @@ -30,12 +27,13 @@ vi.mock('../../shared/remote-runtime/remote-runtime-client', () => ({ })) const { - ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED, abortRemoteOrcadMigrationCatalog, commitRemoteOrcadMigrationCatalog, readRemoteOrcadMigrationCatalogState, stageRemoteOrcadMigrationCatalog } = await import('./orcad-migration-catalog-client') +const { ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED } = + await import('./orcad-migration-request') const OPERATIONS = [ stageRemoteOrcadMigrationCatalog, @@ -83,41 +81,10 @@ beforeEach(() => { }) describe('orcad migration source-kind capability gate', () => { - it.each(OPERATIONS)('sends an SSH manifest unchanged to an older destination', async (op) => { - await expect(op(pairingCode, sshManifest())).rejects.toThrow('sent') - expect(sendRequest).toHaveBeenCalledTimes(1) - const params = sendRequest.mock.calls[0][2] - expect(params).toEqual({ manifest: sshManifest() }) - expect(JSON.stringify(params)).not.toContain('"kind"') - }) - it.each(OPERATIONS)('never sends a WSL manifest to an older destination', async (op) => { await expect(op(pairingCode, manifestOfKind('local-wsl'))).rejects.toThrow( ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED ) expect(sendRequest).not.toHaveBeenCalled() }) - - it.each(OPERATIONS)('sends a WSL manifest once the destination advertises it', async (op) => { - status.capabilities = [ - ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY, - ORCAD_MIGRATION_LOCAL_WSL_SOURCE_RUNTIME_CAPABILITY - ] - await expect(op(pairingCode, manifestOfKind('local-wsl'))).rejects.toThrow('sent') - expect(sendRequest).toHaveBeenCalledTimes(1) - }) - - it.each(['ssh-relay', 'wsl', ''])( - 'refuses an unregistered kind %j before any request', - async (kind) => { - status.capabilities = [ - ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY, - ORCAD_MIGRATION_LOCAL_WSL_SOURCE_RUNTIME_CAPABILITY - ] - await expect( - stageRemoteOrcadMigrationCatalog(pairingCode, manifestOfKind(kind)) - ).rejects.toThrow(ORCAD_MIGRATION_SOURCE_KIND_UNKNOWN) - expect(sendRequest).not.toHaveBeenCalled() - } - ) }) diff --git a/src/main/ssh/orcad-migration-catalog-client.test.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts similarity index 81% rename from src/main/ssh/orcad-migration-catalog-client.test.ts rename to src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts index ff53839e399..0e0e06c0263 100644 --- a/src/main/ssh/orcad-migration-catalog-client.test.ts +++ b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts @@ -1,14 +1,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../shared/orcad-migration/orcad-migration-manifest-validation' -import type { OrcadMigrationManifest } from '../../shared/orcad-migration/orcad-migration-manifest' -import { computeOrcadMigrationManifestSha256 } from '../orcad/orcad-migration-manifest-digest' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' +import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' const sendRequest = vi.hoisted(() => vi.fn()) const status = vi.hoisted(() => ({ capabilities: ['orcad.migration-catalog.v1'] })) // Run status preflight, then adapt to the existing single-call assertions. -vi.mock('../../shared/remote-runtime/remote-runtime-client', () => ({ +vi.mock('../../../../shared/remote-runtime/remote-runtime-client', () => ({ sendRemoteRuntimeRequestWithStatusPreflight: async ( pairing: unknown, method: string, @@ -28,8 +28,9 @@ vi.mock('../../shared/remote-runtime/remote-runtime-client', () => ({ } })) -const { readRemoteOrcadMigrationCatalogState, stageRemoteOrcadMigrationSnapshotChunk } = - await import('./orcad-migration-catalog-client') +const { readRemoteOrcadMigrationCatalogState } = await import('./orcad-migration-catalog-client') +const { stageRemoteOrcadMigrationSnapshotChunk } = + await import('../transfers/orcad-migration-chunk-client') function manifest(): OrcadMigrationManifest { const unsigned = { diff --git a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.ts new file mode 100644 index 00000000000..7fbd038ae0d --- /dev/null +++ b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.ts @@ -0,0 +1,146 @@ +import { hasModernAutomationLaunchSetup } from '../../../../shared/automations/launch/automation-launch-setup' +import { automationCanonicalLaunchSetup } from '../../../../shared/automations/launch/automation-canonical-launch-setup' +import { AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY } from '../../../../shared/automations/automation-runtime-capabilities' +import { + parseOrcadMigrationCatalogAbortResult, + parseOrcadMigrationCatalogState +} from '../../../../shared/orcad-migration/orcad-migration-catalog-state' + +import type { + OrcadMigrationCatalogAbortResult, + OrcadMigrationCatalogState, + OrcadMigrationManifest +} from '../../../../shared/orcad-migration/orcad-migration-manifest' + +import { + findUnsupportedMigrationBlobKind, + orcadMigrationBlobKindUnsupportedBlocker +} from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' + +import type { OrcadMigrationBlobDescriptor } from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' +import { orcadMigrationManifestBlobs } from '../../../../shared/orcad-migration/orcad-migration-automation-run-history' +import { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' +import { assertOrcadMigrationRequestFits } from './orcad-migration-request-budget' +import { hasExtraAgentArgs } from '../../../../shared/agent-launch/startup/automation-extra-agent-args' +import { requiredOrcadMigrationSourceCapability } from '../../../../shared/orcad-migration/orcad-migration-source-kind' +import type { CatalogRequestOptions } from './orcad-migration-request' +import { sendSupportedMigrationRequest } from './orcad-migration-request' + +type OrcadCatalogMigrationOperation = 'abort' | 'commit' | 'stage' | 'state' + +const METHOD_BY_OPERATION: Record = { + abort: 'orcad.migration.abortCatalog', + commit: 'orcad.migration.commitCatalog', + stage: 'orcad.migration.stageCatalog', + state: 'orcad.migration.catalogState' +} + +export function stageRemoteOrcadMigrationCatalog( + pairingCode: string, + manifest: OrcadMigrationManifest, + options: CatalogRequestOptions = {} +): Promise { + return requestCatalogState(pairingCode, 'stage', manifest, options) +} + +/** Expected blobs make the destination refuse incomplete commits. */ +export async function commitRemoteOrcadMigrationCatalog( + pairingCode: string, + manifest: OrcadMigrationManifest, + options: CatalogRequestOptions & { + expectedBlobs?: readonly OrcadMigrationBlobDescriptor[] + } = {} +): Promise { + const result = await request(pairingCode, 'commit', manifest, options, options.expectedBlobs) + return parseOrcadMigrationCatalogState(result, manifest) +} + +export function readRemoteOrcadMigrationCatalogState( + pairingCode: string, + manifest: OrcadMigrationManifest, + options: CatalogRequestOptions = {} +): Promise { + return requestCatalogState(pairingCode, 'state', manifest, options) +} + +export async function abortRemoteOrcadMigrationCatalog( + pairingCode: string, + manifest: OrcadMigrationManifest, + options: CatalogRequestOptions = {} +): Promise { + const result = await request(pairingCode, 'abort', manifest, options) + const parsed = parseOrcadMigrationCatalogAbortResult(result, manifest) + // Older already-absent replies prove no durability, unlike real aborts. + if (parsed.state === 'absent' && !parsed.aborted && parsed.durableAbsent !== true) { + throw new Error('orcad_migration_abort_durability_unverifiable:destination_update_required') + } + return parsed +} + +async function requestCatalogState( + pairingCode: string, + operation: Exclude, + manifest: OrcadMigrationManifest, + options: CatalogRequestOptions +): Promise { + const result = await request(pairingCode, operation, manifest, options) + return parseOrcadMigrationCatalogState(result, manifest) +} + +async function request( + pairingCode: string, + operation: OrcadCatalogMigrationOperation, + manifest: OrcadMigrationManifest, + options: CatalogRequestOptions, + expectedBlobs: readonly OrcadMigrationBlobDescriptor[] = [] +): Promise { + const pairing = parsePairingCode(pairingCode) + if (!pairing) { + throw new Error('orcad_migration_pairing_code_invalid') + } + // Preserve exact { manifest } wire shape for blob-free and SSH moves. + const params = expectedBlobs.length > 0 ? { manifest, expectedBlobs } : { manifest } + // Validation-size limits can exceed sealed-frame capacity; reject before the host closes the socket. + assertOrcadMigrationRequestFits(params) + const imports = operation === 'stage' || operation === 'commit' + const carriesExtraAgentArgs = + imports && + (manifest.payload.dormantState?.automations ?? []).some((automation) => + hasExtraAgentArgs(automation.extraAgentArgs) + ) + // An older host would drop the blob a manifest names and import without its rows. + const requiredBlobs = imports + ? [...expectedBlobs, ...orcadMigrationManifestBlobs(manifest)] + : expectedBlobs + const response = await sendSupportedMigrationRequest( + pairing, + METHOD_BY_OPERATION[operation], + params, + options, + carriesExtraAgentArgs, + // Recheck source capabilities on every operation; older hosts may misparse non-SSH sources. + requiredOrcadMigrationSourceCapability(manifest.source), + // Hosts without blob capability would strip expectedBlobs and commit unchecked. + (capabilities) => { + if ( + imports && + (manifest.payload.dormantState?.automations ?? []).some((automation) => + hasModernAutomationLaunchSetup(automationCanonicalLaunchSetup(automation)) + ) && + !capabilities.includes(AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY) + ) { + throw new Error( + 'Update Orca on the destination host to keep automation agent launch settings.' + ) + } + const unsupported = findUnsupportedMigrationBlobKind(requiredBlobs, capabilities) + if (unsupported) { + throw new Error(orcadMigrationBlobKindUnsupportedBlocker(unsupported)) + } + } + ) + if (!response.ok) { + throw new Error(`orcad_migration_${operation}_failed:${response.error.message}`) + } + return response.result +} diff --git a/src/main/ssh/orcad-migration-catalog-reference-client.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-reference-client.ts similarity index 84% rename from src/main/ssh/orcad-migration-catalog-reference-client.ts rename to src/main/managed-server/migration/catalog/orcad-migration-catalog-reference-client.ts index c45ead0f2e8..94999eea6e0 100644 --- a/src/main/ssh/orcad-migration-catalog-reference-client.ts +++ b/src/main/managed-server/migration/catalog/orcad-migration-catalog-reference-client.ts @@ -1,16 +1,16 @@ -import { parseOrcadMigrationCatalogReferenceAbortResult } from '../../shared/orcad-migration/orcad-migration-catalog-state' +import { parseOrcadMigrationCatalogReferenceAbortResult } from '../../../../shared/orcad-migration/orcad-migration-catalog-state' import type { OrcadMigrationCatalogReference, OrcadMigrationCatalogReferenceAbortResult -} from '../../shared/orcad-migration/orcad-migration-manifest' -import { ORCAD_MIGRATION_CATALOG_ABORT_BY_REFERENCE_RUNTIME_CAPABILITY } from '../../shared/orcad-runtime-capabilities' -import { parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' +import { ORCAD_MIGRATION_CATALOG_ABORT_BY_REFERENCE_RUNTIME_CAPABILITY } from '../../../../shared/orcad-runtime-capabilities' +import { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' import { ORCAD_MIGRATION_DESTINATION_UNSUPPORTED, sendSupportedMigrationRequest, type CatalogRequestOptions -} from './orcad-migration-catalog-client' +} from './orcad-migration-request' /** Unlike migration-unsupported, this refusal cannot prove no earlier stage exists. */ export const ORCAD_MIGRATION_DESTINATION_ABORT_BY_REFERENCE_UNSUPPORTED = diff --git a/src/main/managed-server/migration/catalog/orcad-migration-payload-capacity.ts b/src/main/managed-server/migration/catalog/orcad-migration-payload-capacity.ts new file mode 100644 index 00000000000..cbfcc01f0aa --- /dev/null +++ b/src/main/managed-server/migration/catalog/orcad-migration-payload-capacity.ts @@ -0,0 +1,63 @@ +import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' +import type { OrcadMigrationCatalogPayload } from '../../../../shared/orcad-migration/orcad-migration-manifest' + +export const ORCAD_MIGRATION_MANIFEST_TOO_LARGE = 'orcad_migration_manifest_too_large' + +/** Name the largest sections and how to trim the largest; a bare error code was unhelpful (#30126). */ +export function describeOversizedOrcadMigrationPayload( + payload: OrcadMigrationCatalogPayload, + limitBytes = MAX_ORCAD_MIGRATION_MANIFEST_BYTES +): string { + const dormant = payload.dormantState + const removeProjects = 'remove projects you no longer use from this host' + const closeTabs = 'close tabs you no longer need' + const parts: [words: string, value: unknown, trim: string][] = [ + ['projects', payload.repositories, removeProjects], + ['folder workspaces', payload.folderWorkspaces, removeProjects], + ['project groups', payload.projectGroups, removeProjects], + ['saved tabs and panes', dormant?.workspaceSession, closeTabs], + ['saved terminal history', dormant?.terminalScrollbackSnapshots, closeTabs], + ['saved workspace details', dormant?.worktreeMeta, 'delete workspaces you no longer need'], + [ + 'workspace history', + [dormant?.worktreeLineage, dormant?.workspaceLineage], + 'delete workspaces you no longer need' + ], + [ + 'sparse checkout presets', + dormant?.sparsePresets, + 'delete sparse checkout presets you no longer use' + ], + [ + 'retired workspace names', + [dormant?.retiredWorktreeNames, dormant?.retiredWorktreeNamespaces], + removeProjects + ], + [ + 'automations', + [dormant?.automations, dormant?.automationRuns], + "delete automations you no longer need from this host's projects" + ], + ['sidebar and browser settings', dormant?.clientState, closeTabs] + ] + const largest = parts + .map(([words, value, trim]) => ({ + words, + trim, + bytes: new TextEncoder().encode(JSON.stringify(value ?? null)).byteLength + })) + .sort((left, right) => right.bytes - left.bytes) + .slice(0, 3) + const { trim } = largest[0] + return ( + `This SSH host's saved state is too large to move to its Orca server (limit ` + + `${formatKib(limitBytes)}). Largest parts: ` + + `${largest.map(({ words, bytes }) => `${words} (${formatKib(bytes)})`).join(', ')}. ` + + `${trim.charAt(0).toUpperCase()}${trim.slice(1)}, then reconnect. ` + + `(${ORCAD_MIGRATION_MANIFEST_TOO_LARGE})` + ) +} + +export function formatKib(bytes: number): string { + return `${Math.ceil(bytes / 1024)} KB` +} diff --git a/src/main/managed-server/migration/catalog/orcad-migration-request-budget.ts b/src/main/managed-server/migration/catalog/orcad-migration-request-budget.ts new file mode 100644 index 00000000000..18bbecb0a28 --- /dev/null +++ b/src/main/managed-server/migration/catalog/orcad-migration-request-budget.ts @@ -0,0 +1,30 @@ +import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' +import { REMOTE_RUNTIME_MAX_INBOUND_REQUEST_JSON_BYTES } from '../../../../shared/remote-runtime/remote-runtime-memory-limits' +import { describeOversizedOrcadMigrationPayload } from './orcad-migration-payload-capacity' + +// Request id, device token, method name and JSON framing around the params. +const REQUEST_ENVELOPE_RESERVE_BYTES = 1024 + +/** The largest catalog-request params that still fit the host's sealed inbound frame. */ +export const ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES = + REMOTE_RUNTIME_MAX_INBOUND_REQUEST_JSON_BYTES - REQUEST_ENVELOPE_RESERVE_BYTES + +/** Reject oversized manifest requests before fencing: stage/state/full abort would all exceed the sealed frame and close its socket. */ +export function assertOrcadMigrationRequestFits(params: { + manifest: OrcadMigrationManifest +}): void { + if (!orcadMigrationRequestFits(params)) { + throw new Error( + describeOversizedOrcadMigrationPayload( + params.manifest.payload, + ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES + ) + ) + } +} + +export function orcadMigrationRequestFits(params: { manifest: OrcadMigrationManifest }): boolean { + return ( + Buffer.byteLength(JSON.stringify(params), 'utf8') <= ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES + ) +} diff --git a/src/main/managed-server/migration/catalog/orcad-migration-request.ts b/src/main/managed-server/migration/catalog/orcad-migration-request.ts new file mode 100644 index 00000000000..a5951a9c7ce --- /dev/null +++ b/src/main/managed-server/migration/catalog/orcad-migration-request.ts @@ -0,0 +1,81 @@ +import { AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY } from '../../../../shared/automations/automation-runtime-capabilities' +import { pairedRuntimeConnectionFromOffer } from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' +import type { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' +import { ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY } from '../../../../shared/orcad-runtime-capabilities' +import { sendRemoteRuntimeRequestWithStatusPreflight } from '../../../../shared/remote-runtime/remote-runtime-client' +import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' + +/** Missing capability/method is definite refusal; other failures require catalog re-read because a lost reply may hide staged state. */ +export const ORCAD_MIGRATION_DESTINATION_UNSUPPORTED = 'orcad_migration_destination_unsupported' + +/** Refuse older destinations that would silently strip extra agent arguments. */ +export const ORCAD_MIGRATION_DESTINATION_EXTRA_AGENT_ARGS_UNSUPPORTED = + 'orcad_migration_destination_extra_agent_args_unsupported:Update Orca on this host to use extra arguments.' + +/** Unsupported source kinds are refused before any staging request. */ +export const ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED = + 'orcad_migration_destination_source_kind_unsupported:Update Orca on this host to move this project to it.' + +export type CatalogRequestOptions = { + signal?: AbortSignal + timeoutMs?: number + expectedRuntimeId?: string +} + +export async function sendSupportedMigrationRequest( + pairing: NonNullable>, + method: string, + params: unknown, + options: CatalogRequestOptions, + requiresExtraAgentArgs = false, + requiredSourceCapability: string | null = null, + assertCapabilities: (capabilities: readonly string[]) => void = () => {} +): Promise> { + const response = await sendRemoteRuntimeRequestWithStatusPreflight( + pairedRuntimeConnectionFromOffer(pairing), + method, + params, + options.timeoutMs ?? 15_000, + (status) => { + if (!status.ok) { + throw new Error(`orcad_migration_status_failed:${status.error.message}`) + } + if ( + options.expectedRuntimeId !== undefined && + status._meta?.runtimeId !== options.expectedRuntimeId + ) { + throw new Error('orcad_migration_destination_runtime_mismatch') + } + if (!status.result.capabilities?.includes(ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY)) { + throw new Error(ORCAD_MIGRATION_DESTINATION_UNSUPPORTED) + } + if ( + requiresExtraAgentArgs && + !status.result.capabilities?.includes(AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY) + ) { + throw new Error(ORCAD_MIGRATION_DESTINATION_EXTRA_AGENT_ARGS_UNSUPPORTED) + } + if ( + requiredSourceCapability !== null && + !status.result.capabilities?.includes(requiredSourceCapability) + ) { + throw new Error(ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED) + } + assertCapabilities(status.result.capabilities ?? []) + }, + undefined, + ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, + options.signal + ) + if (!response.ok && response.error.code === 'method_not_found') { + throw new Error(ORCAD_MIGRATION_DESTINATION_UNSUPPORTED) + } + if ( + options.expectedRuntimeId !== undefined && + response._meta?.runtimeId !== options.expectedRuntimeId + ) { + throw new Error('orcad_migration_destination_runtime_mismatch') + } + return response +} diff --git a/src/main/managed-server/migration/catalog/orcad-server-catalog-rows.ts b/src/main/managed-server/migration/catalog/orcad-server-catalog-rows.ts new file mode 100644 index 00000000000..880cea92533 --- /dev/null +++ b/src/main/managed-server/migration/catalog/orcad-server-catalog-rows.ts @@ -0,0 +1,20 @@ +import { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' +import type { CatalogRequestOptions } from './orcad-migration-request' +import { sendSupportedMigrationRequest } from './orcad-migration-request' + +export async function listServerRows( + pairingCode: string, + method: string, + rows: string, + options: CatalogRequestOptions +): Promise { + const pairing = parsePairingCode(pairingCode) + if (!pairing) { + throw new Error('orcad_migration_pairing_code_invalid') + } + const response = await sendSupportedMigrationRequest(pairing, method, undefined, options) + if (!response.ok) { + throw new Error(`orcad_migration_${rows}_failed:${response.error.message}`) + } + return response.result +} diff --git a/src/main/ssh/orcad-catalog-durable-mutation.ts b/src/main/managed-server/migration/cutover/orcad-catalog-durable-mutation.ts similarity index 84% rename from src/main/ssh/orcad-catalog-durable-mutation.ts rename to src/main/managed-server/migration/cutover/orcad-catalog-durable-mutation.ts index 04dbc171f19..0f3d6139d97 100644 --- a/src/main/ssh/orcad-catalog-durable-mutation.ts +++ b/src/main/managed-server/migration/cutover/orcad-catalog-durable-mutation.ts @@ -1,4 +1,4 @@ -import type { OrcadMigrationCatalogState } from '../../shared/orcad-migration/orcad-migration-manifest' +import type { OrcadMigrationCatalogState } from '../../../../shared/orcad-migration/orcad-migration-manifest' export async function resolveDurableOrcadCatalogMutation( mutate: () => Promise, diff --git a/src/main/ssh/orcad-conversion-abandon.ts b/src/main/managed-server/migration/cutover/orcad-conversion-abandon.ts similarity index 73% rename from src/main/ssh/orcad-conversion-abandon.ts rename to src/main/managed-server/migration/cutover/orcad-conversion-abandon.ts index 5759e159270..c03d3794252 100644 --- a/src/main/ssh/orcad-conversion-abandon.ts +++ b/src/main/managed-server/migration/cutover/orcad-conversion-abandon.ts @@ -1,19 +1,19 @@ /** Registered destinations must abort/prove empty, then unregister before fence release so later starts cannot reclaim the host. Never-registered destinations held nothing. */ -import { removeManagedOrcadEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import type { KnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' -import { closeOrcadManagedTunnel } from '../managed-server/lifecycle/orcad-managed-tunnel' +import { removeManagedOrcadEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { closeOrcadManagedTunnel } from '../../lifecycle/orcad-managed-tunnel' import { abortOrcadMigrationCutover, type OrcadMigrationAbortResult, type OrcadMigrationCutoverContext, type OrcadMigrationDestinationCatalog } from './orcad-migration-cutover-coordinator' -import { findOrcadMigrationSourceCutoverForTarget } from './orcad-migration-cutover-journal' +import { findOrcadMigrationSourceCutoverForTarget } from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { releaseOrcadMigrationFence, releaseUndeployedMigrationFence -} from './orcad-migration-source-fence' +} from '../../../ssh/migration-source/orcad-migration-source-fence' export async function abandonOrcadConversion(args: { userDataPath: string diff --git a/src/main/ssh/orcad-migration-conflict-guidance.ts b/src/main/managed-server/migration/cutover/orcad-migration-conflict-guidance.ts similarity index 100% rename from src/main/ssh/orcad-migration-conflict-guidance.ts rename to src/main/managed-server/migration/cutover/orcad-migration-conflict-guidance.ts diff --git a/src/main/ssh/orcad-migration-cutover-coordinator.test.ts b/src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.test.ts similarity index 88% rename from src/main/ssh/orcad-migration-cutover-coordinator.test.ts rename to src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.test.ts index 50cc383a076..5357c01be18 100644 --- a/src/main/ssh/orcad-migration-cutover-coordinator.test.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.test.ts @@ -2,30 +2,31 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import type { SshTarget } from '../../shared/ssh-types' -import type { OrcadMigrationManifest } from '../../shared/orcad-migration/orcad-migration-manifest' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' +import { getManagedOrcadFenceEnvironmentId } from '../../../../shared/managed-orcad-ssh-owner' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' +import { + closeTestStores, + createSqliteTestStore +} from '../../../persistence/persistence-test-harness' +import { Store } from '../../../persistence/loading-store/store' import { abortOrcadMigrationCutover, commitOrcadMigrationDestination, stageOrcadMigrationDestination, type OrcadMigrationCutoverContext } from './orcad-migration-cutover-coordinator' -import { ORCAD_MIGRATION_DESTINATION_UNSUPPORTED } from './orcad-migration-catalog-client' +import { ORCAD_MIGRATION_DESTINATION_UNSUPPORTED } from '../catalog/orcad-migration-request' import { listOrcadMigrationSourceCutovers, writeOrcadMigrationSourceCutover -} from './orcad-migration-cutover-journal' -import { - assertOrcadMigrationRequestFits, - createOrcadMigrationManifest -} from './orcad-migration-manifest-export' -import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../shared/orcad-migration/orcad-migration-manifest-validation' -import { fenceOrcadMigrationSource } from './orcad-migration-source-fence' -import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' -import { fakeOrcadMigrationDestination as fakeDestination } from './orcad-migration-destination-fake' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { assertOrcadMigrationRequestFits } from '../catalog/orcad-migration-request-budget' +import { createOrcadMigrationManifest } from '../../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' +import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' +import { fenceOrcadMigrationSource } from '../../../ssh/migration-source/orcad-migration-source-fence' +import { SshTargetOrcadClaims } from '../../../ssh/targets/ssh-target-orcad-claims' +import { fakeOrcadMigrationDestination as fakeDestination } from './testing/orcad-migration-destination-fake' const TARGET: SshTarget = { id: 'ssh-prod', @@ -79,20 +80,6 @@ async function setup() { } describe('migration cutover coordinator', () => { - it('reads a lost commit reply back from the destination instead of failing or retrying blind', async () => { - const h = await setup() - await stageOrcadMigrationDestination(h.context, h.migrationId) - const commit = h.destination.commit.getMockImplementation()! - h.destination.commit.mockImplementationOnce(async (manifest) => { - await commit(manifest) - throw new Error('socket closed') - }) - await expect(commitOrcadMigrationDestination(h.context, h.migrationId)).resolves.toMatchObject({ - phase: 'destination-committed' - }) - expect(h.destination.commits).toBe(1) - }) - it('never journals a commit the server holds only in memory, until its flush succeeds', async () => { const h = await setup() await stageOrcadMigrationDestination(h.context, h.migrationId) diff --git a/src/main/ssh/orcad-migration-cutover-coordinator.ts b/src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.ts similarity index 90% rename from src/main/ssh/orcad-migration-cutover-coordinator.ts rename to src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.ts index b7cee2e2255..657dfcfd930 100644 --- a/src/main/ssh/orcad-migration-cutover-coordinator.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.ts @@ -5,39 +5,39 @@ import type { OrcadMigrationCatalogReferenceAbortResult, OrcadMigrationCatalogState, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' import type { OrcadMigrationSnapshotChunkRequest, OrcadMigrationSnapshotChunkResult -} from '../../shared/orcad-migration/orcad-migration-scrollback' +} from '../../../../shared/orcad-migration/orcad-migration-scrollback' import type { OrcadMigrationBlobChunkRequest, OrcadMigrationBlobChunkResult -} from '../../shared/orcad-migration/orcad-migration-blob-transfer' +} from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' import type { OrcadMigrationSourceCutover, OrcadMigrationSourceCutoverPhase -} from '../../shared/orcad-migration/orcad-migration-source-cutover' +} from '../../../../shared/orcad-migration/orcad-migration-source-cutover' import { resolveDurableOrcadCatalogMutation } from './orcad-catalog-durable-mutation' -import { ORCAD_MIGRATION_DESTINATION_UNSUPPORTED } from './orcad-migration-catalog-client' -import { orcadMigrationRequestFits } from './orcad-migration-manifest-export' +import { ORCAD_MIGRATION_DESTINATION_UNSUPPORTED } from '../catalog/orcad-migration-request' +import { orcadMigrationRequestFits } from '../catalog/orcad-migration-request-budget' import { listOrcadMigrationSourceCutovers, writeOrcadMigrationSourceCutover -} from './orcad-migration-cutover-journal' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import type { OrcadMigrationSourceCutoverPort } from './orcad-migration-source' import { transferOrcadMigrationSnapshots, type OrcadMigrationSnapshotSource -} from './orcad-migration-snapshot-coordinator' +} from '../transfers/orcad-migration-snapshot-coordinator' import { exportedOrcadMigrationBlobSource, transferOrcadMigrationBlobs -} from './orcad-migration-blob-coordinator' -import type { OrcadMigrationExportedBlob } from './orcad-migration-manifest-export' -import type { OrcadMigrationPreflightStore } from './targets/ssh-target-orcad-preflight' -import { sshRelayMigrationCutoverPort } from './orcad-migration-ssh-relay-source' -import type { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' +} from '../transfers/orcad-migration-blob-coordinator' +import type { OrcadMigrationExportedBlob } from '../../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' +import type { OrcadMigrationPreflightStore } from '../../../ssh/targets/ssh-target-orcad-preflight' +import { sshRelayMigrationCutoverPort } from '../../../ssh/migration-source/orcad-migration-ssh-relay-source' +import type { SshTargetOrcadClaims } from '../../../ssh/targets/ssh-target-orcad-claims' export type OrcadMigrationDestinationCatalog = { readState: (manifest: OrcadMigrationManifest) => Promise diff --git a/src/main/ssh/orcad-migration-delta-move.test.ts b/src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts similarity index 83% rename from src/main/ssh/orcad-migration-delta-move.test.ts rename to src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts index c89e680de5a..23e07da08cd 100644 --- a/src/main/ssh/orcad-migration-delta-move.test.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts @@ -2,64 +2,64 @@ 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 { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { addManagedOrcadEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { getManagedOrcadFenceEnvironmentId } from '../../../../shared/managed-orcad-ssh-owner' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { addManagedOrcadEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' import { listEnvironments, resolveEnvironment -} from '../../shared/remote-runtime/host-store/runtime-environment-store' -import type { Repo } from '../../shared/repo-types' -import type { SshTarget } from '../../shared/ssh-types' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import { folderWorkspaceKey } from '../../shared/workspace-scope' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import type { Repo } from '../../../../shared/repo-types' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { closeTestStores, createSqliteTestStore, readPersistedStateJson, writePersistedStateJson -} from '../persistence/persistence-test-harness' -import type { PersistedState } from '../../shared/persisted-state-types' -import { Store } from '../persistence/loading-store/store' +} from '../../../persistence/persistence-test-harness' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import { Store } from '../../../persistence/loading-store/store' import { listOrcadMigrationCutoverChainForTarget, listOrcadMigrationSourceCutovers, writeOrcadMigrationSourceCutover -} from './orcad-migration-cutover-journal' -import { fakeOrcadMigrationDestination } from './orcad-migration-destination-fake' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { fakeOrcadMigrationDestination } from './testing/orcad-migration-destination-fake' import { keepOrcadServerVersion, runOrcadDeltaMove } from './orcad-migration-delta-move' import { orcadSourceStoreWithout, planOrcadDeltaMove } from './orcad-migration-delta-plan' import { createOrcadMigrationManifest, orcadMigrationCatalogIds -} from './orcad-migration-manifest-export' -import { latestOrcadMigrationInto } from './orcad-migration-rollback-mark' -import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../shared/orcad-migration/orcad-migration-manifest-validation' -import { retainOrcadMigrationSource } from './orcad-migration-source-retention' -import { reconcileManagedOrcadSshTargets, visibleRepos } from './orcad-retained-source' -import { SshConnectionStore } from './connection/ssh-connection-store' -import { resolveHostServerOnConnect } from './ssh-host-server-on-connect' -import { hostServerDepsStub } from './ssh-host-server-on-connect-test-deps' -import { runTargetLifecycle } from '../ipc/ssh/ssh-target-lifecycle-queue' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' + +import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' +import { retainOrcadMigrationSource } from '../../../persistence/migrating-orcad-catalog/orcad-migration-source-retention' +import { reconcileManagedOrcadSshTargets } from '../../../persistence/migrating-orcad-catalog/orcad-retained-source' +import { visibleRepos } from '../../../persistence/migrating-orcad-catalog/orcad-source-visibility' +import { SshConnectionStore } from '../../../ssh/targets/ssh-connection-store' +import { resolveHostServerOnConnect } from '../../../ssh/host-server/ssh-host-server-on-connect' +import { hostServerDepsStub } from '../../../ssh/host-server/testing/ssh-host-server-on-connect-test-deps' +import { runTargetLifecycle } from '../../../ipc/ssh/ssh-target-lifecycle-queue' const mocks = vi.hoisted(() => { const state: { targetStore: unknown } = { targetStore: null } return { state, deploy: vi.fn(), ensureTunnel: vi.fn() } }) -vi.mock('./targets/ssh-target-registry', () => ({ +vi.mock('../../../ssh/targets/ssh-target-registry', () => ({ getSshConnectionManager: () => ({}), getSshTargetRegistryStore: () => mocks.state.targetStore })) -vi.mock('../managed-server/lifecycle/orcad-runtime-deployment', () => ({ +vi.mock('../../lifecycle/orcad-runtime-deployment', () => ({ createManagedOrcadEnvironment: mocks.deploy })) -vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ +vi.mock('../../lifecycle/orcad-managed-tunnel', () => ({ ensureOrcadManagedTunnel: mocks.ensureTunnel })) -const { convertSshTargetToManagedOrcad } = - await import('../managed-server/lifecycle/orcad-runtime-conversion') +const { convertSshTargetToManagedOrcad } = await import('../../lifecycle/orcad-runtime-conversion') const TARGET: SshTarget = { id: 'ssh-prod', @@ -429,19 +429,6 @@ describe('moving what an older build added to a converted host', () => { expect(lease.state).not.toBe('terminated') }) - it('commits through the destination the tunnel hands back once it opens', async () => { - await convertedThenChangedOnOlderBuild() - const opened: string[] = [] - // A re-pair while the tunnel opens: only the destination built after it can commit. - const result = await deltaMove(now, 'exited', async () => { - opened.push(listOrcadMigrationSourceCutovers(userDataPath).length === 2 ? 'journaled' : '?') - return destination - }) - expect(result).toMatchObject({ outcome: 'moved' }) - expect(opened).toEqual(['journaled']) - expect(destination.commits).toBe(2) - }) - it('keeps a delta journaled and the host marked when the tunnel cannot open', async () => { await convertedThenChangedOnOlderBuild() await expect( @@ -732,65 +719,3 @@ describe('a retained source is never deleted', () => { expectAllRetained() }) }) - -describe('a delta move against a rollback of an update taken before it', () => { - const later = () => new Date('2026-10-05T00:00:00.000Z') - // An update activated after the conversion and before the delta: its snapshot lacks the delta. - const updateActivatedAt = Date.parse('2026-10-04T00:00:00.000Z') - const rollbackCrossesMigration = () => - updateActivatedAt < - Date.parse(latestOrcadMigrationInto(userDataPath, listEnvironments(userDataPath)[0]!) ?? '') - - it('marks the server before the delta commits, so the rollback is refused', async () => { - await convertedThenChangedOnOlderBuild() - expect(rollbackCrossesMigration()).toBe(false) - const commit = destination.commit.getMockImplementation()! - destination.commit.mockImplementationOnce(async (manifest) => { - expect(listEnvironments(userDataPath)[0]?.orcadMigratedAt).toBe(later().toISOString()) - return commit(manifest) - }) - await expect(deltaMove(later)).resolves.toMatchObject({ outcome: 'moved' }) - expect(rollbackCrossesMigration()).toBe(true) - }) - - it('keeps the mark when the commit lands but its reply is lost', async () => { - await convertedThenChangedOnOlderBuild() - const commit = destination.commit.getMockImplementation()! - const read = destination.readState.getMockImplementation()! - let lost = false - destination.commit.mockImplementationOnce(async (manifest) => { - await commit(manifest) - lost = true - throw new Error('socket closed') - }) - destination.readState.mockImplementation(async (manifest) => { - if (lost) { - throw new Error('socket closed') - } - return read(manifest) - }) - await expect(deltaMove(later)).rejects.toThrow('socket closed') - expect(destination.commits).toBe(2) - expect(rollbackCrossesMigration()).toBe(true) - }) - - it('protects a folder-only delta the same way', async () => { - await convertedThenChangedOnOlderBuild() - store.removeProjectForHost({ id: 'repo-2', executionHostId: `ssh:${TARGET.id}` }) - const group = store.createProjectGroup({ - name: 'folders', - parentPath: '/srv/folders', - connectionId: TARGET.id, - createdFrom: 'manual' - }) - store.createFolderWorkspace({ - projectGroupId: group.id, - folderPath: '/srv/folders/notes', - connectionId: TARGET.id - }) - const plan = planOrcadDeltaMove(userDataPath, store, store.getSshTarget(TARGET.id)!) - expect(plan.added.map((row) => row.kind).sort()).toEqual(['folder-workspace', 'project-group']) - await expect(deltaMove(later)).resolves.toMatchObject({ outcome: 'moved' }) - expect(rollbackCrossesMigration()).toBe(true) - }) -}) diff --git a/src/main/ssh/orcad-migration-delta-move.ts b/src/main/managed-server/migration/cutover/orcad-migration-delta-move.ts similarity index 88% rename from src/main/ssh/orcad-migration-delta-move.ts rename to src/main/managed-server/migration/cutover/orcad-migration-delta-move.ts index f11cfc7e77a..fea494d857d 100644 --- a/src/main/ssh/orcad-migration-delta-move.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-delta-move.ts @@ -2,12 +2,12 @@ import { ORCAD_MIGRATION_SOURCE_CUTOVER_VERSION, type OrcadMigrationSourceCutover -} from '../../shared/orcad-migration/orcad-migration-source-cutover' -import type { OrcadDeltaMoveResult } from '../../shared/orcad-managed-runtime' -import { recordManagedOrcadMigration } from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import type { KnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { SshTarget } from '../../shared/ssh-types' -import type { Store } from '../persistence/loading-store/store' +} from '../../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { OrcadDeltaMoveResult } from '../../../../shared/orcad-managed-runtime' +import { recordManagedOrcadMigration } from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import type { KnownRuntimeEnvironment } from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { Store } from '../../../persistence/loading-store/store' import { abortOrcadMigrationCutover, commitOrcadMigrationDestination, @@ -19,7 +19,7 @@ import { listOrcadMigrationCutoverChainForTarget, removeOrcadMigrationSourceCutover, writeOrcadMigrationSourceCutover -} from './orcad-migration-cutover-journal' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { committedOrcadMigrationChain, orcadDeltaSourceStore, @@ -27,24 +27,24 @@ import { unfinishedOrcadDelta, type OrcadDeltaMovePlan } from './orcad-migration-delta-plan' -import { assertOrcadMigrationRequestFits } from './orcad-migration-manifest-export' -import { retainOrcadMigrationSource } from './orcad-migration-source-retention' +import { assertOrcadMigrationRequestFits } from '../catalog/orcad-migration-request-budget' +import { retainOrcadMigrationSource } from '../../../persistence/migrating-orcad-catalog/orcad-migration-source-retention' import { assessOrcadMigrationTerminals, type OrcadMigrationTerminalVerdict, retireProvenExitedLeases, type CensusHostRelayTerminals -} from './orcad-migration-terminal-gate' +} from '../../../ssh/migration-source/orcad-migration-terminal-gate' import { currentOrcadSourceFingerprint, orcadCatalogFingerprint, unmovedOrcadSourceRows, withKeptOrcadSourceRows -} from './orcad-retained-source' -import { collectOrcadMigrationSourceCatalog } from '../persistence/migrating-orcad-catalog/orcad-source-catalog' -import type { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' +} from '../../../persistence/migrating-orcad-catalog/orcad-retained-source' +import { collectOrcadMigrationSourceCatalog } from '../../../persistence/migrating-orcad-catalog/orcad-source-catalog' +import type { SshTargetOrcadClaims } from '../../../ssh/targets/ssh-target-orcad-claims' import { orcadMigrationRefusalReason } from './orcad-migration-refusal-reason' -import { errorMessage } from '../../shared/error-message' +import { errorMessage } from '../../../../shared/error-message' type OrcadDeltaMoveArgs = { userDataPath: string diff --git a/src/main/ssh/orcad-migration-delta-plan.ts b/src/main/managed-server/migration/cutover/orcad-migration-delta-plan.ts similarity index 85% rename from src/main/ssh/orcad-migration-delta-plan.ts rename to src/main/managed-server/migration/cutover/orcad-migration-delta-plan.ts index 027c2b3f133..df8e5b6d98a 100644 --- a/src/main/ssh/orcad-migration-delta-plan.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-delta-plan.ts @@ -1,23 +1,26 @@ /** Subtract earlier migrations' currently retained rows/state; export only additions. Never merge overlapping old source copies over server-owned state. */ -import type { OrcadDeltaMovePreview, OrcadDeltaMoveRow } from '../../shared/orcad-managed-runtime' +import type { + OrcadDeltaMovePreview, + OrcadDeltaMoveRow +} from '../../../../shared/orcad-managed-runtime' import type { OrcadMigrationCatalogPayload, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import { isRetainedOrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' -import type { OrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' -import type { SshTarget } from '../../shared/ssh-types' -import type { Store } from '../persistence/loading-store/store' -import { collectOrcadMigrationSourceCatalog } from '../persistence/migrating-orcad-catalog/orcad-source-catalog' -import { listOrcadMigrationCutoverChainForTarget } from './orcad-migration-cutover-journal' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' +import { isRetainedOrcadMigrationSourceCutover } from '../../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { OrcadMigrationSourceCutover } from '../../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { Store } from '../../../persistence/loading-store/store' +import { collectOrcadMigrationSourceCatalog } from '../../../persistence/migrating-orcad-catalog/orcad-source-catalog' +import { listOrcadMigrationCutoverChainForTarget } from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { createOrcadMigrationManifest, orcadMigrationCatalogIds, type OrcadMigrationCatalogIds -} from './orcad-migration-manifest-export' -import type { OrcadMigrationSnapshotSource } from './orcad-migration-snapshot-coordinator' -import { collectUntransferredDependentBlockers } from './targets/ssh-target-orcad-dependents' -import type { OrcadMigrationPreflightStore } from './targets/ssh-target-orcad-preflight' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' +import type { OrcadMigrationSnapshotSource } from '../transfers/orcad-migration-snapshot-coordinator' +import { collectUntransferredDependentBlockers } from '../../../ssh/targets/ssh-target-orcad-dependents' +import type { OrcadMigrationPreflightStore } from '../../../ssh/targets/ssh-target-orcad-preflight' export type OrcadDeltaSourceStore = OrcadMigrationPreflightStore & OrcadMigrationSnapshotSource diff --git a/src/main/ssh/orcad-migration-delta-snapshot.test.ts b/src/main/managed-server/migration/cutover/orcad-migration-delta-snapshot.test.ts similarity index 80% rename from src/main/ssh/orcad-migration-delta-snapshot.test.ts rename to src/main/managed-server/migration/cutover/orcad-migration-delta-snapshot.test.ts index 77db2d16811..30320f62a12 100644 --- a/src/main/ssh/orcad-migration-delta-snapshot.test.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-delta-snapshot.test.ts @@ -2,43 +2,45 @@ 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 { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { addManagedOrcadEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { getManagedOrcadFenceEnvironmentId } from '../../../../shared/managed-orcad-ssh-owner' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { addManagedOrcadEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' import { listEnvironments, resolveEnvironment -} from '../../shared/remote-runtime/host-store/runtime-environment-store' -import type { Repo } from '../../shared/repo-types' -import type { SshTarget } from '../../shared/ssh-types' -import { folderWorkspaceKey } from '../../shared/workspace-scope' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' -import { listOrcadMigrationSourceCutovers } from './orcad-migration-cutover-journal' -import { fakeOrcadMigrationDestination } from './orcad-migration-destination-fake' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import type { Repo } from '../../../../shared/repo-types' +import type { SshTarget } from '../../../../shared/ssh-types' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import { + closeTestStores, + createSqliteTestStore +} from '../../../persistence/persistence-test-harness' +import { Store } from '../../../persistence/loading-store/store' +import { listOrcadMigrationSourceCutovers } from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { fakeOrcadMigrationDestination } from './testing/orcad-migration-destination-fake' import { runOrcadDeltaMove } from './orcad-migration-delta-move' -import { reconcileManagedOrcadSshTargets } from './orcad-retained-source' -import { SshConnectionStore } from './connection/ssh-connection-store' -import { runTargetLifecycle } from '../ipc/ssh/ssh-target-lifecycle-queue' +import { reconcileManagedOrcadSshTargets } from '../../../persistence/migrating-orcad-catalog/orcad-retained-source' +import { SshConnectionStore } from '../../../ssh/targets/ssh-connection-store' +import { runTargetLifecycle } from '../../../ipc/ssh/ssh-target-lifecycle-queue' const mocks = vi.hoisted(() => { const state: { targetStore: unknown } = { targetStore: null } return { state, deploy: vi.fn(), ensureTunnel: vi.fn() } }) -vi.mock('./targets/ssh-target-registry', () => ({ +vi.mock('../../../ssh/targets/ssh-target-registry', () => ({ getSshConnectionManager: () => ({}), getSshTargetRegistryStore: () => mocks.state.targetStore })) -vi.mock('../managed-server/lifecycle/orcad-runtime-deployment', () => ({ +vi.mock('../../lifecycle/orcad-runtime-deployment', () => ({ createManagedOrcadEnvironment: mocks.deploy })) -vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ +vi.mock('../../lifecycle/orcad-managed-tunnel', () => ({ ensureOrcadManagedTunnel: mocks.ensureTunnel })) -const { convertSshTargetToManagedOrcad } = - await import('../managed-server/lifecycle/orcad-runtime-conversion') +const { convertSshTargetToManagedOrcad } = await import('../../lifecycle/orcad-runtime-conversion') const TARGET: SshTarget = { id: 'ssh-prod', diff --git a/src/main/ssh/orcad-migration-refusal-reason.ts b/src/main/managed-server/migration/cutover/orcad-migration-refusal-reason.ts similarity index 96% rename from src/main/ssh/orcad-migration-refusal-reason.ts rename to src/main/managed-server/migration/cutover/orcad-migration-refusal-reason.ts index 3f953dbc183..bcca2d4618e 100644 --- a/src/main/ssh/orcad-migration-refusal-reason.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-refusal-reason.ts @@ -1,7 +1,7 @@ import type { OrcadMigrationBlocker, OrcadMigrationDependencyKind -} from '../../shared/orcad-migration/orcad-migration-preflight' +} from '../../../../shared/orcad-migration/orcad-migration-preflight' const DEPENDENCY_WORDS: Record = { 'saved-port-forward': 'saved port forwards', diff --git a/src/main/ssh/orcad-migration-source.ts b/src/main/managed-server/migration/cutover/orcad-migration-source.ts similarity index 77% rename from src/main/ssh/orcad-migration-source.ts rename to src/main/managed-server/migration/cutover/orcad-migration-source.ts index 7d18ef6c985..3af5dfb6301 100644 --- a/src/main/ssh/orcad-migration-source.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-source.ts @@ -1,19 +1,19 @@ /** Expose fenced-source checks/release through the cutover port; conversion owns terminal assessment, export and fence acquisition. */ -import type { OrcadMigrationSourceKind } from '../../shared/orcad-migration/orcad-migration-source-kind' +import type { OrcadMigrationSourceKind } from '../../../../shared/orcad-migration/orcad-migration-source-kind' import type { OrcadMigrationCatalogPayload, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import type { OrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' +import type { OrcadMigrationSourceCutover } from '../../../../shared/orcad-migration/orcad-migration-source-cutover' import type { OrcadMigrationExportedBlob, OrcadMigrationManifestExportOptions -} from './orcad-migration-manifest-export' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' import type { OrcadMigrationFenceResult, OrcadMigrationFenceState -} from './orcad-migration-source-fence' -import type { OrcadMigrationTerminalVerdict } from './orcad-migration-terminal-gate' +} from '../../../ssh/migration-source/orcad-migration-source-fence' +import type { OrcadMigrationTerminalVerdict } from '../../../ssh/migration-source/orcad-migration-terminal-gate' export type OrcadMigrationSourceCutoverPort = { /** Before every stage and commit; throws unless the fenced source still matches the journal. diff --git a/src/main/ssh/orcad-migration-stuck-host-profiles.test.ts b/src/main/managed-server/migration/cutover/orcad-migration-stuck-host-profiles.test.ts similarity index 94% rename from src/main/ssh/orcad-migration-stuck-host-profiles.test.ts rename to src/main/managed-server/migration/cutover/orcad-migration-stuck-host-profiles.test.ts index fdf0ae84ad8..2f8aa10f469 100644 --- a/src/main/ssh/orcad-migration-stuck-host-profiles.test.ts +++ b/src/main/managed-server/migration/cutover/orcad-migration-stuck-host-profiles.test.ts @@ -2,31 +2,34 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { getDefaultPersistedState, getDefaultWorkspaceSession } from '../../shared/constants' -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import type { PersistedState } from '../../shared/persisted-state-types' -import type { SshRemotePtyLease, SshTarget } from '../../shared/ssh-types' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' +import { getDefaultPersistedState, getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { SshRemotePtyLease, SshTarget } from '../../../../shared/ssh-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { + closeTestStores, + createSqliteTestStore +} from '../../../persistence/persistence-test-harness' +import { Store } from '../../../persistence/loading-store/store' import { fenceOrcadMigrationSource, ORCAD_MIGRATION_LEAVE_BEHIND_TERMINALS -} from './orcad-migration-source-fence' +} from '../../../ssh/migration-source/orcad-migration-source-fence' import { assessOrcadMigrationTerminals, retireProvenExitedLeases, type HostRelayTerminalProof -} from './orcad-migration-terminal-gate' -import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' -import { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import { listOrcadMigrationSourceCutovers } from './orcad-migration-cutover-journal' +} from '../../../ssh/migration-source/orcad-migration-terminal-gate' +import { SshTargetOrcadClaims } from '../../../ssh/targets/ssh-target-orcad-claims' +import { getManagedOrcadFenceEnvironmentId } from '../../../../shared/managed-orcad-ssh-owner' +import { listOrcadMigrationSourceCutovers } from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { leaveBehindClearsOrcadMigrationBlockers, onlyLeavableOrcadMigrationBlockers -} from './targets/ssh-target-orcad-preflight' -import { ownedEditorFileId } from '../../shared/workspace-session/workspace-session-pane-ownership' -import { allowsDirectSshRelay } from './connection/ssh-connection-store' +} from '../../../ssh/targets/ssh-target-orcad-preflight' +import { ownedEditorFileId } from '../../../../shared/workspace-session/workspace-session-pane-ownership' +import { allowsDirectSshRelay } from '../../../ssh/targets/ssh-target-runtime-ownership' // Load relay-era profiles through the real Store, then exercise terminal proof, lease retirement and fenced preflight. diff --git a/src/main/ssh/orcad-unreachable-setup-release.test.ts b/src/main/managed-server/migration/cutover/orcad-unreachable-setup-release.test.ts similarity index 73% rename from src/main/ssh/orcad-unreachable-setup-release.test.ts rename to src/main/managed-server/migration/cutover/orcad-unreachable-setup-release.test.ts index c7328fcb695..47ae852d4b2 100644 --- a/src/main/ssh/orcad-unreachable-setup-release.test.ts +++ b/src/main/managed-server/migration/cutover/orcad-unreachable-setup-release.test.ts @@ -2,20 +2,23 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { addManagedOrcadEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import type { SshTarget } from '../../shared/ssh-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' +import { getManagedOrcadFenceEnvironmentId } from '../../../../shared/managed-orcad-ssh-owner' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { addManagedOrcadEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import type { SshTarget } from '../../../../shared/ssh-types' +import { + closeTestStores, + createSqliteTestStore +} from '../../../persistence/persistence-test-harness' +import { Store } from '../../../persistence/loading-store/store' import { stageOrcadMigrationDestination } from './orcad-migration-cutover-coordinator' -import { listOrcadMigrationSourceCutovers } from './orcad-migration-cutover-journal' -import { fakeOrcadMigrationDestination } from './orcad-migration-destination-fake' -import { fenceOrcadMigrationSource } from './orcad-migration-source-fence' +import { listOrcadMigrationSourceCutovers } from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { fakeOrcadMigrationDestination } from './testing/orcad-migration-destination-fake' +import { fenceOrcadMigrationSource } from '../../../ssh/migration-source/orcad-migration-source-fence' import { releaseUnreachableOrcadSetup } from './orcad-unreachable-setup-release' -import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' +import { SshTargetOrcadClaims } from '../../../ssh/targets/ssh-target-orcad-claims' const TARGET: SshTarget = { id: 'ssh-locked', diff --git a/src/main/ssh/orcad-unreachable-setup-release.ts b/src/main/managed-server/migration/cutover/orcad-unreachable-setup-release.ts similarity index 63% rename from src/main/ssh/orcad-unreachable-setup-release.ts rename to src/main/managed-server/migration/cutover/orcad-unreachable-setup-release.ts index 7afaa5f942d..136915edcd7 100644 --- a/src/main/ssh/orcad-unreachable-setup-release.ts +++ b/src/main/managed-server/migration/cutover/orcad-unreachable-setup-release.ts @@ -1,23 +1,26 @@ /** Release conversion setups stranded before staging by refused SSH forwarding. Stop any activated slot, unregister, then use undeployed-fence release; source rows remain intact for retry. */ -import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { removeManagedOrcadEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { findOrcadMigrationSourceCutoverForTarget } from './orcad-migration-cutover-journal' -import { releaseUndeployedMigrationFence } from './orcad-migration-source-fence' -import { closeOrcadManagedTunnel } from '../managed-server/lifecycle/orcad-managed-tunnel' -import type { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' -import { withOrcadActivationLock } from '../managed-server/activation/orcad-activation-lock' -import { withDeactivatedVersionCommitted } from '../managed-server/activation/orcad-activation-record' +import { listEnvironments } from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import { removeManagedOrcadEnvironment } from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import { findOrcadMigrationSourceCutoverForTarget } from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { releaseUndeployedMigrationFence } from '../../../ssh/migration-source/orcad-migration-source-fence' +import { closeOrcadManagedTunnel } from '../../lifecycle/orcad-managed-tunnel' +import type { SshTargetOrcadClaims } from '../../../ssh/targets/ssh-target-orcad-claims' +import { withOrcadActivationLock } from '../../activation/orcad-activation-lock' +import { withDeactivatedVersionCommitted } from '../../activation/orcad-activation-record' import { readOrcadActivationRecord, writeOrcadActivationRecord -} from '../managed-server/activation/orcad-activation-record-store' -import { managedOrcadSlot } from '../managed-server/lifecycle/orcad-managed-runtime-context' -import { resolveOrcadRemoteContext } from '../managed-server/install/orcad-remote-context' -import { orcadStopFreedTheHost } from '../managed-server/install/orcad-remote-process-control' -import { orcadSlotDir, stopOrcadSlot } from './orcad-recovery-slot' -import { sshOrcadHostTransport } from './orcad-ssh-host-transport' -import { getSshConnectionManager, getSshTargetRegistryStore } from './targets/ssh-target-registry' -import { errorMessage } from '../../shared/error-message' +} from '../../activation/orcad-activation-record-store' +import { managedOrcadSlot } from '../../lifecycle/orcad-managed-runtime-context' +import { resolveOrcadRemoteContext } from '../../install/orcad-remote-context' +import { orcadStopFreedTheHost } from '../../install/orcad-remote-process-control' +import { orcadSlotDir, stopOrcadSlot } from '../../activation/orcad-recovery-slot' + +import { + getSshConnectionManager, + getSshTargetRegistryStore +} from '../../../ssh/targets/ssh-target-registry' +import { errorMessage } from '../../../../shared/error-message' export async function releaseUnreachableOrcadSetup(args: { userDataPath: string @@ -59,7 +62,7 @@ async function stopStrandedOrcad(targetId: string, signal?: AbortSignal): Promis } const context = await resolveOrcadRemoteContext( target, - sshOrcadHostTransport(await connectionManager.connect(target)), + await connectionManager.connect(target), signal ) if (!context.activationRecord.active) { diff --git a/src/main/ssh/orcad-migration-cutover-fixture.ts b/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts similarity index 76% rename from src/main/ssh/orcad-migration-cutover-fixture.ts rename to src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts index eb8834a1bb7..a52afb6e458 100644 --- a/src/main/ssh/orcad-migration-cutover-fixture.ts +++ b/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts @@ -1,6 +1,6 @@ -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../shared/orcad-migration/orcad-migration-manifest-validation' -import type { OrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' -import { computeOrcadMigrationManifestSha256 } from '../orcad/orcad-migration-manifest-digest' +import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' +import type { OrcadMigrationSourceCutover } from '../../../../../shared/orcad-migration/orcad-migration-source-cutover' +import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/orcad-migration-manifest-digest' export function orcadMigrationCutoverFixture( migrationId = 'migration-1', diff --git a/src/main/ssh/orcad-migration-destination-fake.ts b/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts similarity index 89% rename from src/main/ssh/orcad-migration-destination-fake.ts rename to src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts index 2fa6a9788b7..f039e5abfbb 100644 --- a/src/main/ssh/orcad-migration-destination-fake.ts +++ b/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts @@ -2,12 +2,12 @@ import { vi, type Mock } from 'vitest' import type { OrcadMigrationCatalogState, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import { parseOrcadMigrationManifest } from '../../shared/orcad-migration/orcad-migration-manifest-validation' -import { advertisedOrcadMigrationDestinationCapabilities } from '../orcad/orcad-migration-destination-capabilities' -import { assertOrcadMigrationManifestDigest } from '../orcad/orcad-migration-manifest-digest' -import type { Store } from '../persistence/loading-store/store' -import type { OrcadMigrationDestinationCatalog } from './orcad-migration-cutover-coordinator' +} from '../../../../../shared/orcad-migration/orcad-migration-manifest' +import { parseOrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' +import { advertisedOrcadMigrationDestinationCapabilities } from '../../../../orcad/orcad-migration-destination-capabilities' +import { assertOrcadMigrationManifestDigest } from '../../../../orcad/orcad-migration-manifest-digest' +import type { Store } from '../../../../persistence/loading-store/store' +import type { OrcadMigrationDestinationCatalog } from '../orcad-migration-cutover-coordinator' type Catalog = OrcadMigrationDestinationCatalog diff --git a/src/main/ssh/orcad-migration-repository-link.test.ts b/src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts similarity index 91% rename from src/main/ssh/orcad-migration-repository-link.test.ts rename to src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts index ea4536b02f7..9ef3706d191 100644 --- a/src/main/ssh/orcad-migration-repository-link.test.ts +++ b/src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts @@ -2,60 +2,63 @@ 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 { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import type { OrcadMigrationManifest } from '../../shared/orcad-migration/orcad-migration-manifest' +import { getManagedOrcadFenceEnvironmentId } from '../../../../shared/managed-orcad-ssh-owner' +import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' import { addManagedOrcadEnvironment, removeManagedOrcadEnvironment -} from '../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import * as environments from '../../shared/remote-runtime/host-store/runtime-environment-store' -import type { Repo } from '../../shared/repo-types' -import { LOCAL_EXECUTION_HOST_ID, toSshExecutionHostId } from '../../shared/execution-host' -import { hostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' -import type { SshTarget } from '../../shared/ssh-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' -import type { OrcadMigrationDestinationCatalog } from './orcad-migration-cutover-coordinator' -import { storeBackedOrcadMigrationDestination } from './orcad-migration-destination-fake' +} from '../../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' +import * as environments from '../../../../shared/remote-runtime/host-store/runtime-environment-store' +import type { Repo } from '../../../../shared/repo-types' +import { LOCAL_EXECUTION_HOST_ID, toSshExecutionHostId } from '../../../../shared/execution-host' +import { hostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' +import type { SshTarget } from '../../../../shared/ssh-types' +import { + closeTestStores, + createSqliteTestStore +} from '../../../persistence/persistence-test-harness' +import { Store } from '../../../persistence/loading-store/store' +import type { OrcadMigrationDestinationCatalog } from '../cutover/orcad-migration-cutover-coordinator' +import { storeBackedOrcadMigrationDestination } from '../cutover/testing/orcad-migration-destination-fake' import { listOrcadMigrationSourceCutovers, removeOrcadMigrationJournalsForDestination -} from './orcad-migration-cutover-journal' -import { planOrcadDeltaMove } from './orcad-migration-delta-plan' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { planOrcadDeltaMove } from '../cutover/orcad-migration-delta-plan' import { linkedOrcadMigrationProjects, - repositoriesHeldByServer, - type OrcadServerRepository + repositoriesHeldByServer } from './orcad-migration-repository-link' +import type { OrcadServerRepository } from './orcad-server-repositories' import { folderWorkspacesHeldByServer, type OrcadServerFolderCatalog } from './orcad-server-folder-workspaces' -import { reconcileManagedOrcadSshTargets, visibleRepos } from './orcad-retained-source' -import { SshConnectionStore } from './connection/ssh-connection-store' +import { reconcileManagedOrcadSshTargets } from '../../../persistence/migrating-orcad-catalog/orcad-retained-source' +import { visibleRepos } from '../../../persistence/migrating-orcad-catalog/orcad-source-visibility' +import { SshConnectionStore } from '../../../ssh/targets/ssh-connection-store' const mocks = vi.hoisted(() => { const state: { targetStore: unknown } = { targetStore: null } return { state, deploy: vi.fn(), ensureTunnel: vi.fn() } }) -vi.mock('./targets/ssh-target-registry', () => ({ +vi.mock('../../../ssh/targets/ssh-target-registry', () => ({ getSshConnectionManager: () => ({}), getSshTargetRegistryStore: () => mocks.state.targetStore })) -vi.mock('../managed-server/lifecycle/orcad-runtime-deployment', () => ({ +vi.mock('../../lifecycle/orcad-runtime-deployment', () => ({ createManagedOrcadEnvironment: mocks.deploy })) -vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ +vi.mock('../../lifecycle/orcad-managed-tunnel', () => ({ ensureOrcadManagedTunnel: mocks.ensureTunnel, closeOrcadManagedTunnel: async () => {} })) -const { convertSshTargetToManagedOrcad } = - await import('../managed-server/lifecycle/orcad-runtime-conversion') -const { runOrcadDeltaMove } = await import('./orcad-migration-delta-move') -const { runTargetLifecycle } = await import('../ipc/ssh/ssh-target-lifecycle-queue') +const { convertSshTargetToManagedOrcad } = await import('../../lifecycle/orcad-runtime-conversion') +const { runOrcadDeltaMove } = await import('../cutover/orcad-migration-delta-move') +const { runTargetLifecycle } = await import('../../../ipc/ssh/ssh-target-lifecycle-queue') const TARGET: SshTarget = { id: 'ssh-shared', @@ -589,33 +592,6 @@ describe('moving the host again after its server was stopped', () => { expect(groupName(server, groupId)).toBe('Renamed on the server') }) - // The server's deletion stands: the move is refused whole and the host stays marked changed. - it.each([ - ['linked', true], - ['moved', false] - ])( - 'refuses, without resurrecting it, a later row in a %s group the server deleted', - async (_kind, relink) => { - const groupId = groupDesktopRepo() - await convert() - if (relink) { - stopServer() - await convert() - } - server.moveProjectToGroup(server.getRepo('desktop-repo')!, null) - server.deleteProjectGroup(groupId) - store.addRepo(repo('added-later', '/root/later')) - store.moveProjectToGroup(store.getRepo('added-later')!, groupId) - await expect(runDelta()).resolves.toMatchObject({ - outcome: 'refused', - code: 'orcad_delta_refused_by_server' - }) - expect(server.getRepo('added-later')).toBeUndefined() - expect(groupName(server, groupId)).toBeUndefined() - expect(store.getSshTarget(TARGET.id)?.orcadFence?.sourceChangedAt).toBeDefined() - } - ) - it('resumes, not relinks, a move the server committed before the reply was lost', async () => { const commit = destination.commit destination.commit = async (manifest) => { diff --git a/src/main/ssh/orcad-migration-repository-link.ts b/src/main/managed-server/migration/linking/orcad-migration-repository-link.ts similarity index 82% rename from src/main/ssh/orcad-migration-repository-link.ts rename to src/main/managed-server/migration/linking/orcad-migration-repository-link.ts index 42a0d0bdccc..bdbac2736c9 100644 --- a/src/main/ssh/orcad-migration-repository-link.ts +++ b/src/main/managed-server/migration/linking/orcad-migration-repository-link.ts @@ -1,38 +1,28 @@ -/** Link same-host-path checkouts to existing server rows without overwriting their newer state; retain desktop source copies. Re-journal under the same id only after proving the prior manifest absent, preventing duplicate imports. */ -import { getAutomationRunRepoId } from '../../shared/automations/history/automation-run-identity' -import type { Automation } from '../../shared/automations/automation-definition' -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' -import { isRepoOnCatalogHost } from '../../shared/execution-host' -import type { OrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' -import type { Repo } from '../../shared/repo-types' -import type { SshManagedServerLinkedProject } from '../../shared/ssh-types' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { splitWorktreeId } from '../../shared/worktree/id' -import type { Store } from '../persistence/loading-store/store' -import { - abortOrcadMigrationCutover, - type OrcadMigrationDestinationCatalog -} from './orcad-migration-cutover-coordinator' -import { writeOrcadMigrationSourceCutover } from './orcad-migration-cutover-journal' -import { orcadSourceStoreWithout, type OrcadDeltaSourceStore } from './orcad-migration-delta-plan' -import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' -import type { OrcadMigrationSourceCutoverPort } from './orcad-migration-source' -import { sshRelayMigrationCutoverPort } from './orcad-migration-ssh-relay-source' -import { orcadCatalogFingerprint } from './orcad-retained-source' -import { - folderWorkspacesHeldByServer, - type OrcadServerFolderCatalog -} from './orcad-server-folder-workspaces' +import { getAutomationRunRepoId } from '../../../../shared/automations/history/automation-run-identity' +import type { Automation } from '../../../../shared/automations/automation-definition' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import type { OrcadMigrationSourceCutover } from '../../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { SshManagedServerLinkedProject } from '../../../../shared/ssh-types' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { splitWorktreeId } from '../../../../shared/worktree/id' +import type { Store } from '../../../persistence/loading-store/store' +import { abortOrcadMigrationCutover } from '../cutover/orcad-migration-cutover-coordinator' +import type { OrcadMigrationDestinationCatalog } from '../cutover/orcad-migration-cutover-coordinator' +import { writeOrcadMigrationSourceCutover } from '../../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' +import { orcadSourceStoreWithout } from '../cutover/orcad-migration-delta-plan' +import type { OrcadDeltaSourceStore } from '../cutover/orcad-migration-delta-plan' +import { createOrcadMigrationManifest } from '../../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' +import type { OrcadMigrationSourceCutoverPort } from '../cutover/orcad-migration-source' +import { sshRelayMigrationCutoverPort } from '../../../ssh/migration-source/orcad-migration-ssh-relay-source' +import { orcadCatalogFingerprint } from '../../../persistence/migrating-orcad-catalog/orcad-retained-source' +import { folderWorkspacesHeldByServer } from './orcad-server-folder-workspaces' +import type { OrcadServerFolderCatalog } from './orcad-server-folder-workspaces' import { projectGroupsHeldByServer, serverHeldProjectGroups } from './orcad-server-project-groups' -import type { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' -export type OrcadServerRepository = Pick & { - connectionId?: string | null - executionHostId?: string | null - /** Proves the server holds this group: its record, not this desktop's copy, wins on relink. */ - projectGroupId?: string | null -} +import type { SshTargetOrcadClaims } from '../../../ssh/targets/ssh-target-orcad-claims' +import type { OrcadServerRepository } from './orcad-server-repositories' /** Match only server-local checkouts. Same-id rows can survive earlier moves into stopped-server profiles (#29560); nested remote rows identify different hosts. */ export function repositoriesHeldByServer( diff --git a/src/main/ssh/orcad-server-folder-workspaces.ts b/src/main/managed-server/migration/linking/orcad-server-folder-workspaces.ts similarity index 83% rename from src/main/ssh/orcad-server-folder-workspaces.ts rename to src/main/managed-server/migration/linking/orcad-server-folder-workspaces.ts index 1a9e297e3d2..8beeceb08a4 100644 --- a/src/main/ssh/orcad-server-folder-workspaces.ts +++ b/src/main/managed-server/migration/linking/orcad-server-folder-workspaces.ts @@ -1,12 +1,13 @@ import { z } from 'zod' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { resolveFolderWorkspaceHost, type FolderHostCatalog -} from '../../shared/folder-workspaces/folder-workspace-execution-host' -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import { listServerRows, type CatalogRequestOptions } from './orcad-migration-catalog-client' -import type { OrcadServerRepository } from './orcad-migration-repository-link' +} from '../../../../shared/folder-workspaces/folder-workspace-execution-host' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import { listServerRows } from '../catalog/orcad-server-catalog-rows' +import type { CatalogRequestOptions } from '../catalog/orcad-migration-request' +import type { OrcadServerRepository } from './orcad-server-repositories' /** Include groups because they can supply a folder's host. */ export type OrcadServerFolderCatalog = Omit diff --git a/src/main/ssh/orcad-server-project-groups.ts b/src/main/managed-server/migration/linking/orcad-server-project-groups.ts similarity index 93% rename from src/main/ssh/orcad-server-project-groups.ts rename to src/main/managed-server/migration/linking/orcad-server-project-groups.ts index cebe89fc3e7..70e9191c3f2 100644 --- a/src/main/ssh/orcad-server-project-groups.ts +++ b/src/main/managed-server/migration/linking/orcad-server-project-groups.ts @@ -1,5 +1,5 @@ -import { isRepoOnCatalogHost } from '../../shared/execution-host' -import type { OrcadMigrationCatalogPayload } from '../../shared/orcad-migration/orcad-migration-manifest' +import { isRepoOnCatalogHost } from '../../../../shared/execution-host' +import type { OrcadMigrationCatalogPayload } from '../../../../shared/orcad-migration/orcad-migration-manifest' import type { OrcadServerFolderCatalog } from './orcad-server-folder-workspaces' /** Same-id groups match only on the server's own host, even when empty. */ diff --git a/src/main/managed-server/migration/linking/orcad-server-repositories.ts b/src/main/managed-server/migration/linking/orcad-server-repositories.ts new file mode 100644 index 00000000000..dde27eef86c --- /dev/null +++ b/src/main/managed-server/migration/linking/orcad-server-repositories.ts @@ -0,0 +1,40 @@ +import { z } from 'zod' +import type { CatalogRequestOptions } from '../catalog/orcad-migration-request' +import { listServerRows } from '../catalog/orcad-server-catalog-rows' +import type { Repo } from '../../../../shared/repo-types' + +// repo.list returns full stored rows; omitted host fields identify server-local repos. +const ServerRepositoriesSchema = z.object({ + repos: z.array( + z.object({ + id: z.string().min(1), + path: z.string().min(1), + connectionId: z.string().nullish(), + executionHostId: z.string().nullish(), + projectGroupId: z.string().nullish() + }) + ) +}) + +export async function listRemoteOrcadRepositories( + pairingCode: string, + options: CatalogRequestOptions = {} +): Promise { + const result = await listServerRows(pairingCode, 'repo.list', 'repositories', options) + return ServerRepositoriesSchema.parse(result).repos.map( + ({ id, path, connectionId, executionHostId, projectGroupId }) => ({ + id, + path, + ...(connectionId != null ? { connectionId } : {}), + ...(executionHostId != null ? { executionHostId } : {}), + ...(projectGroupId != null ? { projectGroupId } : {}) + }) + ) +} + +export type OrcadServerRepository = Pick & { + connectionId?: string | null + executionHostId?: string | null + /** Proves the server holds this group: its record, not this desktop's copy, wins on relink. */ + projectGroupId?: string | null +} diff --git a/src/main/ssh/orcad-migration-blob-coordinator.test.ts b/src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.test.ts similarity index 69% rename from src/main/ssh/orcad-migration-blob-coordinator.test.ts rename to src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.test.ts index 68a00dc563b..082076f86c8 100644 --- a/src/main/ssh/orcad-migration-blob-coordinator.test.ts +++ b/src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.test.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +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' @@ -7,19 +7,17 @@ import { ORCAD_MIGRATION_BLOB_CHUNK_BYTES, requiredMigrationBlobCapabilities, type OrcadMigrationBlobDescriptor -} from '../../shared/orcad-migration/orcad-migration-blob-transfer' -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../shared/orcad-migration/orcad-migration-manifest-validation' +} from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' +import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationCatalogState, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import { ORCAD_MIGRATION_BLOB_CHANNEL_RUNTIME_CAPABILITY } from '../../shared/orcad-runtime-capabilities' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' +import { ORCAD_MIGRATION_BLOB_CHANNEL_RUNTIME_CAPABILITY } from '../../../../shared/orcad-runtime-capabilities' import { - commitOrcadMigrationBlobs, - getOrcadMigrationReceivedBlobPath, inspectOrcadMigrationBlobUploads, stageOrcadMigrationBlobChunk -} from '../persistence/migrating-orcad-catalog/orcad-migration-blob-staging' +} from '../../../persistence/migrating-orcad-catalog/orcad-migration-blob-staging' import { transferOrcadMigrationBlobs, type OrcadMigrationBlobDestination @@ -54,29 +52,6 @@ const contents = new Map([ ]) describe('orcad migration blob sender', () => { - it('uploads every blob in bounded chunks, resuming from the staged offset', async () => { - stageOrcadMigrationBlobChunk({ - stagedManifest: manifest, - root, - request: chunkRequest(blobs[0], 0, history.subarray(0, ORCAD_MIGRATION_BLOB_CHUNK_BYTES)) - }) - const destination = realDestination(requiredMigrationBlobCapabilities(blobs)) - - await transferOrcadMigrationBlobs({ source: source(), manifest, blobs, destination }) - - expect(destination.stageChunk.mock.calls.map(([request]) => request.offset)).toEqual([ - ORCAD_MIGRATION_BLOB_CHUNK_BYTES, - ORCAD_MIGRATION_BLOB_CHUNK_BYTES * 2, - 0 - ]) - commitOrcadMigrationBlobs(manifest, root) - for (const blob of blobs) { - expect(readFileSync(getOrcadMigrationReceivedBlobPath(root, manifest, blob))).toEqual( - contents.get(blob.key) - ) - } - }) - it.each([ ['the blob channel', [blobs[1]], ['orcad.migration-blob.terminal-restore-hints.v1']], ["the blob's kind", [blobs[1]], [ORCAD_MIGRATION_BLOB_CHANNEL_RUNTIME_CAPABILITY]] @@ -91,20 +66,6 @@ describe('orcad migration blob sender', () => { expect(inspectOrcadMigrationBlobUploads(manifest, root)).toBeUndefined() }) - it('confirms a chunk whose acknowledgement was lost from the staged state', async () => { - const destination = realDestination(requiredMigrationBlobCapabilities(blobs)) - const stage = destination.stageChunk.getMockImplementation() - destination.stageChunk.mockImplementationOnce(async (request) => { - await stage?.(request) - throw new Error('connection_lost') - }) - - await transferOrcadMigrationBlobs({ source: source(), manifest, blobs, destination }) - expect(inspectOrcadMigrationBlobUploads(manifest, root)?.map((u) => u.receivedBytes)).toEqual( - expect.arrayContaining([history.length, hints.length]) - ) - }) - it('refuses when the destination holds the same key with other bytes', async () => { const stale = descriptor('terminal-restore-hints', 'migration', Buffer.from('stale')) stageOrcadMigrationBlobChunk({ diff --git a/src/main/ssh/orcad-migration-blob-coordinator.ts b/src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.ts similarity index 97% rename from src/main/ssh/orcad-migration-blob-coordinator.ts rename to src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.ts index 4fd25047753..ec88185b652 100644 --- a/src/main/ssh/orcad-migration-blob-coordinator.ts +++ b/src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.ts @@ -9,11 +9,11 @@ import { orcadMigrationBlobIdentity, orcadMigrationBlobKindUnsupportedBlocker, sameOrcadMigrationBlob -} from '../../shared/orcad-migration/orcad-migration-blob-transfer' +} from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' import type { OrcadMigrationCatalogState, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' export type OrcadMigrationBlobSource = { /** Return the descriptor's exact hashed bytes at offset, up to maxBytes. */ diff --git a/src/main/managed-server/migration/transfers/orcad-migration-chunk-client.ts b/src/main/managed-server/migration/transfers/orcad-migration-chunk-client.ts new file mode 100644 index 00000000000..e5db4409dae --- /dev/null +++ b/src/main/managed-server/migration/transfers/orcad-migration-chunk-client.ts @@ -0,0 +1,71 @@ +import { parseOrcadMigrationSnapshotChunkResult } from '../../../../shared/orcad-migration/orcad-migration-scrollback' +import type { + OrcadMigrationSnapshotChunkRequest, + OrcadMigrationSnapshotChunkResult +} from '../../../../shared/orcad-migration/orcad-migration-scrollback' + +import { + findUnsupportedMigrationBlobKind, + orcadMigrationBlobKindUnsupportedBlocker, + parseOrcadMigrationBlobChunkResult +} from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' + +import type { + OrcadMigrationBlobChunkRequest, + OrcadMigrationBlobChunkResult +} from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' + +import { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' +import type { CatalogRequestOptions } from '../catalog/orcad-migration-request' +import { sendSupportedMigrationRequest } from '../catalog/orcad-migration-request' + +export async function stageRemoteOrcadMigrationSnapshotChunk( + pairingCode: string, + request: OrcadMigrationSnapshotChunkRequest, + options: CatalogRequestOptions = {} +): Promise { + const pairing = parsePairingCode(pairingCode) + if (!pairing) { + throw new Error('orcad_migration_pairing_code_invalid') + } + const response = await sendSupportedMigrationRequest( + pairing, + 'orcad.migration.stageSnapshotChunk', + request, + options + ) + if (!response.ok) { + throw new Error(`orcad_migration_snapshot_failed:${response.error.message}`) + } + return parseOrcadMigrationSnapshotChunkResult(response.result, request) +} + +export async function stageRemoteOrcadMigrationBlobChunk( + pairingCode: string, + request: OrcadMigrationBlobChunkRequest, + options: CatalogRequestOptions = {} +): Promise { + const pairing = parsePairingCode(pairingCode) + if (!pairing) { + throw new Error('orcad_migration_pairing_code_invalid') + } + const response = await sendSupportedMigrationRequest( + pairing, + 'orcad.migration.stageBlobChunk', + request, + options, + false, + null, + // Recheck every request so a downgraded destination cannot stage an unsupported blob kind. + (capabilities) => { + const unsupported = findUnsupportedMigrationBlobKind([request.blob], capabilities) + if (unsupported) { + throw new Error(orcadMigrationBlobKindUnsupportedBlocker(unsupported)) + } + } + ) + if (!response.ok) { + throw new Error(`orcad_migration_blob_failed:${response.error.message}`) + } + return parseOrcadMigrationBlobChunkResult(response.result, request) +} diff --git a/src/main/ssh/orcad-migration-snapshot-coordinator.test.ts b/src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.test.ts similarity index 71% rename from src/main/ssh/orcad-migration-snapshot-coordinator.test.ts rename to src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.test.ts index 95b29e1a03a..0fb0075d094 100644 --- a/src/main/ssh/orcad-migration-snapshot-coordinator.test.ts +++ b/src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.test.ts @@ -1,11 +1,11 @@ import { createHash } from 'node:crypto' -import { describe, expect, it, vi } from 'vitest' -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../shared/orcad-migration/orcad-migration-manifest-validation' +import { describe, expect, it } from 'vitest' +import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationCatalogState, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import type { OrcadMigrationTerminalScrollbackSnapshot } from '../../shared/orcad-migration/orcad-migration-scrollback' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' +import type { OrcadMigrationTerminalScrollbackSnapshot } from '../../../../shared/orcad-migration/orcad-migration-scrollback' import { transferOrcadMigrationSnapshots } from './orcad-migration-snapshot-coordinator' const BYTES = Buffer.from('resume these bytes', 'utf8') @@ -55,37 +55,6 @@ const unreachableRead: ChunkReader = () => { } describe('orcad migration snapshot coordinator', () => { - it('resumes at the observed offset and reconciles a lost chunk response', async () => { - const initialOffset = 4 - const sourceRead = vi.fn(() => ({ - bytesBase64: BYTES.subarray(initialOffset).toString('base64'), - totalBytes: BYTES.length, - eof: true - })) - const store = source(sourceRead) - const snapshotRequest = vi.fn() - const remoteReads = [staged(BYTES.length), staged(BYTES.length)] - - await transferOrcadMigrationSnapshots({ - source: store, - manifest: MANIFEST, - state: staged(initialOffset), - destination: { - stageChunk: async (request) => { - snapshotRequest(request) - throw new Error('response lost') - }, - readState: async () => nextState(remoteReads) - } - }) - - expect(sourceRead).toHaveBeenCalledWith(MANIFEST, SNAPSHOT.ref, initialOffset) - expect(snapshotRequest).toHaveBeenCalledWith( - expect.objectContaining({ offset: initialOffset, ref: SNAPSHOT.ref }) - ) - expect(remoteReads).toEqual([]) - }) - it('refuses a snapshot whose source length changed since export', async () => { await expect( transferOrcadMigrationSnapshots({ diff --git a/src/main/ssh/orcad-migration-snapshot-coordinator.ts b/src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.ts similarity index 94% rename from src/main/ssh/orcad-migration-snapshot-coordinator.ts rename to src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.ts index 945ac9f233b..8e772005806 100644 --- a/src/main/ssh/orcad-migration-snapshot-coordinator.ts +++ b/src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.ts @@ -2,13 +2,13 @@ import type { OrcadMigrationCatalogState, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' +} from '../../../../shared/orcad-migration/orcad-migration-manifest' import { decodeOrcadMigrationSnapshotChunk, type OrcadMigrationSnapshotChunkRequest, type OrcadMigrationSnapshotChunkResult -} from '../../shared/orcad-migration/orcad-migration-scrollback' -import type { Store } from '../persistence/loading-store/store' +} from '../../../../shared/orcad-migration/orcad-migration-scrollback' +import type { Store } from '../../../persistence/loading-store/store' export type OrcadMigrationSnapshotSource = Pick diff --git a/src/main/ssh/unused-host-transport.test-fixture.ts b/src/main/managed-server/testing/managed-host-transport.test-fixture.ts similarity index 80% rename from src/main/ssh/unused-host-transport.test-fixture.ts rename to src/main/managed-server/testing/managed-host-transport.test-fixture.ts index bc0c09e7e22..459c6938ac8 100644 --- a/src/main/ssh/unused-host-transport.test-fixture.ts +++ b/src/main/managed-server/testing/managed-host-transport.test-fixture.ts @@ -1,5 +1,5 @@ -import type { SshConnection } from './connection/ssh-connection' -import type { OrcadHostTransport } from './orcad-host-transport' +import type { SshConnection } from '../../ssh/connection/ssh-connection' +import type { OrcadHostTransport } from '../install/orcad-host-transport' // Placeholders for tests that mock every reader of the connection, so it is only forwarded. diff --git a/src/main/memory/host-malloc-tunables.ts b/src/main/memory/host-malloc-tunables.ts index a9f342a9314..b961d1f4264 100644 --- a/src/main/memory/host-malloc-tunables.ts +++ b/src/main/memory/host-malloc-tunables.ts @@ -4,7 +4,7 @@ * at idle, flood throughput unchanged). glibc reads GLIBC_TUNABLES only at exec, so the launch sets it * and each host process removes it at once: shells, agents and git must keep the user's malloc. */ -import type { OrcadLaunchEnvEntry } from '../ssh/orcad-host-transport' +import type { OrcadLaunchEnvEntry } from '../managed-server/install/orcad-host-transport' export const HOST_MALLOC_TUNABLES = 'glibc.malloc.mmap_threshold=16384' const GLIBC_TUNABLES = 'GLIBC_TUNABLES' diff --git a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-startup-attempt-contract.ts b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-startup-attempt-contract.ts index 0e5c6edaf09..8cc4be8e92c 100644 --- a/src/main/native-chat/agent-session-wire/startup/structured-agent-session-startup-attempt-contract.ts +++ b/src/main/native-chat/agent-session-wire/startup/structured-agent-session-startup-attempt-contract.ts @@ -10,7 +10,7 @@ import type { AgentChildWorkEvidence } from '../../../../shared/agent-status/chi import type { StructuredAgentSessionEventSink } from '../journal-ingress/structured-agent-session-event-sink' import type { AgentChatPermissionChoice } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' -/** Absolute registration-time ceiling, independent of shorter protocol-step bounds. */ +/** Absolute registration-time ceiling, independent of protocol readiness. */ export const STRUCTURED_AGENT_SESSION_STARTUP_CEILING_MS = 10 * 60_000 export type StructuredAgentSessionStartupLimits = { ceilingMs: number } diff --git a/src/main/opencode/opencode-wsl-text-task.ts b/src/main/opencode/opencode-wsl-text-task.ts index 90e22eb371c..7e6b5246e67 100644 --- a/src/main/opencode/opencode-wsl-text-task.ts +++ b/src/main/opencode/opencode-wsl-text-task.ts @@ -5,7 +5,7 @@ import { getAppEnvironment } from '../../shared/app-environment' import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' import { OPENCODE_WSL_TEXT_TASK_FILENAME } from '../../shared/remote-bundle-artifacts' import { SearchSubprocessLineAccumulator } from '../../shared/search-subprocess-lines' -import { relayBundleCandidates } from '../ssh/relay-bundle-paths' +import { relayBundleCandidates } from '../wsl/execution/relay-bundle-paths' import { ensureWslPinnedRuntime } from '../wsl/execution/wsl-pinned-runtime' import { runWslProcess, type WslSpec } from '../wsl/execution/wsl-runner' import { describeWslProcessFailure } from '../wsl/execution/wsl-process-failure' diff --git a/src/main/orcad/orcad-profile-state-startup.ts b/src/main/orcad/orcad-profile-state-startup.ts index 3f3e940b5ae..5cbcd3be895 100644 --- a/src/main/orcad/orcad-profile-state-startup.ts +++ b/src/main/orcad/orcad-profile-state-startup.ts @@ -1,8 +1,8 @@ import { createProfileStateStoreForStartup } from '../persistence/profile-state/profile-state-startup-authority' import type { ProfileStateStoreFactoryResult } from '../persistence/profile-state/profile-state-store-factory' import { ensureActiveOrcaProfile, initOrcaProfilePaths } from '../orca-profiles/profile-index-store' -import { initSshHostKeyStoreFile } from '../ssh/ssh-host-key-store' -import { initOrcadHeldFenceTokenFile } from '../ssh/orcad-held-fence-tokens' +import { initSshHostKeyStoreFile } from '../ssh/host-keys/ssh-host-key-store' +import { initOrcadHeldFenceTokenFile } from '../managed-server/activation/orcad-held-fence-tokens' import { emitOrcadProfileStateAuthoritySelected } from './orcad-profile-state-telemetry' import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' diff --git a/src/main/persistence/loading-store/ssh-profile-operations.ts b/src/main/persistence/loading-store/ssh-profile-operations.ts index c9f179217c7..f236db609ba 100644 --- a/src/main/persistence/loading-store/ssh-profile-operations.ts +++ b/src/main/persistence/loading-store/ssh-profile-operations.ts @@ -26,7 +26,7 @@ import type { WriteSchedulingOperations } from './write-scheduling' import type { RepoLifecycleOperations } from './repo-lifecycle-operations' import { syncProjectHostSetupCompatibilityState } from './repo-lifecycle-operations' import { scheduleSave } from './write-scheduling' -import { forgetSshConnectionGeneration } from '../../ssh/connection/ssh-connection-generation' +import { forgetSshConnectionGeneration } from '../../ssh/connection/authority/ssh-connection-generation' type SshProfileOperationsRuntime = Pick diff --git a/src/main/ssh/connection/ssh-reattach-pane-cardinality.test.ts b/src/main/persistence/loading-store/ssh-reattach-pane-cardinality.test.ts similarity index 94% rename from src/main/ssh/connection/ssh-reattach-pane-cardinality.test.ts rename to src/main/persistence/loading-store/ssh-reattach-pane-cardinality.test.ts index e3819bc78d7..cda5be49744 100644 --- a/src/main/ssh/connection/ssh-reattach-pane-cardinality.test.ts +++ b/src/main/persistence/loading-store/ssh-reattach-pane-cardinality.test.ts @@ -2,17 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { - testState, - createStore, - makeRepo, - writeDataFile -} from '../../persistence/persistence-test-harness' -import { - makeTerminalTab, - TEST_LEAF_1, - TEST_LEAF_2 -} from '../../persistence/persistence-session-fixtures' +import { testState, createStore, makeRepo, writeDataFile } from '../persistence-test-harness' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' import { getDefaultPersistedState } from '../../../shared/constants' diff --git a/src/main/ssh/orcad-migration-automation-run-history.test.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-automation-run-history.test.ts similarity index 85% rename from src/main/ssh/orcad-migration-automation-run-history.test.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-automation-run-history.test.ts index 49b54a5fb86..506b1c90465 100644 --- a/src/main/ssh/orcad-migration-automation-run-history.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-automation-run-history.test.ts @@ -2,20 +2,20 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES, parseOrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest-validation' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' -import { commitOrcadMigrationDestination } from './orcad-migration-cutover-coordinator' -import { storeBackedOrcadMigrationDestination } from './orcad-migration-destination-fake' +} from '../../../shared/orcad-migration/orcad-migration-manifest-validation' +import { closeTestStores, createSqliteTestStore } from '../persistence-test-harness' +import { Store } from '../loading-store/store' +import { commitOrcadMigrationDestination } from '../../managed-server/migration/cutover/orcad-migration-cutover-coordinator' +import { storeBackedOrcadMigrationDestination } from '../../managed-server/migration/cutover/testing/orcad-migration-destination-fake' 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' +import '../../ssh/migration-source/orcad-migration-source-assertions' +import { fenceOrcadMigrationSource } from '../../ssh/migration-source/orcad-migration-source-fence' +import { SshTargetOrcadClaims } from '../../ssh/targets/ssh-target-orcad-claims' const TARGET: SshTarget = { id: 'ssh-prod', diff --git a/src/main/ssh/orcad-migration-cutover-journal.test.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-cutover-journal.test.ts similarity index 72% rename from src/main/ssh/orcad-migration-cutover-journal.test.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-cutover-journal.test.ts index b18741d6ac0..2110dca23d0 100644 --- a/src/main/ssh/orcad-migration-cutover-journal.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-cutover-journal.test.ts @@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { orcadMigrationCutoverFixture as cutover } from './orcad-migration-cutover-fixture' +import { orcadMigrationCutoverFixture as cutover } from '../../managed-server/migration/cutover/testing/orcad-migration-cutover-fixture' import { findOrcadMigrationSourceCutoverForTarget, listOrcadMigrationSourceCutovers, @@ -48,17 +48,6 @@ describe('migration cutover journal sidecar', () => { expect(listOrcadMigrationSourceCutovers(userDataPath)).toEqual([cutover()]) }) - it('serves repeat reads from cache yet sees a file rewritten behind its back', () => { - writeOrcadMigrationSourceCutover(userDataPath, cutover()) - const first = listOrcadMigrationSourceCutovers(userDataPath) - expect(listOrcadMigrationSourceCutovers(userDataPath)[0]).toBe(first[0]) - writeFileSync( - journalPath('migration-1'), - JSON.stringify({ ...cutover(), phase: 'destination-staged' }) - ) - expect(listOrcadMigrationSourceCutovers(userDataPath)[0]?.phase).toBe('destination-staged') - }) - it('fails closed on a file whose name disagrees with its migration', () => { mkdirSync(orcadMigrationCutoverJournalDirectory(userDataPath), { recursive: true }) writeFileSync(journalPath('other'), JSON.stringify(cutover())) @@ -74,20 +63,4 @@ describe('migration cutover journal sidecar', () => { 'journals name SSH target' ) }) - - it('bounds concurrent migrations but rewrites an existing one', () => { - for (const index of [1, 2, 3, 4]) { - writeOrcadMigrationSourceCutover(userDataPath, cutover(`m-${index}`, `ssh-${index}`)) - } - expect(() => writeOrcadMigrationSourceCutover(userDataPath, cutover('m-5', 'ssh-5'))).toThrow( - 'capacity' - ) - writeOrcadMigrationSourceCutover(userDataPath, { - ...cutover('m-1', 'ssh-1'), - phase: 'destination-staged' - }) - expect(findOrcadMigrationSourceCutoverForTarget(userDataPath, 'ssh-1')?.phase).toBe( - 'destination-staged' - ) - }) }) diff --git a/src/main/ssh/orcad-migration-cutover-journal.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-cutover-journal.ts similarity index 96% rename from src/main/ssh/orcad-migration-cutover-journal.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-cutover-journal.ts index 71fccc65482..898b609bcb8 100644 --- a/src/main/ssh/orcad-migration-cutover-journal.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-cutover-journal.ts @@ -4,11 +4,11 @@ import { isRetainedOrcadMigrationSourceCutover, parseOrcadMigrationSourceCutover, type OrcadMigrationSourceCutover -} from '../../shared/orcad-migration/orcad-migration-source-cutover' +} from '../../../shared/orcad-migration/orcad-migration-source-cutover' import { createMigrationJournalDirectory, orderMigrationJournalChain -} from '../persistence/migrating-orcad-catalog/migration-journal-directory' +} from './migration-journal-directory' class OrcadMigrationCutoverJournalUnreadableError extends Error { constructor(detail: string) { diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-migration-dormant-state.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-dormant-state.ts new file mode 100644 index 00000000000..ee210bc44b5 --- /dev/null +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-dormant-state.ts @@ -0,0 +1,18 @@ +import type { OrcadMigrationDormantStatePayload } from '../../../shared/orcad-migration/orcad-migration-manifest' + +export function hasDormantState(state: OrcadMigrationDormantStatePayload): boolean { + return ( + state.worktreeMeta.length > 0 || + state.worktreeLineage.length > 0 || + state.workspaceLineage.length > 0 || + state.sparsePresets.length > 0 || + state.retiredWorktreeNames.length > 0 || + state.retiredWorktreeNamespaces.length > 0 || + state.workspaceSession !== undefined || + (state.terminalScrollbackSnapshots?.length ?? 0) > 0 || + (state.automations?.length ?? 0) > 0 || + (state.automationRuns?.length ?? 0) > 0 || + state.automationRunHistory !== undefined || + (state.clientState !== undefined && Object.keys(state.clientState).length > 0) + ) +} diff --git a/src/main/ssh/orcad-migration-manifest-export.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-manifest-export.ts similarity index 56% rename from src/main/ssh/orcad-migration-manifest-export.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-manifest-export.ts index 18b93c229b2..7757f62fbbe 100644 --- a/src/main/ssh/orcad-migration-manifest-export.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-manifest-export.ts @@ -1,34 +1,40 @@ -/** Export copied catalog/dormant state without mutating source. Path rewriting precedes signing; source ownership remains until cutover establishes destination authority. */ import { createHash, randomUUID } from 'node:crypto' + import { - MAX_ORCAD_MIGRATION_MANIFEST_BYTES, ORCAD_MIGRATION_MANIFEST_VERSION, parseOrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest-validation' +} from '../../../shared/orcad-migration/orcad-migration-manifest-validation' + import type { OrcadMigrationCatalogPayload, - OrcadMigrationDormantStatePayload, OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import { - ORCAD_MIGRATION_BLOB_KIND_CONTRACTS, - type OrcadMigrationBlobDescriptor -} from '../../shared/orcad-migration/orcad-migration-blob-transfer' +} from '../../../shared/orcad-migration/orcad-migration-manifest' + +import { ORCAD_MIGRATION_BLOB_KIND_CONTRACTS } from '../../../shared/orcad-migration/orcad-migration-blob-transfer' +import type { OrcadMigrationBlobDescriptor } from '../../../shared/orcad-migration/orcad-migration-blob-transfer' import { orcadMigrationAutomationRunHistoryBlob, serializeOrcadMigrationAutomationRunHistory, withOrcadMigrationAutomationRunHistory -} from '../../shared/orcad-migration/orcad-migration-automation-run-history' -import type { SshTarget } from '../../shared/ssh-types' -import { REMOTE_RUNTIME_MAX_INBOUND_REQUEST_JSON_BYTES } from '../../shared/remote-runtime/remote-runtime-memory-limits' -import type { Store } from '../persistence/loading-store/store' -import { collectOrcadMigrationSourceCatalog } from '../persistence/migrating-orcad-catalog/orcad-source-catalog' -import { computeOrcadMigrationManifestSha256 } from '../orcad/orcad-migration-manifest-digest' +} from '../../../shared/orcad-migration/orcad-migration-automation-run-history' + +import type { SshTarget } from '../../../shared/ssh-types' +import type { Store } from '../loading-store/store' +import { collectOrcadMigrationSourceCatalog } from './orcad-source-catalog' +import { computeOrcadMigrationManifestSha256 } from '../../orcad/orcad-migration-manifest-digest' import { IDENTITY_ORCAD_MIGRATION_PATH_REWRITER, - rewriteOrcadMigrationPayloadPaths, - type OrcadMigrationPathRewriter -} from './orcad-migration-path-rewrite' + rewriteOrcadMigrationPayloadPaths +} from './path-rewrite/orcad-migration-path-rewrite' + +import type { OrcadMigrationPathRewriter } from './path-rewrite/orcad-migration-path-rewrite' +import { + ORCAD_MIGRATION_MANIFEST_TOO_LARGE, + describeOversizedOrcadMigrationPayload, + formatKib +} from '../../managed-server/migration/catalog/orcad-migration-payload-capacity' + +import { hasDormantState } from './orcad-migration-dormant-state' export type OrcadMigrationExportStore = Pick< Store, @@ -172,94 +178,8 @@ function moveAutomationRunsToBlob(payload: OrcadMigrationCatalogPayload): { } } -const ORCAD_MIGRATION_MANIFEST_TOO_LARGE = 'orcad_migration_manifest_too_large' const UNSIGNED_DIGEST = '0'.repeat(64) -// Request id, device token, method name and JSON framing around the params. -const REQUEST_ENVELOPE_RESERVE_BYTES = 1024 -/** The largest catalog-request params that still fit the host's sealed inbound frame. */ -export const ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES = - REMOTE_RUNTIME_MAX_INBOUND_REQUEST_JSON_BYTES - REQUEST_ENVELOPE_RESERVE_BYTES - -/** Reject oversized manifest requests before fencing: stage/state/full abort would all exceed the sealed frame and close its socket. */ -export function assertOrcadMigrationRequestFits(params: { - manifest: OrcadMigrationManifest -}): void { - if (!orcadMigrationRequestFits(params)) { - throw new Error( - describeOversizedOrcadMigrationPayload( - params.manifest.payload, - ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES - ) - ) - } -} - -export function orcadMigrationRequestFits(params: { manifest: OrcadMigrationManifest }): boolean { - return ( - Buffer.byteLength(JSON.stringify(params), 'utf8') <= ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES - ) -} - -/** Name the largest sections and how to trim the largest; a bare error code was unhelpful (#30126). */ -export function describeOversizedOrcadMigrationPayload( - payload: OrcadMigrationCatalogPayload, - limitBytes = MAX_ORCAD_MIGRATION_MANIFEST_BYTES -): string { - const dormant = payload.dormantState - const removeProjects = 'remove projects you no longer use from this host' - const closeTabs = 'close tabs you no longer need' - const parts: [words: string, value: unknown, trim: string][] = [ - ['projects', payload.repositories, removeProjects], - ['folder workspaces', payload.folderWorkspaces, removeProjects], - ['project groups', payload.projectGroups, removeProjects], - ['saved tabs and panes', dormant?.workspaceSession, closeTabs], - ['saved terminal history', dormant?.terminalScrollbackSnapshots, closeTabs], - ['saved workspace details', dormant?.worktreeMeta, 'delete workspaces you no longer need'], - [ - 'workspace history', - [dormant?.worktreeLineage, dormant?.workspaceLineage], - 'delete workspaces you no longer need' - ], - [ - 'sparse checkout presets', - dormant?.sparsePresets, - 'delete sparse checkout presets you no longer use' - ], - [ - 'retired workspace names', - [dormant?.retiredWorktreeNames, dormant?.retiredWorktreeNamespaces], - removeProjects - ], - [ - 'automations', - [dormant?.automations, dormant?.automationRuns], - "delete automations you no longer need from this host's projects" - ], - ['sidebar and browser settings', dormant?.clientState, closeTabs] - ] - const largest = parts - .map(([words, value, trim]) => ({ - words, - trim, - bytes: new TextEncoder().encode(JSON.stringify(value ?? null)).byteLength - })) - .sort((left, right) => right.bytes - left.bytes) - .slice(0, 3) - const { trim } = largest[0] - return ( - `This SSH host's saved state is too large to move to its Orca server (limit ` + - `${formatKib(limitBytes)}). Largest parts: ` + - `${largest.map(({ words, bytes }) => `${words} (${formatKib(bytes)})`).join(', ')}. ` + - `${trim.charAt(0).toUpperCase()}${trim.slice(1)}, then reconnect. ` + - `(${ORCAD_MIGRATION_MANIFEST_TOO_LARGE})` - ) -} - -function formatKib(bytes: number): string { - return `${Math.ceil(bytes / 1024)} KB` -} - export type OrcadMigrationCatalogIds = { repositoryIds: ReadonlySet folderWorkspaceIds: ReadonlySet @@ -289,20 +209,3 @@ function restrictCatalog( projectGroups: payload.projectGroups.filter((row) => ids.projectGroupIds.has(row.id)) } } - -export function hasDormantState(state: OrcadMigrationDormantStatePayload): boolean { - return ( - state.worktreeMeta.length > 0 || - state.worktreeLineage.length > 0 || - state.workspaceLineage.length > 0 || - state.sparsePresets.length > 0 || - state.retiredWorktreeNames.length > 0 || - state.retiredWorktreeNamespaces.length > 0 || - state.workspaceSession !== undefined || - (state.terminalScrollbackSnapshots?.length ?? 0) > 0 || - (state.automations?.length ?? 0) > 0 || - (state.automationRuns?.length ?? 0) > 0 || - state.automationRunHistory !== undefined || - (state.clientState !== undefined && Object.keys(state.clientState).length > 0) - ) -} diff --git a/src/main/ssh/orcad-migration-moved-automations.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-moved-automations.ts similarity index 92% rename from src/main/ssh/orcad-migration-moved-automations.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-moved-automations.ts index 8c3a4734f0c..47670d5999e 100644 --- a/src/main/ssh/orcad-migration-moved-automations.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-moved-automations.ts @@ -1,13 +1,13 @@ /** Moves carry automations disabled, which every server version accepts; re-enable those that ran here once the move commits. */ import { z } from 'zod' -import type { Automation } from '../../shared/automations/automation-definition' -import { isRetainedOrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' -import { parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' +import type { Automation } from '../../../shared/automations/automation-definition' +import { isRetainedOrcadMigrationSourceCutover } from '../../../shared/orcad-migration/orcad-migration-source-cutover' +import { parsePairingCode } from '../../../shared/remote-runtime/pairing/pairing' import { ORCAD_MIGRATION_DESTINATION_UNSUPPORTED, sendSupportedMigrationRequest, type CatalogRequestOptions -} from './orcad-migration-catalog-client' +} from '../../managed-server/migration/catalog/orcad-migration-request' import { listOrcadMigrationCutoverChainForTarget, listOrcadMigrationSourceCutovers, diff --git a/src/main/ssh/orcad-migration-rollback-mark.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-rollback-mark.ts similarity index 88% rename from src/main/ssh/orcad-migration-rollback-mark.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-rollback-mark.ts index b5688da9bdd..d2fe9e6535a 100644 --- a/src/main/ssh/orcad-migration-rollback-mark.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-rollback-mark.ts @@ -1,4 +1,4 @@ -import type { KnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' +import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { listOrcadMigrationSourceCutovers } from './orcad-migration-cutover-journal' /** Use the durable migration mark or older delta journal time; unreadable journals conservatively return now to block destructive rollback. */ diff --git a/src/main/ssh/orcad-migration-scrollback-retention-wiring.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-scrollback-retention-wiring.ts similarity index 93% rename from src/main/ssh/orcad-migration-scrollback-retention-wiring.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-scrollback-retention-wiring.ts index 28439bae62c..f6306da30f9 100644 --- a/src/main/ssh/orcad-migration-scrollback-retention-wiring.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-scrollback-retention-wiring.ts @@ -1,4 +1,4 @@ -import type { Store } from '../persistence/loading-store/store' +import type { Store } from '../loading-store/store' import { listOrcadMigrationSourceCutovers, setOrcadMigrationJournalChangeListener diff --git a/src/main/ssh/orcad-migration-source-retention.test.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.test.ts similarity index 95% rename from src/main/ssh/orcad-migration-source-retention.test.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.test.ts index 742e2f9526d..77876d701da 100644 --- a/src/main/ssh/orcad-migration-source-retention.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.test.ts @@ -3,16 +3,16 @@ 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 type { PersistedOpenFile } from '../../shared/workspace-session/workspace-session-state-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' +import type { Repo } from '../../../shared/repo-types' +import type { PersistedOpenFile } from '../../../shared/workspace-session/workspace-session-state-types' +import { closeTestStores, createSqliteTestStore } from '../persistence-test-harness' +import { Store } from '../loading-store/store' import { listOrcadMigrationSourceCutovers, writeOrcadMigrationSourceCutover } from './orcad-migration-cutover-journal' -import { orcadMigrationCutoverFixture } from './orcad-migration-cutover-fixture' -import { listPendingManagedOrcadMigrations } from '../managed-server/lifecycle/orcad-managed-migration-status' +import { orcadMigrationCutoverFixture } from '../../managed-server/migration/cutover/testing/orcad-migration-cutover-fixture' +import { listPendingManagedOrcadMigrations } from '../../managed-server/lifecycle/orcad-managed-migration-status' import { retainUnretainedOrcadMigrationSources, retainOrcadMigrationSource diff --git a/src/main/ssh/orcad-migration-source-retention.ts b/src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts similarity index 92% rename from src/main/ssh/orcad-migration-source-retention.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts index 020863c2314..1d30b6851c6 100644 --- a/src/main/ssh/orcad-migration-source-retention.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts @@ -1,9 +1,9 @@ /** Keep source rows for downgraded clients using their old relays; new clients hide them and serve managed state. Never delete retained rows automatically. */ -import { toRuntimeExecutionHostId } from '../../shared/execution-host' -import type { OrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import type { Store } from '../persistence/loading-store/store' -import { withRenamedOrcadMigrationDrafts } from '../persistence/migrating-orcad-catalog/orcad-source-draft-rename' +import { toRuntimeExecutionHostId } from '../../../shared/execution-host' +import type { OrcadMigrationSourceCutover } from '../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { Store } from '../loading-store/store' +import { withRenamedOrcadMigrationDrafts } from './orcad-source-draft-rename' import { listOrcadMigrationSourceCutovers, writeOrcadMigrationSourceCutover diff --git a/src/main/ssh/orcad-retained-source-changes.test.ts b/src/main/persistence/migrating-orcad-catalog/orcad-retained-source-changes.test.ts similarity index 91% rename from src/main/ssh/orcad-retained-source-changes.test.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-retained-source-changes.test.ts index 804c9a787a8..ae2a22eb826 100644 --- a/src/main/ssh/orcad-retained-source-changes.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-retained-source-changes.test.ts @@ -2,23 +2,23 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { Repo } from '../../shared/repo-types' -import type { SshTarget } from '../../shared/ssh-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' -import { SshConnectionStore } from './connection/ssh-connection-store' -import { orcadMigrationCutoverFixture } from './orcad-migration-cutover-fixture' +import type { Repo } from '../../../shared/repo-types' +import type { SshTarget } from '../../../shared/ssh-types' +import { closeTestStores, createSqliteTestStore } from '../persistence-test-harness' +import { Store } from '../loading-store/store' +import { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' +import { orcadMigrationCutoverFixture } from '../../managed-server/migration/cutover/testing/orcad-migration-cutover-fixture' import { findOrcadMigrationSourceCutoverForTarget, writeOrcadMigrationSourceCutover } from './orcad-migration-cutover-journal' -import { keepOrcadServerVersion } from './orcad-migration-delta-move' +import { keepOrcadServerVersion } from '../../managed-server/migration/cutover/orcad-migration-delta-move' import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' import { currentOrcadSourceFingerprint, - reconcileManagedOrcadSshTargets, - visibleRepos + reconcileManagedOrcadSshTargets } from './orcad-retained-source' +import { visibleRepos } from './orcad-source-visibility' const TARGET: SshTarget = { id: 'ssh-prod', diff --git a/src/main/ssh/orcad-retained-source-session.ts b/src/main/persistence/migrating-orcad-catalog/orcad-retained-source-session.ts similarity index 85% rename from src/main/ssh/orcad-retained-source-session.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-retained-source-session.ts index 9219aab48ee..4db77c86690 100644 --- a/src/main/ssh/orcad-retained-source-session.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-retained-source-session.ts @@ -1,6 +1,6 @@ -import { parseExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' -import type { Store } from '../persistence/loading-store/store' -import { appUserDataPath, hiddenRetainedSourceTargetIds } from './orcad-retained-source' +import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import type { Store } from '../loading-store/store' +import { appUserDataPath, hiddenRetainedSourceTargetIds } from './orcad-source-visibility' /** A hidden source's session goes with its repos: a window adopting it at startup brings closed tabs back (#33539). */ export function visibleSessionHostIds( diff --git a/src/main/ssh/orcad-retained-source.ts b/src/main/persistence/migrating-orcad-catalog/orcad-retained-source.ts similarity index 50% rename from src/main/ssh/orcad-retained-source.ts rename to src/main/persistence/migrating-orcad-catalog/orcad-retained-source.ts index 57e51438a60..60eae83fba7 100644 --- a/src/main/ssh/orcad-retained-source.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-retained-source.ts @@ -1,177 +1,27 @@ -/** Hide migrated rows while managed, retaining them for downgraded clients. Only newly added projects/folders mark sourceChangedAt and require explicit delta migration; edits/removals/groups never overwrite server state or trigger automatic merging. */ import { createHash } from 'node:crypto' -import { getAppEnvironment } from '../../shared/app-environment' -import { getRepoExecutionHostId, parseExecutionHostId } 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 { OrcadMigrationCatalogPayload } from '../../shared/orcad-migration/orcad-migration-manifest' +import type { OrcadMigrationCatalogPayload } from '../../../shared/orcad-migration/orcad-migration-manifest' import { MAX_ORCAD_MIGRATION_FOLDER_WORKSPACES, MAX_ORCAD_MIGRATION_REPOSITORIES -} from '../../shared/orcad-migration/orcad-migration-manifest-validation' +} from '../../../shared/orcad-migration/orcad-migration-manifest-fields' + +import { isRetainedOrcadMigrationSourceCutover } from '../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { OrcadMigrationSourceCutover } from '../../../shared/orcad-migration/orcad-migration-source-cutover' +import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getOrcadSshDeployment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import type { SshTarget } from '../../../shared/ssh-types' +import type { Store } from '../loading-store/store' +import { collectOrcadMigrationSourceCatalog } from './orcad-source-catalog' import { - isRetainedOrcadMigrationSourceCutover, - type OrcadMigrationSourceCutover -} from '../../shared/orcad-migration/orcad-migration-source-cutover' -import type { Repo } from '../../shared/repo-types' -import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { getOrcadSshDeployment } from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { SshTarget } from '../../shared/ssh-types' -import type { Store } from '../persistence/loading-store/store' -import { collectOrcadMigrationSourceCatalog } from '../persistence/migrating-orcad-catalog/orcad-source-catalog' -import { - orcadSourceFolderWorkspaceIds, - projectGroupBelongsToOrcadSource, - repoBelongsToOrcadSource -} from '../persistence/migrating-orcad-catalog/orcad-source-ownership' -import { - findOrcadMigrationSourceCutoverForTarget, listOrcadMigrationCutoverChainForTarget, writeOrcadMigrationSourceCutover } from './orcad-migration-cutover-journal' + import { orcadMigrationCatalogIds } from './orcad-migration-manifest-export' -import { - withoutWslMovedFolderWorkspaces, - withoutWslMovedRepos -} from '../persistence/moving-wsl-projects/wsl-move-scope-guard' +import type { CatalogStore } from './orcad-source-visibility' -export const appUserDataPath = (): string => getAppEnvironment().getPath('userData') - -type CatalogStore = Pick type TargetStore = Pick -/** Hide only retained committed source without later additions; in-flight or unjournaled fences leave source rows visible. */ -function isHiddenRetainedSourceTarget( - userDataPath: string, - target: Pick -): boolean { - if (!target.orcadFence || target.orcadFence.sourceChangedAt) { - return false - } - let head: OrcadMigrationSourceCutover | null - try { - head = findOrcadMigrationSourceCutoverForTarget(userDataPath, target.id) - } catch { - return true // An unreadable journal keeps the host fenced, and so hidden. - } - return ( - head !== null && - (head.phase === 'destination-committed' || - head.phase === 'source-retired' || - head.destinationEnvironmentId !== target.orcadFence.environmentId) - ) -} - -/** Delay journal reads until a host is fenced. */ -export function hiddenRetainedSourceTargetIds( - getUserDataPath: () => string, - targets: readonly SshTarget[] -): string[] { - return targets - .filter( - (target) => target.orcadFence && isHiddenRetainedSourceTarget(getUserDataPath(), target) - ) - .map((target) => target.id) -} - -/** Freeze fenced ssh: partitions: renderer saves could mutate in-flight source or strip retained rows after commit. */ -export function isFrozenOrcadSourceSessionPartition( - store: Pick, - hostId: string | null | undefined -): boolean { - const parsed = parseExecutionHostId(hostId) - const fence = parsed?.kind === 'ssh' ? store.getSshTarget(parsed.targetId)?.orcadFence : undefined - return fence !== undefined && !fence.sourceChangedAt -} - -export function visibleRepos( - store: CatalogStore & Pick, - getUserDataPath = appUserDataPath -): Repo[] { - return reposShownWith( - store.getRepos(), - hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) - ) -} - -function reposShownWith(allRepos: Repo[], hiddenTargets: readonly string[]): Repo[] { - const repos = withoutWslMovedRepos(allRepos) - if (hiddenTargets.length === 0) { - return repos - } - return repos.filter( - (repo) => !hiddenTargets.some((targetId) => repoBelongsToOrcadSource(repo, targetId)) - ) -} - -/** Keep local groups that merely contain host-owned projects. */ -export function visibleProjectGroups( - store: Pick, - getUserDataPath = appUserDataPath -): ProjectGroup[] { - const hidden = hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) - const groups = store.getProjectGroups() - if (hidden.length === 0) { - return groups - } - return groups.filter( - (group) => !hidden.some((targetId) => projectGroupBelongsToOrcadSource(group, targetId)) - ) -} - -export function visibleFolderWorkspaces( - store: CatalogStore & Pick, - getUserDataPath = appUserDataPath -): FolderWorkspace[] { - const hidden = hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) - const folderWorkspaces = withoutWslMovedFolderWorkspaces(store.getFolderWorkspaces()) - if (hidden.length === 0) { - return folderWorkspaces - } - const state = { - repos: store.getRepos(), - projectGroups: store.getProjectGroups(), - folderWorkspaces - } - const hiddenIds = new Set( - hidden.flatMap((targetId) => [...orcadSourceFolderWorkspaceIds(state, targetId)]) - ) - return folderWorkspaces.filter((workspace) => !hiddenIds.has(workspace.id)) -} - -/** Hide setups with their source repo rows so managed server listings do not duplicate same-id setups (#30859). */ -export function visibleProjectHostSetups( - store: CatalogStore & Pick, - getUserDataPath = appUserDataPath -): ProjectHostSetup[] { - const setups = store.getProjectHostSetups() - if (setups.length === 0) { - return setups - } - const hiddenTargets = hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) - const allRepos = store.getRepos() - const shownRepos = reposShownWith(allRepos, hiddenTargets) - if (hiddenTargets.length === 0 && shownRepos.length === allRepos.length) { - return setups - } - const rowKey = (hostId: string, repoId: string): string => `${hostId}\0${repoId}` - const shownKeys = new Set(shownRepos.map((repo) => rowKey(getRepoExecutionHostId(repo), repo.id))) - const hiddenKeys = new Set( - allRepos - .map((repo) => rowKey(getRepoExecutionHostId(repo), repo.id)) - .filter((key) => !shownKeys.has(key)) - ) - return setups.filter((setup) => { - if (setup.repoId && hiddenKeys.has(rowKey(setup.hostId, setup.repoId))) { - return false - } - // Repo-less placeholders have no row to follow, so the hidden host decides for them. - const host = parseExecutionHostId(setup.hostId) - return !(host?.kind === 'ssh' && hiddenTargets.includes(host.targetId)) - }) -} - /** Keep the identity-only fingerprint format stable for older builds; timestamps must not create source changes. */ export function orcadCatalogFingerprint(catalog: OrcadMigrationCatalogPayload): string { return createHash('sha256') diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-export.test.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-export.test.ts index cd663ee175b..db604d6e714 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-export.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-export.test.ts @@ -8,7 +8,7 @@ import type { SshTarget } from '../../../shared/ssh-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { closeTestStores, createSqliteTestStore } from '../persistence-test-harness' import { Store } from '../loading-store/store' -import { createOrcadMigrationManifest } from '../../ssh/orcad-migration-manifest-export' +import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' import { getProfileTerminalScrollbackSnapshotRoot, readTerminalScrollbackStoredBytesSync, diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts index 4cd8d92eb7c..8b779a9acb0 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.test.ts @@ -3,7 +3,7 @@ import { getDefaultPersistedState } from '../../../shared/constants' import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' import type { ProjectGroup } from '../../../shared/project-group-types' import type { Repo } from '../../../shared/repo-types' -import { orcadMigrationCutoverFixture } from '../../ssh/orcad-migration-cutover-fixture' +import { orcadMigrationCutoverFixture } from '../../managed-server/migration/cutover/testing/orcad-migration-cutover-fixture' import { subtractOrcadSourceCatalogState } from './orcad-source-catalog-subtraction' import { orcadSourceFolderWorkspaceIds, repoBelongsToOrcadSource } from './orcad-source-ownership' diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-visibility.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-visibility.ts new file mode 100644 index 00000000000..02477471d99 --- /dev/null +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-visibility.ts @@ -0,0 +1,156 @@ +import { getAppEnvironment } from '../../../shared/app-environment' +import { getRepoExecutionHostId, parseExecutionHostId } 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 { OrcadMigrationSourceCutover } from '../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { Repo } from '../../../shared/repo-types' +import type { SshTarget } from '../../../shared/ssh-types' +import type { Store } from '../loading-store/store' +import { + orcadSourceFolderWorkspaceIds, + projectGroupBelongsToOrcadSource, + repoBelongsToOrcadSource +} from './orcad-source-ownership' + +import { findOrcadMigrationSourceCutoverForTarget } from './orcad-migration-cutover-journal' +import { + withoutWslMovedFolderWorkspaces, + withoutWslMovedRepos +} from '../moving-wsl-projects/wsl-move-scope-guard' + +export const appUserDataPath = (): string => getAppEnvironment().getPath('userData') + +export type CatalogStore = Pick + +/** Hide only retained committed source without later additions; in-flight or unjournaled fences leave source rows visible. */ +function isHiddenRetainedSourceTarget( + userDataPath: string, + target: Pick +): boolean { + if (!target.orcadFence || target.orcadFence.sourceChangedAt) { + return false + } + let head: OrcadMigrationSourceCutover | null + try { + head = findOrcadMigrationSourceCutoverForTarget(userDataPath, target.id) + } catch { + return true // An unreadable journal keeps the host fenced, and so hidden. + } + return ( + head !== null && + (head.phase === 'destination-committed' || + head.phase === 'source-retired' || + head.destinationEnvironmentId !== target.orcadFence.environmentId) + ) +} + +/** Delay journal reads until a host is fenced. */ +export function hiddenRetainedSourceTargetIds( + getUserDataPath: () => string, + targets: readonly SshTarget[] +): string[] { + return targets + .filter( + (target) => target.orcadFence && isHiddenRetainedSourceTarget(getUserDataPath(), target) + ) + .map((target) => target.id) +} + +/** Freeze fenced ssh: partitions: renderer saves could mutate in-flight source or strip retained rows after commit. */ +export function isFrozenOrcadSourceSessionPartition( + store: Pick, + hostId: string | null | undefined +): boolean { + const parsed = parseExecutionHostId(hostId) + const fence = parsed?.kind === 'ssh' ? store.getSshTarget(parsed.targetId)?.orcadFence : undefined + return fence !== undefined && !fence.sourceChangedAt +} + +export function visibleRepos( + store: CatalogStore & Pick, + getUserDataPath = appUserDataPath +): Repo[] { + return reposShownWith( + store.getRepos(), + hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) + ) +} + +function reposShownWith(allRepos: Repo[], hiddenTargets: readonly string[]): Repo[] { + const repos = withoutWslMovedRepos(allRepos) + if (hiddenTargets.length === 0) { + return repos + } + return repos.filter( + (repo) => !hiddenTargets.some((targetId) => repoBelongsToOrcadSource(repo, targetId)) + ) +} + +/** Keep local groups that merely contain host-owned projects. */ +export function visibleProjectGroups( + store: Pick, + getUserDataPath = appUserDataPath +): ProjectGroup[] { + const hidden = hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) + const groups = store.getProjectGroups() + if (hidden.length === 0) { + return groups + } + return groups.filter( + (group) => !hidden.some((targetId) => projectGroupBelongsToOrcadSource(group, targetId)) + ) +} + +export function visibleFolderWorkspaces( + store: CatalogStore & Pick, + getUserDataPath = appUserDataPath +): FolderWorkspace[] { + const hidden = hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) + const folderWorkspaces = withoutWslMovedFolderWorkspaces(store.getFolderWorkspaces()) + if (hidden.length === 0) { + return folderWorkspaces + } + const state = { + repos: store.getRepos(), + projectGroups: store.getProjectGroups(), + folderWorkspaces + } + const hiddenIds = new Set( + hidden.flatMap((targetId) => [...orcadSourceFolderWorkspaceIds(state, targetId)]) + ) + return folderWorkspaces.filter((workspace) => !hiddenIds.has(workspace.id)) +} + +/** Hide setups with their source repo rows so managed server listings do not duplicate same-id setups (#30859). */ +export function visibleProjectHostSetups( + store: CatalogStore & Pick, + getUserDataPath = appUserDataPath +): ProjectHostSetup[] { + const setups = store.getProjectHostSetups() + if (setups.length === 0) { + return setups + } + const hiddenTargets = hiddenRetainedSourceTargetIds(getUserDataPath, store.getSshTargets()) + const allRepos = store.getRepos() + const shownRepos = reposShownWith(allRepos, hiddenTargets) + if (hiddenTargets.length === 0 && shownRepos.length === allRepos.length) { + return setups + } + const rowKey = (hostId: string, repoId: string): string => `${hostId}\0${repoId}` + const shownKeys = new Set(shownRepos.map((repo) => rowKey(getRepoExecutionHostId(repo), repo.id))) + const hiddenKeys = new Set( + allRepos + .map((repo) => rowKey(getRepoExecutionHostId(repo), repo.id)) + .filter((key) => !shownKeys.has(key)) + ) + return setups.filter((setup) => { + if (setup.repoId && hiddenKeys.has(rowKey(setup.hostId, setup.repoId))) { + return false + } + // Repo-less placeholders have no row to follow, so the hidden host decides for them. + const host = parseExecutionHostId(setup.hostId) + return !(host?.kind === 'ssh' && hiddenTargets.includes(host.targetId)) + }) +} diff --git a/src/main/ssh/orcad-migration-path-fields.ts b/src/main/persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-fields.ts similarity index 100% rename from src/main/ssh/orcad-migration-path-fields.ts rename to src/main/persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-fields.ts diff --git a/src/main/ssh/orcad-migration-path-rewrite.ts b/src/main/persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite.ts similarity index 92% rename from src/main/ssh/orcad-migration-path-rewrite.ts rename to src/main/persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite.ts index 2b4d59c30c2..a263fd4a92c 100644 --- a/src/main/ssh/orcad-migration-path-rewrite.ts +++ b/src/main/persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite.ts @@ -1,9 +1,9 @@ /** Rewrite differing source/destination paths, such as WSL via \wsl.localhost; SSH identity rewriting must preserve payload bytes. */ -import type { OrcadMigrationCatalogPayload } from '../../shared/orcad-migration/orcad-migration-manifest' -import { isRecord } from '../../shared/orcad-migration/orcad-migration-manifest-fields' -import { PTY_SESSION_ID_SEPARATOR } from '../../shared/terminal/pty/lifecycle/pty-session-id-format' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { rewriteWorktreeIdPath } from '../../shared/worktree/id' +import type { OrcadMigrationCatalogPayload } from '../../../../shared/orcad-migration/orcad-migration-manifest' +import { isRecord } from '../../../../shared/orcad-migration/orcad-migration-manifest-fields' +import { PTY_SESSION_ID_SEPARATOR } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' +import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { rewriteWorktreeIdPath } from '../../../../shared/worktree/id' import { ORCAD_MIGRATION_PATH_FIELDS, type OrcadMigrationPathFieldKind, diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-desktop-rewrite-stores.ts b/src/main/persistence/moving-wsl-projects/wsl-move-desktop-rewrite-stores.ts index c40679da108..19120ba8f3f 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-desktop-rewrite-stores.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-desktop-rewrite-stores.ts @@ -1,7 +1,7 @@ // Record each store only after durable rewrite so crashes retry the unfinished stores. import type { WslMoveCutover } from '../../../shared/wsl-move/wsl-move-cutover' import { WSL_MOVE_RENDERER_REWRITE_STORE_IDS } from '../../../shared/wsl-move/wsl-move-renderer-rewrite-types' -import type { OrcadMigrationPathRewriter } from '../../ssh/orcad-migration-path-rewrite' +import type { OrcadMigrationPathRewriter } from '../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' export type WslMoveDesktopRewriteContext = { cutover: Readonly diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-driver-ports.ts b/src/main/persistence/moving-wsl-projects/wsl-move-driver-ports.ts index 1931cf9bb5a..c34b7a4fbfd 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-driver-ports.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-driver-ports.ts @@ -15,9 +15,9 @@ import type { WslMoveProgressEvent } from '../../../shared/wsl-move/wsl-move-dri import type { OrcadMigrationBlobDestination, OrcadMigrationBlobSource -} from '../../ssh/orcad-migration-blob-coordinator' -import type { OrcadMigrationDestinationCatalog } from '../../ssh/orcad-migration-cutover-coordinator' -import type { OrcadMigrationSnapshotSource } from '../../ssh/orcad-migration-snapshot-coordinator' +} from '../../managed-server/migration/transfers/orcad-migration-blob-coordinator' +import type { OrcadMigrationDestinationCatalog } from '../../managed-server/migration/cutover/orcad-migration-cutover-coordinator' +import type { OrcadMigrationSnapshotSource } from '../../managed-server/migration/transfers/orcad-migration-snapshot-coordinator' import type { WslMoveHostHolding } from './wsl-move-delta-plan' import type { WslMoveQuiesceDeps } from './wsl-move-quiesce' import type { WslMoveSleptScrollback } from './wsl-move-slept-scrollback' diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-driver-transfer.ts b/src/main/persistence/moving-wsl-projects/wsl-move-driver-transfer.ts index 973edc3a269..28de35a3b9a 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-driver-transfer.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-driver-transfer.ts @@ -9,9 +9,9 @@ import type { WslMoveCutover, WslMoveCutoverPhase } from '../../../shared/wsl-mo import { transferOrcadMigrationBlobs, type OrcadMigrationBlobSource -} from '../../ssh/orcad-migration-blob-coordinator' -import { resolveDurableOrcadCatalogMutation } from '../../ssh/orcad-catalog-durable-mutation' -import { transferOrcadMigrationSnapshots } from '../../ssh/orcad-migration-snapshot-coordinator' +} from '../../managed-server/migration/transfers/orcad-migration-blob-coordinator' +import { resolveDurableOrcadCatalogMutation } from '../../managed-server/migration/cutover/orcad-catalog-durable-mutation' +import { transferOrcadMigrationSnapshots } from '../../managed-server/migration/transfers/orcad-migration-snapshot-coordinator' import { writeWslMoveCutover } from './wsl-move-cutover-journal' import type { WslMoveDriverDeps, WslMoveHost, WslMoveManifestExport } from './wsl-move-driver-ports' import { assertWslMoveCommitRequestAllowed } from './wsl-move-reset' diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-manifest-budget.ts b/src/main/persistence/moving-wsl-projects/wsl-move-manifest-budget.ts index faf538ce332..422a6501737 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-manifest-budget.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-manifest-budget.ts @@ -4,7 +4,7 @@ * Capping it when the move is recorded keeps new moves out of that gap entirely. */ import type { OrcadMigrationManifest } from '../../../shared/orcad-migration/orcad-migration-manifest' -import { ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES } from '../../ssh/orcad-migration-manifest-export' +import { ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES } from '../../managed-server/migration/catalog/orcad-migration-request-budget' // Headroom for a host whose request limit is a little lower than this build's. const WSL_MOVE_MANIFEST_MARGIN_BYTES = 16 * 1024 diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-manifest-export.ts b/src/main/persistence/moving-wsl-projects/wsl-move-manifest-export.ts index 41857cc0c4a..e281aca3eff 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-manifest-export.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-manifest-export.ts @@ -24,11 +24,11 @@ import type { Repo } from '../../../shared/repo-types' import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { getRepoIdFromWorktreeId, getRepoMainWorktreeId } from '../../../shared/worktree/id' import { computeOrcadMigrationManifestSha256 } from '../../orcad/orcad-migration-manifest-digest' -import { hasDormantState } from '../../ssh/orcad-migration-manifest-export' +import { hasDormantState } from '../migrating-orcad-catalog/orcad-migration-dormant-state' import { rewriteOrcadMigrationPayloadPaths, rewriteOrcadMigrationWorktreeId -} from '../../ssh/orcad-migration-path-rewrite' +} from '../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' import type { Store } from '../loading-store/store' import { compareKeys } from '../migrating-orcad-catalog/orcad-source-key-order' import { wslUncPathToLinux } from '../../../shared/wsl-paths' diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-owed-host-aborts.ts b/src/main/persistence/moving-wsl-projects/wsl-move-owed-host-aborts.ts index 7b10d892a90..1c0c9161a3c 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-owed-host-aborts.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-owed-host-aborts.ts @@ -8,7 +8,7 @@ import type { OrcadMigrationCatalogReferenceAbortResult } from '../../../shared/ import { isRecord } from '../../../shared/orcad-migration/orcad-migration-manifest-fields' import type { WslMoveCutover } from '../../../shared/wsl-move/wsl-move-cutover' import { createMigrationJournalDirectory } from '../migrating-orcad-catalog/migration-journal-directory' -import type { OrcadMigrationDestinationCatalog } from '../../ssh/orcad-migration-cutover-coordinator' +import type { OrcadMigrationDestinationCatalog } from '../../managed-server/migration/cutover/orcad-migration-cutover-coordinator' export type WslMoveOwedHostAbort = { migrationId: string diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-path-rewriter.ts b/src/main/persistence/moving-wsl-projects/wsl-move-path-rewriter.ts index 938c25646fd..b069283ba1f 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-path-rewriter.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-path-rewriter.ts @@ -1,6 +1,6 @@ // Convert only the moved distro's UNC paths; unrelated paths remain unchanged. import { wslUncPathToLinux } from '../../../shared/wsl-paths' -import type { OrcadMigrationPathRewriter } from '../../ssh/orcad-migration-path-rewrite' +import type { OrcadMigrationPathRewriter } from '../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' export function createUncToLinuxPathRewriter(distro: string): OrcadMigrationPathRewriter { const fileUrl = new RegExp(`^file://(?:wsl\\.localhost|wsl\\$)/([^/]+)(/.*)?$`, 'i') diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-reset.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-reset.test.ts index 5e8bb5181a3..88f1902aae1 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-reset.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-reset.test.ts @@ -9,12 +9,12 @@ import type { } from '../../../shared/orcad-migration/orcad-migration-manifest' import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../shared/wsl-host-internal-gate' import type { WslMoveCutoverPhase } from '../../../shared/wsl-move/wsl-move-cutover' -import type { OrcadMigrationDestinationCatalog } from '../../ssh/orcad-migration-cutover-coordinator' +import type { OrcadMigrationDestinationCatalog } from '../../managed-server/migration/cutover/orcad-migration-cutover-coordinator' import { MAX_ORCAD_MIGRATION_MANIFEST_BYTES } from '../../../shared/orcad-migration/orcad-migration-manifest-validation' import { ORCAD_MIGRATION_REQUEST_PARAMS_BUDGET_BYTES, orcadMigrationRequestFits -} from '../../ssh/orcad-migration-manifest-export' +} from '../../managed-server/migration/catalog/orcad-migration-request-budget' import { computeOrcadMigrationManifestSha256 } from '../../orcad/orcad-migration-manifest-digest' import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutover-fixture' import { seedWslMoveCutover } from '../__fixtures__/wsl-mover/wsl-move-journal-seeding' diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-reset.ts b/src/main/persistence/moving-wsl-projects/wsl-move-reset.ts index 2c658a81d4a..7509d861e2e 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-reset.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-reset.ts @@ -20,8 +20,8 @@ import { abortWithRecovery, confirmDurableCommit, type OrcadMigrationDestinationCatalog -} from '../../ssh/orcad-migration-cutover-coordinator' -import { orcadMigrationRequestFits } from '../../ssh/orcad-migration-manifest-export' +} from '../../managed-server/migration/cutover/orcad-migration-cutover-coordinator' +import { orcadMigrationRequestFits } from '../../managed-server/migration/catalog/orcad-migration-request-budget' import { wslHostsServing } from '../../wsl/host-lifecycle/wsl-host-gate' import { listWslMoveCutovers, diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-restore-hints-blob.ts b/src/main/persistence/moving-wsl-projects/wsl-move-restore-hints-blob.ts index 051835546c7..caa88208722 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-restore-hints-blob.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-restore-hints-blob.ts @@ -8,7 +8,7 @@ import { parseOrcadMigrationTerminalRestoreHintsDocument, type OrcadMigrationTerminalRestoreHint } from '../../../shared/orcad-migration/orcad-migration-terminal-restore-hints' -import type { OrcadMigrationBlobSource } from '../../ssh/orcad-migration-blob-coordinator' +import type { OrcadMigrationBlobSource } from '../../managed-server/migration/transfers/orcad-migration-blob-coordinator' export type WslMoveRestoreHintsBlob = { descriptor: OrcadMigrationBlobDescriptor diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-retention.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-retention.test.ts index 3786b564c73..9682d72414a 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-retention.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-retention.test.ts @@ -16,7 +16,10 @@ import { testState, writeDataFile } from '../persistence-test-harness' -import { visibleFolderWorkspaces, visibleRepos } from '../../ssh/orcad-retained-source' +import { + visibleFolderWorkspaces, + visibleRepos +} from '../migrating-orcad-catalog/orcad-source-visibility' import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutover-fixture' import { seedWslMoveCutover } from '../__fixtures__/wsl-mover/wsl-move-journal-seeding' import { listWslMoveCutovers, wslMoveJournalDirectory } from './wsl-move-cutover-journal' diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-scope.ts b/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-scope.ts index 1347dfb0a3f..9acb4dfa2b1 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-scope.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-scope.ts @@ -8,7 +8,7 @@ import { normalizeWorkspaceSessionKeyToWorkspaceId, parseWorkspaceKey } from '../../../shared/workspace-scope' -import { rewriteOrcadMigrationWorktreeId } from '../../ssh/orcad-migration-path-rewrite' +import { rewriteOrcadMigrationWorktreeId } from '../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' import type { WslMoveDesktopRewriteContext } from './wsl-move-desktop-rewrite-stores' export type WslMoveRewriteScope = { diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.test.ts index cfd8e999717..c2e4a320c1c 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.test.ts @@ -15,7 +15,7 @@ import { parseOrcadMigrationBlobDescriptor, type OrcadMigrationBlobDescriptor } from '../../../shared/orcad-migration/orcad-migration-blob-transfer' -import { rewriteOrcadMigrationWorktreeId } from '../../ssh/orcad-migration-path-rewrite' +import { rewriteOrcadMigrationWorktreeId } from '../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' import { hashWorktreeId } from '../../pty/history/terminal-history-id' import { parseOrcadMigrationShellHistoryHeader } from '../migrating-orcad-catalog/orcad-migration-shell-history-format' import { createUncToLinuxPathRewriter } from './wsl-move-path-rewriter' diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.ts b/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.ts index 47a6cee4ccd..7ff6233c745 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-shell-history-blobs.ts @@ -9,7 +9,7 @@ import { sameOrcadMigrationBlob, type OrcadMigrationBlobDescriptor } from '../../../shared/orcad-migration/orcad-migration-blob-transfer' -import type { OrcadMigrationBlobSource } from '../../ssh/orcad-migration-blob-coordinator' +import type { OrcadMigrationBlobSource } from '../../managed-server/migration/transfers/orcad-migration-blob-coordinator' import { getHistoryRootWsl } from '../../pty/history/terminal-history-paths' import { hashWorktreeId } from '../../pty/history/terminal-history-id' import { diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-slept-scrollback.ts b/src/main/persistence/moving-wsl-projects/wsl-move-slept-scrollback.ts index 9b9432c2e5c..2b110a8f25f 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-slept-scrollback.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-slept-scrollback.ts @@ -26,7 +26,7 @@ import { parsePtySessionId } from '../../../shared/terminal/pty/lifecycle/pty-se import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' import type { ColdRestoreInfo } from '../../daemon/history/restoration/terminal-history-cold-restore-info' import type { TerminalCheckpointFile } from '../../daemon/protocol/daemon-checkpoint-file' -import type { OrcadMigrationBlobSource } from '../../ssh/orcad-migration-blob-coordinator' +import type { OrcadMigrationBlobSource } from '../../managed-server/migration/transfers/orcad-migration-blob-coordinator' import { orcadMigrationTerminalHistoryKey } from '../migrating-orcad-catalog/orcad-terminal-history-installer' import type { WslMoveDriverDeps } from './wsl-move-driver-ports' import { diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts b/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts index d80eddd87fa..3a7d2672515 100644 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts +++ b/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts @@ -11,7 +11,7 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import type { SshTarget } from '../../../shared/ssh-types' import { isRemoteCliControlAllowed } from '../../../shared/ssh-remote-cli-control' -import { SshConnectionStore } from '../../ssh/connection/ssh-connection-store' +import { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' vi.mock('../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: vi.fn(), diff --git a/src/main/pi/rpc-failure-cleanup.ts b/src/main/pi/rpc-failure-cleanup.ts new file mode 100644 index 00000000000..b9837979770 --- /dev/null +++ b/src/main/pi/rpc-failure-cleanup.ts @@ -0,0 +1,25 @@ +import type { StructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' +import type { PiRpcSession } from './rpc-session' + +export function closeFailedPiSession( + session: Pick, + logger: StructuredAgentSessionLogger +): void { + void session + .close(false) + .then((result) => { + if (result.root !== 'exited' && !result.killDelivered) { + logger.warn('Pi process exit is unverifiable', { + scope: 'pi-stop', + sessionId: session.input.identity.sessionId + }) + } + }) + .catch((cause: unknown) => + logger.error('Pi process cleanup failed', { + scope: 'pi-stop', + sessionId: session.input.identity.sessionId, + error: cause + }) + ) +} diff --git a/src/main/pi/rpc-session-startup.test.ts b/src/main/pi/rpc-session-startup.test.ts index 496d5fb685e..6469812f8d1 100644 --- a/src/main/pi/rpc-session-startup.test.ts +++ b/src/main/pi/rpc-session-startup.test.ts @@ -1,30 +1,110 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { readFileSync } from 'node:fs' +import { PassThrough } from 'node:stream' +import { JsonlRpcPeer } from '../jsonl-rpc/peer' +import { afterEach, describe, expect, it, vi } from 'vitest' import { closePiRpcAdapterFixtures, + type FakeConnection, restart, sessionId, - setup, - state + setup } from './rpc-session-adapter.test-fixture' -afterEach(closePiRpcAdapterFixtures) +function openAt8(h: Awaited>, acquisitionGeneration: string) { + return h.adapter.open({ + sessionId, + fence: 8, + acquisitionGeneration, + signal: new AbortController().signal + }) +} + +const recordedState = readFileSync( + new URL('./__fixtures__/command-only.jsonl', import.meta.url), + 'utf8' +) + .trim() + .split('\n') + .map((line) => JSON.parse(JSON.parse(line).raw)) + .find((frame) => frame.type === 'response' && frame.command === 'get_state') + +function stateThroughPeer(connection: FakeConnection) { + const input = new PassThrough() + const output = new PassThrough() + const peer = new JsonlRpcPeer(input, output) + let requestId: string + output.on('data', (chunk) => { + requestId = JSON.parse(String(chunk)).id + }) + const request = connection.request.bind(connection) + connection.request = (command, params, options?: Parameters[2]) => + command === 'get_state' ? peer.request(command, params, options) : request(command, params) + connection.abortRequest = () => peer.close() + return () => input.write(`${JSON.stringify({ ...recordedState, id: requestId })}\n`) +} + +afterEach(async () => { + await closePiRpcAdapterFixtures() + vi.useRealTimers() +}) describe('Pi host awaited open', () => { - it('fails an open if its lane fails while the state request is pending', async () => { + it('opens on Pi state received after the transport default would expire', async () => { const h = await setup() - const stateReply = Promise.withResolvers() + vi.useFakeTimers() + let reply!: () => unknown const { acquired, child } = await restart(h, (connection) => { - connection.requestOverride = (command) => - command === 'get_state' ? stateReply.promise : undefined + reply = stateThroughPeer(connection) }) - const opening = h.adapter.open({ + const opened = expect(openAt8(h, acquired.acquisitionGeneration)).resolves.toMatchObject({ + reportedOptions: { model: 'openai-codex/gpt-6.1-sol', effort: 'medium' } + }) + await vi.advanceTimersByTimeAsync(31_000) + reply() + await opened + await h.adapter.dispatch({ sessionId, fence: 8, - acquisitionGeneration: acquired.acquisitionGeneration ?? null, - signal: new AbortController().signal + clientMessageId: 'slow-start', + executionOptions: {}, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } }) - child.handlers.onClose?.(new Error('lane failed during startup')) - stateReply.resolve(state) - await expect(opening).rejects.toThrow('lane failed during startup') + expect(child.sent).toMatchObject([{ type: 'prompt', message: 'hello' }]) + }) + + it('fails an open if its lane fails while the state request is pending', async () => { + let refuse = false + const h = await setup({}, (sink) => ({ + ...sink, + tryAppendTransition: (transition) => + refuse ? { accepted: false, reason: 'failed' } : sink.tryAppendTransition!(transition) + })) + let reply!: () => unknown + const { acquired, child } = await restart(h, (connection) => { + reply = stateThroughPeer(connection) + }) + const opening = openAt8(h, acquired.acquisitionGeneration) + refuse = true + child.receive({ + type: 'extension_ui_request', + id: 'startup-confirm', + method: 'confirm', + title: 'Continue?', + message: 'Ready?' + }) + await expect(opening).rejects.toMatchObject({ message: 'failed', retry: 'never' }) + refuse = false + reply() + await expect(openAt8(h, acquired.acquisitionGeneration)).rejects.toThrow('failed') + await expect( + h.adapter.dispatch({ + sessionId, + fence: 8, + clientMessageId: 'failed-start', + executionOptions: {}, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } + }) + ).rejects.toThrow('Pi session is not live') + expect(child.sent).not.toContainEqual(expect.objectContaining({ type: 'prompt' })) }) }) diff --git a/src/main/pi/rpc-session-startup.ts b/src/main/pi/rpc-session-startup.ts index b88792dacd3..4f7582fd341 100644 --- a/src/main/pi/rpc-session-startup.ts +++ b/src/main/pi/rpc-session-startup.ts @@ -35,6 +35,7 @@ export class PiRpcSessionStartup { private readonly resolvesConfig: boolean, private readonly setState: (state: PiRpcState) => void, private readonly failedCause: () => Error | undefined, + private readonly failed: Promise, private readonly prepareObservation: () => (options: AgentSessionOptionsResult) => boolean ) {} @@ -42,7 +43,10 @@ export class PiRpcSessionStartup { launch: PiRpcResolvedLaunch, signal: AbortSignal ): Promise { - const answer = await this.wait(this.connection.request('get_state', {}), signal) + const answer = await this.wait( + this.connection.request('get_state', {}, { timeoutMs: null }), + signal + ) this.assertLive(signal) const state = piRpcStateSchema.parse(answer) if (state.model?.provider === 'unknown') { @@ -160,7 +164,7 @@ export class PiRpcSessionStartup { } } - private assertLive(signal: AbortSignal): void { + assertLive(signal: AbortSignal): void { const failure = this.failedCause() if (failure) { throw failure @@ -171,7 +175,8 @@ export class PiRpcSessionStartup { } private wait(promise: Promise, signal: AbortSignal): Promise { - return waitForPromiseWithSignal(promise, signal) + // Race the raw reply so a received refusal precedes a close from the same input frame. + return waitForPromiseWithSignal(Promise.race([promise, this.failed]), signal) } private notSignedIn(): AgentSessionAcquisitionRefusal { diff --git a/src/main/pi/rpc-session.ts b/src/main/pi/rpc-session.ts index f73728a1b31..c26fe77267b 100644 --- a/src/main/pi/rpc-session.ts +++ b/src/main/pi/rpc-session.ts @@ -21,6 +21,7 @@ import type { StructuredAgentSessionProviderOpenResult } from '../native-chat/ag import type { AgentSessionProviderHandleLink } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' import { PiRpcSessionStartup } from './rpc-session-startup' import { PiHistoryCapture, type PiHistoryCaptureDeps } from './rpc-history-capture' +import { closeFailedPiSession } from './rpc-failure-cleanup' export type PiRpcConnection = Pick< JsonlRpcAgentConnection, @@ -75,6 +76,7 @@ export class PiRpcSession { private publishedExit = false /** What ended this child, once something did. */ failure?: Error + private readonly startupFailure = Promise.withResolvers() private exitDelivery: Promise = Promise.resolve() private releaseAfterExit?: () => void private readonly reading = new ReaderPauseHolds<'lane' | 'journal'>(() => this.connection) @@ -89,6 +91,7 @@ export class PiRpcSession { /** A new Pi session starts on its config's model; a resumed or forked one keeps its own. */ readonly resolvesConfig = false ) { + void this.startupFailure.promise.catch(() => {}) const sink = input.events && providerTimelineSink(input.events) if (!sink) { throw new Error('Pi structured chat requires the shared timeline sink') @@ -166,6 +169,7 @@ export class PiRpcSession { this.optionObservations.seed(state) }, () => this.failure, + this.startupFailure.promise, () => this.optionObservations.prepare() ) } @@ -184,7 +188,9 @@ export class PiRpcSession { } async open(signal: AbortSignal): Promise { + this.startup.assertLive(signal) const result = await this.startup.run(this.resolvedLaunch, signal) + this.startup.assertLive(signal) // Startup replies stay readable; journal pressure paces only later output. if (!this.publishedExit) { this.unbindReadingControl = this.input.events?.bindReadingControl?.( @@ -214,6 +220,7 @@ export class PiRpcSession { fail(error: Error): void { this.failure ??= error + this.startupFailure.reject(this.failure) this.deps.logger.error('Pi RPC session failed', { scope: 'pi-rpc', sessionId: this.input.identity.sessionId, @@ -222,22 +229,7 @@ export class PiRpcSession { if (!this.openedLink) { return } - void this.close(false) - .then((result) => { - if (result.root !== 'exited' && !result.killDelivered) { - this.deps.logger.warn('Pi process exit is unverifiable', { - scope: 'pi-stop', - sessionId: this.input.identity.sessionId - }) - } - }) - .catch((cause: unknown) => - this.deps.logger.error('Pi process cleanup failed', { - scope: 'pi-stop', - sessionId: this.input.identity.sessionId, - error: cause - }) - ) + closeFailedPiSession(this, this.deps.logger) } drainObservedExit(): Promise { diff --git a/src/main/runtime/client/events/runtime-notifier-contract.ts b/src/main/runtime/client/events/runtime-notifier-contract.ts index 910e00ed84a..a39b6216384 100644 --- a/src/main/runtime/client/events/runtime-notifier-contract.ts +++ b/src/main/runtime/client/events/runtime-notifier-contract.ts @@ -34,6 +34,10 @@ import type { RuntimeTerminalDriverState } from '../../../../shared/runtime-session-contracts' import type { RuntimeTerminalPresentation } from '../../../../shared/runtime-terminal-contracts' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../../shared/agent-status/presentation/agent-list-status' type DriverState = RuntimeTerminalDriverState @@ -174,6 +178,8 @@ export type RuntimeNotifier = { workspaceSleepChanged?(notice: WorkspaceSleepNotice): void // Only the host renderer owns slept-agent wake records; phones request navigation-free wake through this optional bridge. resumeSleepingAgents?(worktreeId: string): void + /** The window applies a client's Agents-list change with its own actions and answers with the verdicts it leaves. */ + applyAgentPaneActivity?(change: AgentPaneActivityChange): Promise terminalFitOverrideChanged( ptyId: string, mode: 'mobile-fit' | 'remote-desktop-fit' | 'desktop-fit', diff --git a/src/main/runtime/client/runtime-client-state.ts b/src/main/runtime/client/runtime-client-state.ts index 323c1b20c2d..d2e6570e368 100644 --- a/src/main/runtime/client/runtime-client-state.ts +++ b/src/main/runtime/client/runtime-client-state.ts @@ -17,6 +17,11 @@ import { killAllProcessesForWorktree } from '../workspaces/removal/worktree-tear import type { MemorySnapshot, StatsSummary } from '../../../shared/process-stats-types' import { collectMemorySnapshot } from '../../memory/collector' import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import { isDeepStrictEqual } from 'node:util' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../shared/agent-status/presentation/agent-list-status' import type { FeatureInteractionId } from '../../../shared/feature-interaction-catalog' import type { RuntimeClientSettingsUpdate } from './settings/runtime-client-settings-shape' import type { AgentLaunchSettingsMutation } from '../../../shared/agent-launch/choices/agent-launch-settings' @@ -190,6 +195,29 @@ export abstract class OrcaRuntimeWithPtyForegroundProcessReads extends OrcaRunti return this.store.getUI() } + /** The live desktop window's Agents-list verdicts; null with no window, so worktree.ps claims none. */ + private agentListPublication: AgentListPublication | null = null + + readAgentListPublication(): AgentListPublication | null { + return this.agentListPublication + } + + setAgentListPublication(next: AgentListPublication | null): void { + const changed = !isDeepStrictEqual(this.agentListPublication?.verdicts, next?.verdicts) + this.agentListPublication = next + if (changed) { + this.emitClientEvent({ type: 'agentListChanged' }) + } + } + + /** Applies through the window's own Activity actions and keeps the verdicts it answers with, so the next worktree.ps already shows them. */ + async applyAgentPaneActivity(change: AgentPaneActivityChange): Promise { + if (!this.notifier?.applyAgentPaneActivity) { + throw new Error('agent_activity_needs_desktop_window') + } + this.setAgentListPublication(await this.notifier.applyAgentPaneActivity(change)) + } + recordFeatureInteraction(id: FeatureInteractionId): PersistedUIState { if (!this.store?.recordFeatureInteraction) { throw new Error('runtime_unavailable') diff --git a/src/main/runtime/client/settings/runtime-settings-change-events.test.ts b/src/main/runtime/client/settings/runtime-settings-change-events.test.ts new file mode 100644 index 00000000000..ddaee15f4b7 --- /dev/null +++ b/src/main/runtime/client/settings/runtime-settings-change-events.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest' +import { getDefaultSettings } from '../../../../shared/constants' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import { publishSettingsChanges } from './runtime-settings-change-events' + +type Listener = (updates: Partial, settings: GlobalSettings) => void + +function settingsStore(initial: GlobalSettings) { + let settings = initial + const listeners = new Set() + return { + getSettings: () => settings, + onSettingsChanged: (listener: Listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + // Like the real store: replace the object, then pass listeners what the writer sent. + update: (updates: Partial) => { + settings = { ...settings, ...updates } + for (const listener of listeners) { + listener(updates, settings) + } + } + } +} + +describe('publishSettingsChanges', () => { + it('names only the settings whose values changed', () => { + const store = settingsStore({ + ...getDefaultSettings('/home/me'), + prBotAuthorOverrides: ['renovate'], + diffShowWhitespace: false + }) + const events: RuntimeClientEvent[] = [] + publishSettingsChanges(store, (event) => events.push(event)) + + store.update({ + prBotAuthorOverrides: ['renovate'], + diffShowWhitespace: true + }) + store.update({ diffShowWhitespace: true }) + + expect(events).toEqual([{ type: 'settingsChanged', keys: ['diffShowWhitespace'] }]) + }) +}) diff --git a/src/main/runtime/client/settings/runtime-settings-change-events.ts b/src/main/runtime/client/settings/runtime-settings-change-events.ts new file mode 100644 index 00000000000..37e49ae92f7 --- /dev/null +++ b/src/main/runtime/client/settings/runtime-settings-change-events.ts @@ -0,0 +1,25 @@ +import { isDeepStrictEqual } from 'node:util' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import type { RuntimeStore } from '../../construction/runtime-store-contract' + +/** Tells clients which top-level settings changed, so a phone re-reads only what it shows. */ +export function publishSettingsChanges( + store: Pick | null, + emit: (event: RuntimeClientEvent) => void +): void { + if (!store?.getSettings || !store.onSettingsChanged) { + return + } + let previous = new Map(Object.entries(store.getSettings())) + store.onSettingsChanged((updates, settings) => { + const next = new Map(Object.entries(settings)) + // A writer may resend a value it did not change, as an equal but new object. + const keys = Object.keys(updates).filter( + (key) => !isDeepStrictEqual(previous.get(key), next.get(key)) + ) + previous = next + if (keys.length > 0) { + emit({ type: 'settingsChanged', keys }) + } + }) +} diff --git a/src/main/runtime/files/file-mutation-expectation.ts b/src/main/runtime/files/file-mutation-expectation.ts index ecc95b07958..e22730d51e6 100644 --- a/src/main/runtime/files/file-mutation-expectation.ts +++ b/src/main/runtime/files/file-mutation-expectation.ts @@ -5,7 +5,7 @@ import { import { assertSshMutationExpectation, getSshConnectionGeneration -} from '../../ssh/connection/ssh-connection-generation' +} from '../../ssh/connection/authority/ssh-connection-generation' export const RUNTIME_FILE_MUTATION_UPDATE_REQUIRED = 'Remote file changes require a newer Orca client. Update the paired client and try again.' diff --git a/src/main/runtime/files/runtime-file-host.test-fixture.ts b/src/main/runtime/files/runtime-file-host.test-fixture.ts index 7eb8cab1060..fbff2d19fdf 100644 --- a/src/main/runtime/files/runtime-file-host.test-fixture.ts +++ b/src/main/runtime/files/runtime-file-host.test-fixture.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, vi } from 'vitest' import { awaitRuntimeFileWatcherUnsubscribes } from './watch/file-watcher-leases' import type { RuntimeFileCommandHost } from './file-command-host' -import { resetSshConnectionGenerations } from '../../ssh/connection/ssh-connection-generation' +import { resetSshConnectionGenerations } from '../../ssh/connection/authority/ssh-connection-generation' import { resetRuntimeFileMocks } from './runtime-file-command-mock-registry' import { getConnectionExecutionHostId, diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 5c30d7579a0..8c28e659ffb 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -3,6 +3,7 @@ import { conversationRecordReader } from './orchestration/addressing/session-lin import type { RuntimeLinearCommandSurface } from './integrations/linear/runtime-linear-command-surface' import { installRuntimeLinearCommandSurface } from './integrations/linear/runtime-linear-command-surface' import { publishNativeChatPreferenceChanges } from './agent-session/launch/runtime-native-chat-preference-events' +import { publishSettingsChanges } from './client/settings/runtime-settings-change-events' import { publishWorkspaceViewChanges } from './sidebar-inputs/runtime-workspace-view-change-events' import { OrcaRuntimeWithSidebarTemporal, @@ -175,6 +176,7 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { registerWorktreeChangeInvalidator((repoId) => this.invalidateWorktreeCatalog(repoId)) publishWorkspaceViewChanges(this.store, (event) => this.emitClientEvent(event)) publishNativeChatPreferenceChanges(this.store, (event) => this.emitClientEvent(event)) + publishSettingsChanges(this.store, (event) => this.emitClientEvent(event)) } private structuredAgentAvailability?: ReturnType diff --git a/src/main/runtime/rpc/methods/rpc-method-registry.ts b/src/main/runtime/rpc/methods/rpc-method-registry.ts index bc707050b33..79858ee663a 100644 --- a/src/main/runtime/rpc/methods/rpc-method-registry.ts +++ b/src/main/runtime/rpc/methods/rpc-method-registry.ts @@ -7,6 +7,7 @@ import { AI_VAULT_METHODS } from './history/ai-vault' import { AUTOMATION_METHODS } from './automations/automations' import { REPO_METHODS } from './projects/repo' import { WORKTREE_METHODS } from './workspaces/worktree' +import { AGENT_ACTIVITY_METHODS } from './workspaces/agent-activity-methods' import { REFERENCE_METHODS } from './reference/reference' import { TERMINAL_METHODS } from './terminal/terminal' import { TERMINAL_ORPHAN_METHODS } from './terminal/terminal-orphan' @@ -92,6 +93,7 @@ export const ALL_RPC_METHODS = [ ...AUTOMATION_METHODS, ...REPO_METHODS, ...WORKTREE_METHODS, + ...AGENT_ACTIVITY_METHODS, ...REFERENCE_METHODS, ...AGENT_SESSION_METHODS, ...STRUCTURED_AGENT_SESSION_METHODS, diff --git a/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts b/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts index f2905b96470..8156d14a0dd 100644 --- a/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts +++ b/src/main/runtime/rpc/methods/ssh/ssh-target-management.test.ts @@ -23,7 +23,7 @@ vi.mock('../../../../ssh/targets/ssh-target-registry', () => ({ listRegisteredSshTargets: mocks.listRegisteredSshTargets })) -vi.mock('../../../../ssh/ssh-remote-directory-browse', () => ({ +vi.mock('../../../../ssh/filesystem/ssh-remote-directory-browse', () => ({ browseSshDirectory: mocks.browseSshDirectory })) diff --git a/src/main/runtime/rpc/methods/ssh/ssh.ts b/src/main/runtime/rpc/methods/ssh/ssh.ts index 551d6a80a56..3e375c15f20 100644 --- a/src/main/runtime/rpc/methods/ssh/ssh.ts +++ b/src/main/runtime/rpc/methods/ssh/ssh.ts @@ -7,8 +7,8 @@ import { listRegisteredSshTargets, SshTargetManagementUnservedError } from '../../../../ssh/targets/ssh-target-registry' -import { isManagedOrcadSshTarget } from '../../../../ssh/connection/ssh-connection-store' -import { browseSshDirectory } from '../../../../ssh/ssh-remote-directory-browse' +import { isManagedOrcadSshTarget } from '../../../../ssh/targets/ssh-target-runtime-ownership' +import { browseSshDirectory } from '../../../../ssh/filesystem/ssh-remote-directory-browse' import { defineMethod } from '../../core' import { getPublicSshError, diff --git a/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts new file mode 100644 index 00000000000..24cfcf523b6 --- /dev/null +++ b/src/main/runtime/rpc/methods/workspaces/agent-activity-methods.ts @@ -0,0 +1,30 @@ +import { defineMethod } from '../../core' +import { + AgentActivityClearParams, + AgentActivitySetReadParams +} from '../../../../../shared/rpc-contract/agent-activity-params' + +// Desktop Agents-list read and clear for paired clients; the next worktree.ps already reflects them. +export const AGENT_ACTIVITY_METHODS = [ + defineMethod({ + name: 'agentActivity.setRead', + permission: 'workspace', + params: AgentActivitySetReadParams, + handler: async (params, { runtime }) => { + await runtime.applyAgentPaneActivity({ + kind: params.read ? 'read' : 'unread', + paneKeys: params.paneKeys + }) + return { applied: true } + } + }), + defineMethod({ + name: 'agentActivity.clear', + permission: 'workspace', + params: AgentActivityClearParams, + handler: async (params, { runtime }) => { + await runtime.applyAgentPaneActivity({ kind: 'clear', paneKeys: params.paneKeys }) + return { applied: true } + } + }) +] diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts index dfe15ee9d1a..937d3cf7482 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-method-routing.ts @@ -11,6 +11,9 @@ export const EXECUTION_HOST_METHODS = [ 'ui.mutateJiraSavedFilters', 'agent.launch', 'agent.launchReplay', + // Read state lives with the host whose worktree.ps reports it. + 'agentActivity.clear', + 'agentActivity.setRead', 'agentTeams.prepareLaunch', 'agentTeams.tmuxCompat', 'automation.list', diff --git a/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts b/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts index 96f6ab1b642..dcc36708742 100644 --- a/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts +++ b/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts @@ -20,8 +20,8 @@ import type { RuntimeWorktreeRemoveResult } from '../../../shared/runtime-worktr import type { RuntimeRpcSuccess } from '../../../shared/runtime-rpc-envelope' import * as appEnvironment from '../../../shared/app-environment' import type { SshTarget } from '../../../shared/ssh-types' -import { orcadMigrationCutoverFixture } from '../../ssh/orcad-migration-cutover-fixture' -import { writeOrcadMigrationSourceCutover } from '../../ssh/orcad-migration-cutover-journal' +import { orcadMigrationCutoverFixture } from '../../managed-server/migration/cutover/testing/orcad-migration-cutover-fixture' +import { writeOrcadMigrationSourceCutover } from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { removalPtyProvider } from './worktree-rm-pty.test-fixture' import { pairedRemovalReceiver } from './worktree-rm-paired.test-fixture' import { addManagedOrcadEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' diff --git a/src/main/runtime/workspaces/catalog/runtime-visible-catalog.ts b/src/main/runtime/workspaces/catalog/runtime-visible-catalog.ts index 1ca3cd877db..2bfa3d4051b 100644 --- a/src/main/runtime/workspaces/catalog/runtime-visible-catalog.ts +++ b/src/main/runtime/workspaces/catalog/runtime-visible-catalog.ts @@ -18,7 +18,7 @@ import { visibleProjectGroups, visibleProjectHostSetups, visibleRepos -} from '../../../ssh/orcad-retained-source' +} from '../../../persistence/migrating-orcad-catalog/orcad-source-visibility' import type { RuntimeStore } from '../../construction/runtime-store-contract' type CatalogSource = Pick< diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts new file mode 100644 index 00000000000..9df27422243 --- /dev/null +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-activity.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest' +import type { AgentListPublication } from '../../../../shared/agent-status/presentation/agent-list-status' +import type { RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' +import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' +import type { RuntimeWorktreeAgentSource } from './runtime-worktree-agent-source' + +const WORKTREE_ID = 'repo::/work/tree' +const PUBLISHED_AT = 1_800_000_000_000 + +function source(paneKey: string, updatedAt: number): RuntimeWorktreeAgentSource { + return { + paneKey, + worktreeId: WORKTREE_ID, + connectionId: null, + state: 'done', + agentType: 'claude', + prompt: 'fix it', + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: updatedAt, + updatedAt + } +} + +function listAgents(agentList: AgentListPublication | null) { + const summary: RuntimeWorktreePsSummary = { + worktreeId: WORKTREE_ID, + repoId: 'repo', + repo: 'repo', + path: '/work/tree', + branch: 'main', + isArchived: false, + isMainWorktree: false, + hasHostSidebarActivity: false, + parentWorktreeId: null, + childWorktreeIds: [], + displayName: 'tree', + workspaceStatus: '', + sortOrder: 0, + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + comment: '', + isPinned: false, + isActive: false, + unread: false, + liveTerminalCount: 0, + hasAttachedPty: false, + lastOutputAt: null, + preview: '', + status: 'inactive', + agents: [] + } + const summaries = new Map([[WORKTREE_ID, summary]]) + attachRuntimeWorktreeAgentRows({ + summaries, + rowSources: new Map( + [ + source('tab-1:listed', PUBLISHED_AT - 3), + source('tab-1:session-start', PUBLISHED_AT - 2), + source('tab-1:unknown-old', PUBLISHED_AT - 1), + source('tab-1:unknown-new', PUBLISHED_AT + 1) + ].map((row) => [row.paneKey, row]) + ), + terminalTitleEvidenceByRow: new Map(), + orchestrationByPaneKey: null, + getSummary: (id) => summaries.get(id) ?? null, + agentList + }) + return Object.fromEntries((summary.agents ?? []).map((row) => [row.paneKey, row.activity])) +} + +describe('worktree.ps agent rows and the desktop Agents list', () => { + it('carries each pane’s verdict and holds back only turns newer than the verdicts', () => { + const listed = { + listed: true, + status: 'done', + unread: true, + clearable: true, + sortAt: PUBLISHED_AT - 3, + title: 'Fix the build', + childOf: 'tab-0:coordinator', + foldedChild: true + } as const + expect( + listAgents({ + publishedAt: PUBLISHED_AT, + verdicts: { 'tab-1:listed': listed, 'tab-1:session-start': { listed: false } } + }) + ).toEqual({ + 'tab-1:listed': listed, + 'tab-1:session-start': { listed: false }, + 'tab-1:unknown-old': { listed: false }, + 'tab-1:unknown-new': undefined + }) + }) +}) diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts index a306fd80fad..f3ec79e8fcb 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows.ts @@ -7,6 +7,10 @@ import type { RuntimeWorktreeAgentRow, RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' +import type { + AgentListPublication, + AgentListVerdict +} from '../../../../shared/agent-status/presentation/agent-list-status' import { mergeWorktreeSummaryStatus } from './runtime-worktree-status-projection' import { resolveRuntimeWorktreeSidebarStatus, @@ -25,6 +29,19 @@ type OrchestrationDisplay = { parentPaneKey?: string | null } +const UNLISTED: AgentListVerdict = { listed: false } + +/** A pane the window gave no verdict is not in its list, unless it changed after the window last looked. */ +function agentListVerdict( + agentList: AgentListPublication, + source: RuntimeWorktreeAgentSource +): AgentListVerdict | undefined { + return ( + agentList.verdicts[source.paneKey] ?? + (source.updatedAt > agentList.publishedAt ? undefined : UNLISTED) + ) +} + export function attachRuntimeWorktreeAgentRows(args: { summaries: Map rowSources: ReadonlyMap @@ -35,6 +52,8 @@ export function attachRuntimeWorktreeAgentRows(args: { orchestrationByPaneKey: Record | null | undefined getSummary: RuntimeWorktreePsSummaryLookup conversationName?: (source: RuntimeWorktreeAgentSource) => string | null + /** The desktop window's Agents-list verdicts; null when no window has published them. */ + agentList?: AgentListPublication | null }): void { const { rowSources } = args const now = Date.now() @@ -80,6 +99,10 @@ export function attachRuntimeWorktreeAgentRows(args: { if (source.children !== undefined || source.subagents !== undefined) { row.subagentObservation = isAgentStatusFresh(row, now) ? 'live' : 'unverifiable' } + const activity = args.agentList && agentListVerdict(args.agentList, source) + if (activity) { + row.activity = activity + } const rows = rowsBySummary.get(summary) if (rows) { rows.push(row) diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 8610941e3fe..6334fb8480e 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -135,7 +135,8 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends RuntimeChatWorkerEven rowSources, orchestrationByPaneKey: this.agentOrchestrationProjection.buildByPaneKey(), getSummary, - conversationName: this.orchestrationSenderNames.agentRowNamer() + conversationName: this.orchestrationSenderNames.agentRowNamer(), + agentList: this.readAgentListPublication() }) const sorted = [...summaries.values()].sort(compareWorktreePs) diff --git a/src/main/ssh/ssh-agent-identity-filter.test.ts b/src/main/ssh/authentication/ssh-agent-identity-filter.test.ts similarity index 100% rename from src/main/ssh/ssh-agent-identity-filter.test.ts rename to src/main/ssh/authentication/ssh-agent-identity-filter.test.ts diff --git a/src/main/ssh/ssh-agent-identity-filter.ts b/src/main/ssh/authentication/ssh-agent-identity-filter.ts similarity index 97% rename from src/main/ssh/ssh-agent-identity-filter.ts rename to src/main/ssh/authentication/ssh-agent-identity-filter.ts index 148f0fa313e..f35239cf14a 100644 --- a/src/main/ssh/ssh-agent-identity-filter.ts +++ b/src/main/ssh/authentication/ssh-agent-identity-filter.ts @@ -6,7 +6,7 @@ import type { SignCallback, SigningRequestOptions } from 'ssh2' -import { resolveSshConfigHomePath } from './config/ssh-config-path-expansion' +import { resolveSshConfigHomePath } from '../config/ssh-config-path-expansion' import { readSshIdentityFileSync } from './ssh-identity-file-read' import { loadSsh2 } from './ssh2-module-load' diff --git a/src/main/ssh/ssh-agent-sign-observer.ts b/src/main/ssh/authentication/ssh-agent-sign-observer.ts similarity index 100% rename from src/main/ssh/ssh-agent-sign-observer.ts rename to src/main/ssh/authentication/ssh-agent-sign-observer.ts diff --git a/src/main/ssh/ssh-auth-resolution.ts b/src/main/ssh/authentication/ssh-auth-resolution.ts similarity index 95% rename from src/main/ssh/ssh-auth-resolution.ts rename to src/main/ssh/authentication/ssh-auth-resolution.ts index 7fa34309391..dd9a5c1c0fc 100644 --- a/src/main/ssh/ssh-auth-resolution.ts +++ b/src/main/ssh/authentication/ssh-auth-resolution.ts @@ -1,13 +1,13 @@ import { existsSync } from 'node:fs' import type { BaseAgent, ParsedKey } from 'ssh2' -import type { SshTarget } from '../../shared/ssh-types' -import type { SshResolvedConfig } from './config/ssh-g-config-resolution' +import type { SshTarget } from '../../../shared/ssh-types' +import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' import { createIdentityFilteredAgent } from './ssh-agent-identity-filter' import { loadSsh2 } from './ssh2-module-load' -import { resolveSshConfigHomePath } from './config/ssh-config-path-expansion' -import { isOpenSshConfigBackedTarget } from './system-transport/system-ssh-args' +import { resolveSshConfigHomePath } from '../config/ssh-config-path-expansion' +import { isOpenSshConfigBackedTarget } from '../system-transport/system-ssh-args' import { readSshIdentityFileSync } from './ssh-identity-file-read' -import { isAuthError } from './ssh-reconnect-error-classification' +import { isAuthError } from '../connection/reconnect/ssh-reconnect-error-classification' // ssh2 discovers no keys itself; probe regular/FIDO2 default paths for users without agents. const DEFAULT_KEY_NAMES = ['id_ed25519', 'id_rsa', 'id_ecdsa', 'id_dsa', 'id_xmss'] diff --git a/src/main/ssh/ssh-credential-decline.ts b/src/main/ssh/authentication/ssh-credential-decline.ts similarity index 95% rename from src/main/ssh/ssh-credential-decline.ts rename to src/main/ssh/authentication/ssh-credential-decline.ts index 04c004f9f56..f36a72936cb 100644 --- a/src/main/ssh/ssh-credential-decline.ts +++ b/src/main/ssh/authentication/ssh-credential-decline.ts @@ -1,11 +1,11 @@ import { getRuntimeSshAccess, type KnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { SSH_SIGN_IN_AWAITED_SUFFIX, SSH_SIGN_IN_CANCELLED_SUFFIX -} from '../../shared/ssh-sign-in-required-copy' +} from '../../../shared/ssh-sign-in-required-copy' /** Suppress automatic prompts after decline until explicit connect; background status/tunnels/reconnects would otherwise reopen the modal repeatedly. */ // The declining attempt may try other methods; only later attempts are barred. awaitingSignIn records credentials not yet supplied this launch. diff --git a/src/main/ssh/ssh-identity-file-read.test.ts b/src/main/ssh/authentication/ssh-identity-file-read.test.ts similarity index 97% rename from src/main/ssh/ssh-identity-file-read.test.ts rename to src/main/ssh/authentication/ssh-identity-file-read.test.ts index a22bb01b2d0..7dc6eee2fc7 100644 --- a/src/main/ssh/ssh-identity-file-read.test.ts +++ b/src/main/ssh/authentication/ssh-identity-file-read.test.ts @@ -3,7 +3,7 @@ import { mkdir, mkdtemp, rm, symlink, truncate, writeFile } from 'node:fs/promis import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcess } from '@orca/process-host' -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' import { resolvePrivateKeys, withSkippedIdentityFileDetail, diff --git a/src/main/ssh/ssh-identity-file-read.ts b/src/main/ssh/authentication/ssh-identity-file-read.ts similarity index 96% rename from src/main/ssh/ssh-identity-file-read.ts rename to src/main/ssh/authentication/ssh-identity-file-read.ts index 18eb7596266..d4b19b26079 100644 --- a/src/main/ssh/ssh-identity-file-read.ts +++ b/src/main/ssh/authentication/ssh-identity-file-read.ts @@ -3,7 +3,7 @@ import { NodeFileReadTooLargeError, readNodeFileSyncWithinLimit, readNodeFileWithinLimit -} from '../../shared/file-content/node-bounded-file-reader' +} from '../../../shared/file-content/node-bounded-file-reader' import { MAX_SSH_IDENTITY_FILE_BYTES } from './ssh-security-key-identity' /** `problem` is null when the file is simply absent, which is normal for default key paths. */ diff --git a/src/main/ssh/ssh-keyboard-interactive.test.ts b/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts similarity index 87% rename from src/main/ssh/ssh-keyboard-interactive.test.ts rename to src/main/ssh/authentication/ssh-keyboard-interactive.test.ts index eb9dcf0bc25..f01c46b5871 100644 --- a/src/main/ssh/ssh-keyboard-interactive.test.ts +++ b/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts @@ -97,28 +97,6 @@ describe('collectKeyboardInteractiveResponses', () => { expect(setCachedPassword).toHaveBeenCalledWith('corrected-password') }) - it('collects and caches the password when nothing is cached yet', async () => { - const requestCredential = vi.fn(async () => 'password-123') - const setCachedPassword = vi.fn() - const session = createSession({ requestCredential, setCachedPassword }) - - const responses = await collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Password: ', echo: false }, - { prompt: 'Duo push approval', echo: false } - ]) - - expect(responses).toEqual(['password-123', 'password-123']) - expect(requestCredential).toHaveBeenNthCalledWith(1, 'target-1', 'password', 'example.com') - expect(requestCredential).toHaveBeenNthCalledWith( - 2, - 'target-1', - 'keyboard-interactive', - 'Duo push approval', - false - ) - expect(setCachedPassword).toHaveBeenCalledWith('password-123') - }) - it('returns null and marks the session cancelled when the user dismisses a prompt', async () => { const session = createSession({ requestCredential: vi.fn(async () => null) }) diff --git a/src/main/ssh/ssh-keyboard-interactive.ts b/src/main/ssh/authentication/ssh-keyboard-interactive.ts similarity index 97% rename from src/main/ssh/ssh-keyboard-interactive.ts rename to src/main/ssh/authentication/ssh-keyboard-interactive.ts index 403a217fdc9..d8f8dbbdd69 100644 --- a/src/main/ssh/ssh-keyboard-interactive.ts +++ b/src/main/ssh/authentication/ssh-keyboard-interactive.ts @@ -1,5 +1,5 @@ import type { Prompt } from 'ssh2' -import type { SshConnectionCallbacks } from './connection/ssh-connection-callbacks' +import type { SshConnectionCallbacks } from '../connection/ssh-connection-callbacks' // Route password challenges through cached-password auth; other MFA prompts require fresh human answers. const PASSWORD_PROMPT = /password/i diff --git a/src/main/ssh/ssh-multi-factor-authentication.test.ts b/src/main/ssh/authentication/ssh-multi-factor-authentication.test.ts similarity index 98% rename from src/main/ssh/ssh-multi-factor-authentication.test.ts rename to src/main/ssh/authentication/ssh-multi-factor-authentication.test.ts index 3ca4a9aa81b..6ad29008a69 100644 --- a/src/main/ssh/ssh-multi-factor-authentication.test.ts +++ b/src/main/ssh/authentication/ssh-multi-factor-authentication.test.ts @@ -17,9 +17,12 @@ import { type SigningRequestOptions } from 'ssh2' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' -import type { SshResolvedConfig } from './config/ssh-g-config-resolution' -import { buildConnectConfig, type BuildConnectConfigOptions } from './connection/ssh-connect-config' +import type { SshTarget } from '../../../shared/ssh-types' +import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' +import { + buildConnectConfig, + type BuildConnectConfigOptions +} from '../connection/ssh-connect-config' vi.mock('node:os', async (importOriginal) => { const actual = await importOriginal() diff --git a/src/main/ssh/ssh-multi-key-authentication.test.ts b/src/main/ssh/authentication/ssh-multi-key-authentication.test.ts similarity index 90% rename from src/main/ssh/ssh-multi-key-authentication.test.ts rename to src/main/ssh/authentication/ssh-multi-key-authentication.test.ts index f323597ab84..d4c8289439d 100644 --- a/src/main/ssh/ssh-multi-key-authentication.test.ts +++ b/src/main/ssh/authentication/ssh-multi-key-authentication.test.ts @@ -30,12 +30,12 @@ vi.mock('./ssh-identity-file-read', () => ({ } })) -import { buildConnectConfig } from './connection/ssh-connect-config' +import { buildConnectConfig } from '../connection/ssh-connect-config' import { getPassphrasePrivateKeyPath } from './ssh-private-key-authentication' -import './system-transport/system-ssh-args' -import { walkInitialAuthLadder } from './connection/ssh-connection-test-fixtures' -import type { SshTarget } from '../../shared/ssh-types' -import type { SshResolvedConfig } from './config/ssh-g-config-resolution' +import '../system-transport/system-ssh-args' +import { walkInitialAuthLadder } from '../connection/testing/ssh-connection-test-fixtures' +import type { SshTarget } from '../../../shared/ssh-types' +import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' function makeTarget(overrides: Partial = {}): SshTarget { return { @@ -171,20 +171,6 @@ describe('ordered SSH private-key authentication', () => { expect(nextAuth(manual, false)).toBe('keyboard-interactive') }) - it('re-offers keyboard-interactive for each partial-success MFA stage', () => { - const config = buildConnectConfig(makeTarget(), makeResolved(), { - includeAgent: false, - includePrivateKey: true - }) - config.password = 'stage-one' - - expect(nextAuth(config, true)).toMatchObject({ type: 'none' }) - expect(nextAuth(config, false)).toMatchObject({ type: 'password' }) - // Partial success: the host accepted the password and now offers only the challenge. - expect(partialSuccessAuth(config, ['keyboard-interactive'])).toBe('keyboard-interactive') - expect(partialSuccessAuth(config, ['keyboard-interactive'])).toBe('keyboard-interactive') - }) - it('keeps the password challenge on an agent attempt that carries a key, because no key retry follows it', () => { vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock') // Real key bytes, so '/keys/explicit' counts as unencrypted and IdentitiesOnly builds its agent. diff --git a/src/main/ssh/ssh-private-key-authentication.ts b/src/main/ssh/authentication/ssh-private-key-authentication.ts similarity index 100% rename from src/main/ssh/ssh-private-key-authentication.ts rename to src/main/ssh/authentication/ssh-private-key-authentication.ts diff --git a/src/main/ssh/ssh-security-key-identity.test.ts b/src/main/ssh/authentication/ssh-security-key-identity.test.ts similarity index 93% rename from src/main/ssh/ssh-security-key-identity.test.ts rename to src/main/ssh/authentication/ssh-security-key-identity.test.ts index 53f5c2390e4..0ba4f9642d8 100644 --- a/src/main/ssh/ssh-security-key-identity.test.ts +++ b/src/main/ssh/authentication/ssh-security-key-identity.test.ts @@ -10,12 +10,12 @@ import { import { createOpenSshPrivateKeyFixture, createOpenSshPublicKeyFixture -} from './ssh-security-key-identity.test-fixture' -import './ssh-transport-selection' +} from './testing/ssh-security-key-identity.test-fixture' +import '../system-transport/ssh-transport-selection' const { findSystemSshMock } = vi.hoisted(() => ({ findSystemSshMock: vi.fn() })) -vi.mock('./system-transport/system-ssh-binary', () => ({ findSystemSsh: findSystemSshMock })) +vi.mock('../system-transport/system-ssh-binary', () => ({ findSystemSsh: findSystemSshMock })) vi.mock('node:os', async (importOriginal) => { const actual = await importOriginal<{ homedir: () => string }>() diff --git a/src/main/ssh/ssh-security-key-identity.ts b/src/main/ssh/authentication/ssh-security-key-identity.ts similarity index 100% rename from src/main/ssh/ssh-security-key-identity.ts rename to src/main/ssh/authentication/ssh-security-key-identity.ts diff --git a/src/main/ssh/connection/ssh2-credential-fallback.ts b/src/main/ssh/authentication/ssh2-credential-fallback.ts similarity index 93% rename from src/main/ssh/connection/ssh2-credential-fallback.ts rename to src/main/ssh/authentication/ssh2-credential-fallback.ts index 732317a5fa7..17669fb1c0f 100644 --- a/src/main/ssh/connection/ssh2-credential-fallback.ts +++ b/src/main/ssh/authentication/ssh2-credential-fallback.ts @@ -1,24 +1,24 @@ import type { ConnectConfig } from 'ssh2' import type { SshTarget } from '../../../shared/ssh-types' import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' -import type { SkippedIdentityFiles } from '../ssh-auth-resolution' -import type { SshCredentialKind } from './ssh-connection-callbacks' -import { buildConnectConfig } from './ssh-connect-config' -import type { resolveEffectiveProxy } from '../ssh-proxy-command' +import type { SkippedIdentityFiles } from './ssh-auth-resolution' +import type { SshCredentialKind } from '../connection/ssh-connection-callbacks' +import { buildConnectConfig } from '../connection/ssh-connect-config' +import type { resolveEffectiveProxy } from '../system-transport/ssh-proxy-command' import { isAgentFallbackError, isGssapiSystemSshFallbackCandidate, isPassphraseError, isSsh2AlgorithmNegotiationError, isSystemSshFallbackError -} from '../ssh-reconnect-error-classification' -import { isHostKeyVerificationError } from '../ssh-host-key-decision' -import { createCancelledConnectAttemptError } from '../ssh-connect-attempt-cancellation' +} from '../connection/reconnect/ssh-reconnect-error-classification' +import { isHostKeyVerificationError } from '../host-keys/ssh-host-key-decision' +import { createCancelledConnectAttemptError } from '../connection/reconnect/ssh-connect-attempt-cancellation' import { didDeferKeyboardInteractive, didOfferKeyboardInteractive, getPassphrasePrivateKeyPath -} from '../ssh-private-key-authentication' +} from './ssh-private-key-authentication' type EffectiveProxy = ReturnType diff --git a/src/main/ssh/connection/ssh2-handshake.ts b/src/main/ssh/authentication/ssh2-handshake.ts similarity index 96% rename from src/main/ssh/connection/ssh2-handshake.ts rename to src/main/ssh/authentication/ssh2-handshake.ts index 69dbe792501..ad18dd16eb4 100644 --- a/src/main/ssh/connection/ssh2-handshake.ts +++ b/src/main/ssh/authentication/ssh2-handshake.ts @@ -1,8 +1,8 @@ import type { Client as SshClient, ConnectConfig, KeyboardInteractiveCallback, Prompt } from 'ssh2' -import { loadSsh2 } from '../ssh2-module-load' -import { CONNECT_TIMEOUT_MS, SSH_CREDENTIAL_TIMEOUT_MS } from './ssh-connection-timing' -import { createCancelledConnectAttemptError } from '../ssh-connect-attempt-cancellation' -import type { HostKeyVerificationError } from '../ssh-host-key-decision' +import { loadSsh2 } from './ssh2-module-load' +import { CONNECT_TIMEOUT_MS, SSH_CREDENTIAL_TIMEOUT_MS } from '../connection/ssh-connection-timing' +import { createCancelledConnectAttemptError } from '../connection/reconnect/ssh-connect-attempt-cancellation' +import type { HostKeyVerificationError } from '../host-keys/ssh-host-key-decision' // Count INFO_REQUEST across every partial-success stage and PAM challenge round. const SSH_KEYBOARD_INTERACTIVE_MAX_ROUNDS = 8 diff --git a/src/main/ssh/ssh2-module-load.ts b/src/main/ssh/authentication/ssh2-module-load.ts similarity index 100% rename from src/main/ssh/ssh2-module-load.ts rename to src/main/ssh/authentication/ssh2-module-load.ts diff --git a/src/main/ssh/ssh-security-key-identity.test-fixture.ts b/src/main/ssh/authentication/testing/ssh-security-key-identity.test-fixture.ts similarity index 100% rename from src/main/ssh/ssh-security-key-identity.test-fixture.ts rename to src/main/ssh/authentication/testing/ssh-security-key-identity.test-fixture.ts diff --git a/src/main/ssh/connection/authority/ssh-connection-generation.test.ts b/src/main/ssh/connection/authority/ssh-connection-generation.test.ts new file mode 100644 index 00000000000..92543cf24fd --- /dev/null +++ b/src/main/ssh/connection/authority/ssh-connection-generation.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' +import { assertSshMutationExpectation } from './ssh-connection-generation' + +describe('SSH connection generation session scope', () => { + it('rejects an SSH execution-host expectation when direct IPC resolves locally', () => { + expect(() => + assertSshMutationExpectation(undefined, undefined, undefined, 'ssh:ssh-a') + ).toThrow('Workspace host changed; refresh and try again') + }) + + it('rejects a local execution-host expectation when direct IPC resolves through SSH', () => { + expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', 0, 'local')).toThrow( + 'Workspace host changed; refresh and try again' + ) + }) +}) diff --git a/src/main/ssh/connection/ssh-connection-generation.ts b/src/main/ssh/connection/authority/ssh-connection-generation.ts similarity index 95% rename from src/main/ssh/connection/ssh-connection-generation.ts rename to src/main/ssh/connection/authority/ssh-connection-generation.ts index 1e8ea2f746f..1e869f6ad1d 100644 --- a/src/main/ssh/connection/ssh-connection-generation.ts +++ b/src/main/ssh/connection/authority/ssh-connection-generation.ts @@ -1,5 +1,5 @@ import { randomBytes } from 'node:crypto' -import { getConnectionExecutionHostId } from '../../../shared/execution-host' +import { getConnectionExecutionHostId } from '../../../../shared/execution-host' const SESSION_COUNTER_BITS = 13 const SESSION_COUNTER_STRIDE = 2 ** SESSION_COUNTER_BITS @@ -25,11 +25,6 @@ export function forgetSshConnectionGeneration(targetId: string): void { connectionGenerationByTarget.delete(targetId) } -/** @internal - cache-bound test view. */ -export function getSshConnectionGenerationEntryCountForTests(): number { - return connectionGenerationByTarget.size -} - export function isSshConnectionGenerationInCurrentSession(generation: number): boolean { return ( Number.isSafeInteger(generation) && diff --git a/src/main/ssh/ssh-provider-authority.ts b/src/main/ssh/connection/authority/ssh-provider-authority.ts similarity index 98% rename from src/main/ssh/ssh-provider-authority.ts rename to src/main/ssh/connection/authority/ssh-provider-authority.ts index fe5eb3983a3..a0798f6e688 100644 --- a/src/main/ssh/ssh-provider-authority.ts +++ b/src/main/ssh/connection/authority/ssh-provider-authority.ts @@ -1,10 +1,10 @@ import { randomBytes } from 'node:crypto' -import type { DirectSshAuthority, SshProviderEpoch } from '../../shared/ssh-types' +import type { DirectSshAuthority, SshProviderEpoch } from '../../../../shared/ssh-types' import { advanceSshConnectionGeneration, isSshConnectionGenerationInCurrentSession, getSshConnectionGeneration -} from './connection/ssh-connection-generation' +} from './ssh-connection-generation' const authorityByTarget = new Map() type ProviderRequestAbortRegistration = { diff --git a/src/main/ssh/ssh-channel-open.ts b/src/main/ssh/connection/channels/ssh-channel-open.ts similarity index 95% rename from src/main/ssh/ssh-channel-open.ts rename to src/main/ssh/connection/channels/ssh-channel-open.ts index 6f0b3ff39cd..60ee535dc2f 100644 --- a/src/main/ssh/ssh-channel-open.ts +++ b/src/main/ssh/connection/channels/ssh-channel-open.ts @@ -1,7 +1,7 @@ -import { trackSshConnectionChannelLifetime } from './connection/ssh-connection-channel-lifetime' -import { CONNECT_TIMEOUT_MS } from './connection/ssh-connection-timing' -import { createSshOperationAbortError } from './connection/ssh-exec-options' -import { isSshSessionLimitError } from './ssh-session-limit-error' +import { trackSshConnectionChannelLifetime } from './ssh-connection-channel-lifetime' +import { CONNECT_TIMEOUT_MS } from '../ssh-connection-timing' +import { createSshOperationAbortError } from '../ssh-exec-options' +import { isSshSessionLimitError } from '../ssh-session-limit-error' // Upper bound on waiting for an aborted channel's open/close to settle before rejecting anyway. const ABORTED_CHANNEL_CLOSE_GRACE_MS = 5_000 diff --git a/src/main/ssh/connection/ssh-connection-channel-lifetime.ts b/src/main/ssh/connection/channels/ssh-connection-channel-lifetime.ts similarity index 100% rename from src/main/ssh/connection/ssh-connection-channel-lifetime.ts rename to src/main/ssh/connection/channels/ssh-connection-channel-lifetime.ts diff --git a/src/main/ssh/connection/ssh-connection-session-channels.ts b/src/main/ssh/connection/channels/ssh-connection-session-channels.ts similarity index 92% rename from src/main/ssh/connection/ssh-connection-session-channels.ts rename to src/main/ssh/connection/channels/ssh-connection-session-channels.ts index 685b82ce340..766be9a506a 100644 --- a/src/main/ssh/connection/ssh-connection-session-channels.ts +++ b/src/main/ssh/connection/channels/ssh-connection-session-channels.ts @@ -5,14 +5,14 @@ import type { SFTPWrapper, ShellOptions } from 'ssh2' -import type { SshTarget } from '../../../shared/ssh-types' -import type { SystemSshBuildArgsOptions } from '../system-transport/system-ssh-args' -import { spawnSystemSshCommand } from '../system-transport/system-ssh-command' -import { wrapRemoteCommandForPosixShell } from '../ssh-posix-command-wrapper' -import { openSshSessionChannelWithRetry, waitForSshChannelOpen } from '../ssh-channel-open' -import { tagSftpHandshakeCorruption } from '../sftp-handshake-corruption' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { SystemSshBuildArgsOptions } from '../../system-transport/system-ssh-args' +import { spawnSystemSshCommand } from '../../system-transport/system-ssh-command' +import { wrapRemoteCommandForPosixShell } from '../../remote-exec/ssh-posix-command-wrapper' +import { openSshSessionChannelWithRetry, waitForSshChannelOpen } from './ssh-channel-open' +import { tagSftpHandshakeCorruption } from '../../file-transfer/sftp/sftp-handshake-corruption' import { trackSshConnectionChannelLifetime } from './ssh-connection-channel-lifetime' -import { createSshOperationAbortError, type SshExecOptions } from './ssh-exec-options' +import { createSshOperationAbortError, type SshExecOptions } from '../ssh-exec-options' /** What channel opening reads from its connection; getters so each read sees the live transport. */ export type SshSessionChannelHost = { diff --git a/src/main/ssh/ssh-connect-attempt-cancellation.test.ts b/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts similarity index 100% rename from src/main/ssh/ssh-connect-attempt-cancellation.test.ts rename to src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts diff --git a/src/main/ssh/ssh-connect-attempt-cancellation.ts b/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.ts similarity index 100% rename from src/main/ssh/ssh-connect-attempt-cancellation.ts rename to src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.ts diff --git a/src/main/ssh/connection/ssh-connection-reconnect.ts b/src/main/ssh/connection/reconnect/ssh-connection-reconnect.ts similarity index 94% rename from src/main/ssh/connection/ssh-connection-reconnect.ts rename to src/main/ssh/connection/reconnect/ssh-connection-reconnect.ts index f24ffcaa367..1104fbf4eb8 100644 --- a/src/main/ssh/connection/ssh-connection-reconnect.ts +++ b/src/main/ssh/connection/reconnect/ssh-connection-reconnect.ts @@ -1,12 +1,12 @@ -import type { SshConnectionStatus } from '../../../shared/ssh-types' -import { RECONNECT_BACKOFF_MS } from './ssh-connection-timing' +import type { SshConnectionStatus } from '../../../../shared/ssh-types' +import { RECONNECT_BACKOFF_MS } from '../ssh-connection-timing' import { isAuthError, isPassphraseError, isTransientReconnectError -} from '../ssh-reconnect-error-classification' -import { isCancelledConnectAttemptError } from '../ssh-connect-attempt-cancellation' -import { SshReconnectLadder } from '../ssh-reconnect-ladder' +} from './ssh-reconnect-error-classification' +import { isCancelledConnectAttemptError } from './ssh-connect-attempt-cancellation' +import { SshReconnectLadder } from './ssh-reconnect-ladder' import { isSshUserDisconnected } from '../ssh-user-disconnect' // Coalesce resume/online signals: a fresh handshake belongs to the first signal, not the stale pre-sleep route. diff --git a/src/main/ssh/ssh-reconnect-error-classification.ts b/src/main/ssh/connection/reconnect/ssh-reconnect-error-classification.ts similarity index 96% rename from src/main/ssh/ssh-reconnect-error-classification.ts rename to src/main/ssh/connection/reconnect/ssh-reconnect-error-classification.ts index f7cf0b76950..69de9b32f12 100644 --- a/src/main/ssh/ssh-reconnect-error-classification.ts +++ b/src/main/ssh/connection/reconnect/ssh-reconnect-error-classification.ts @@ -1,6 +1,6 @@ -import type { SshTarget } from '../../shared/ssh-types' -import type { SshResolvedConfig } from './config/ssh-g-config-resolution' -import { isHostKeyVerificationError } from './ssh-host-key-decision' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { SshResolvedConfig } from '../../config/ssh-g-config-resolution' +import { isHostKeyVerificationError } from '../../host-keys/ssh-host-key-decision' export function isPassphraseError(err: Error): boolean { const msg = err.message.toLowerCase() diff --git a/src/main/ssh/ssh-reconnect-ladder.ts b/src/main/ssh/connection/reconnect/ssh-reconnect-ladder.ts similarity index 93% rename from src/main/ssh/ssh-reconnect-ladder.ts rename to src/main/ssh/connection/reconnect/ssh-reconnect-ladder.ts index 11e52774a6d..89b853529a7 100644 --- a/src/main/ssh/ssh-reconnect-ladder.ts +++ b/src/main/ssh/connection/reconnect/ssh-reconnect-ladder.ts @@ -1,5 +1,5 @@ -import { MIN_SSH_RELAY_GRACE_PERIOD_SECONDS } from '../../shared/ssh-types' -import { CONNECT_TIMEOUT_MS, RECONNECT_BACKOFF_MS } from './connection/ssh-connection-timing' +import { MIN_SSH_RELAY_GRACE_PERIOD_SECONDS } from '../../../../shared/ssh-types' +import { CONNECT_TIMEOUT_MS, RECONNECT_BACKOFF_MS } from '../ssh-connection-timing' // A connection that held this long is treated as healthy, so the next drop restarts the delay ladder. export const STABLE_CONNECTION_MS = 60_000 diff --git a/src/main/ssh/connection/ssh-connect-config.test.ts b/src/main/ssh/connection/ssh-connect-config.test.ts index 8f569fe5942..377a1923b8a 100644 --- a/src/main/ssh/connection/ssh-connect-config.test.ts +++ b/src/main/ssh/connection/ssh-connect-config.test.ts @@ -17,7 +17,7 @@ function testHomePath(...parts: string[]): string { vi.mock('fs', () => ({ existsSync: (...args: unknown[]) => mockExistsSync(...args) })) -vi.mock('../ssh-identity-file-read', () => ({ +vi.mock('../authentication/ssh-identity-file-read', () => ({ readSshIdentityFileSync: (path: string) => { try { return { contents: mockReadFileSync(path) ?? null, problem: null } @@ -28,9 +28,9 @@ vi.mock('../ssh-identity-file-read', () => ({ })) import { buildConnectConfig } from './ssh-connect-config' -import { findDefaultKeyFile } from '../ssh-auth-resolution' -import { resolveEffectiveProxy } from '../ssh-proxy-command' -import { walkInitialAuthLadder } from './ssh-connection-test-fixtures' +import { findDefaultKeyFile } from '../authentication/ssh-auth-resolution' +import { resolveEffectiveProxy } from '../system-transport/ssh-proxy-command' +import { walkInitialAuthLadder } from './testing/ssh-connection-test-fixtures' import type { SshTarget } from '../../../shared/ssh-types' import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' diff --git a/src/main/ssh/connection/ssh-connect-config.ts b/src/main/ssh/connection/ssh-connect-config.ts index a972d56d2d2..70d1829847e 100644 --- a/src/main/ssh/connection/ssh-connect-config.ts +++ b/src/main/ssh/connection/ssh-connect-config.ts @@ -9,8 +9,8 @@ import { resolvePrivateKeys, resolveUnencryptedExplicitPrivateKeys, type SkippedIdentityFiles -} from '../ssh-auth-resolution' -import { configurePrivateKeyAuthentication } from '../ssh-private-key-authentication' +} from '../authentication/ssh-auth-resolution' +import { configurePrivateKeyAuthentication } from '../authentication/ssh-private-key-authentication' import { isOpenSshConfigBackedTarget } from '../system-transport/system-ssh-args' import { CONNECT_TIMEOUT_MS } from './ssh-connection-timing' diff --git a/src/main/ssh/ssh-connect-failure-next-step.ts b/src/main/ssh/connection/ssh-connect-failure-next-step.ts similarity index 93% rename from src/main/ssh/ssh-connect-failure-next-step.ts rename to src/main/ssh/connection/ssh-connect-failure-next-step.ts index 4aa6e103f15..516aea6b260 100644 --- a/src/main/ssh/ssh-connect-failure-next-step.ts +++ b/src/main/ssh/connection/ssh-connect-failure-next-step.ts @@ -1,5 +1,5 @@ -import { isHostKeyVerificationError } from './ssh-host-key-decision' -import { isAuthError, isPassphraseError } from './ssh-reconnect-error-classification' +import { isHostKeyVerificationError } from '../host-keys/ssh-host-key-decision' +import { isAuthError, isPassphraseError } from './reconnect/ssh-reconnect-error-classification' type FailureKind = | 'host-key' diff --git a/src/main/ssh/connection/ssh-connection-attribution.test.ts b/src/main/ssh/connection/ssh-connection-attribution.test.ts index 08785feccec..0c80b226a91 100644 --- a/src/main/ssh/connection/ssh-connection-attribution.test.ts +++ b/src/main/ssh/connection/ssh-connection-attribution.test.ts @@ -6,7 +6,7 @@ import { recordSshConnectionOpened, runAttributedToSshOwner } from './ssh-connection-attribution' -import { unusedSshConnection } from '../unused-host-transport.test-fixture' +import { unusedSshConnection } from '../../managed-server/testing/managed-host-transport.test-fixture' const transport = (): SshConnection => unusedSshConnection() diff --git a/src/main/ssh/connection/ssh-connection-auth-fallback.test.ts b/src/main/ssh/connection/ssh-connection-auth-fallback.test.ts index a158b52e641..b378ec6485d 100644 --- a/src/main/ssh/connection/ssh-connection-auth-fallback.test.ts +++ b/src/main/ssh/connection/ssh-connection-auth-fallback.test.ts @@ -3,49 +3,58 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as Ssh2 from 'ssh2' -import { clientInstances, emitSshEvent, ssh2Mock } from '../__tests__/ssh-connection-test-client' -import { nextSshClientCreation, resetSshConnectionMocks } from './ssh-connection-test-harness' +import { clientInstances, emitSshEvent, ssh2Mock } from './testing/ssh-connection-test-client' +import { + nextSshClientCreation, + resetSshConnectionMocks +} from './testing/ssh-connection-test-harness' import { createCallbacks, createTarget, walkInitialAuthLadder -} from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' import '../config/ssh-g-config-resolution' -import { loadSsh2 } from '../ssh2-module-load' +import { loadSsh2 } from '../authentication/ssh2-module-load' const { utils } = loadSsh2() -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-channel-error.test.ts b/src/main/ssh/connection/ssh-connection-channel-error.test.ts index 352cdf62ac0..42e543e0756 100644 --- a/src/main/ssh/connection/ssh-connection-channel-error.test.ts +++ b/src/main/ssh/connection/ssh-connection-channel-error.test.ts @@ -1,41 +1,47 @@ import { EventEmitter } from 'node:events' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { SshConnection } from './ssh-connection' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' -import { resetSshConnectionMocks } from './ssh-connection-test-harness' -import { ssh2Mock } from '../__tests__/ssh-connection-test-client' -import * as sshClientMock from '../__tests__/ssh-connection-test-client' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' +import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' +import { ssh2Mock } from './testing/ssh-connection-test-client' +import * as sshClientMock from './testing/ssh-connection-test-client' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-channel-lifetime.test.ts b/src/main/ssh/connection/ssh-connection-channel-lifetime.test.ts deleted file mode 100644 index e722810e411..00000000000 --- a/src/main/ssh/connection/ssh-connection-channel-lifetime.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { EventEmitter } from 'node:events' -import { expect, it, vi } from 'vitest' -import { trackSshConnectionChannelLifetime } from './ssh-connection-channel-lifetime' - -it('removes its error listener when the channel closes', () => { - const channel = new EventEmitter() - trackSshConnectionChannelLifetime(channel) - expect(channel.listenerCount('error')).toBe(1) - channel.emit('close') - expect(channel.listenerCount('error')).toBe(0) -}) - -it('reports a channel error that nothing else handles instead of hiding it', () => { - const report = vi.fn() - const channel = new EventEmitter() - trackSshConnectionChannelLifetime(channel, report) - const failure = new Error('channel reset') - expect(() => channel.emit('error', failure)).not.toThrow() - expect(report).toHaveBeenCalledWith(failure) -}) - -it('leaves a channel error to the owner that handles it', () => { - const report = vi.fn() - const channel = new EventEmitter() - trackSshConnectionChannelLifetime(channel, report) - const owner = vi.fn() - channel.on('error', owner) - channel.emit('error', new Error('handled')) - expect(owner).toHaveBeenCalledOnce() - expect(report).not.toHaveBeenCalled() -}) diff --git a/src/main/ssh/connection/ssh-connection-channel-open.test.ts b/src/main/ssh/connection/ssh-connection-channel-open.test.ts index 495357c36d3..e2334dbebba 100644 --- a/src/main/ssh/connection/ssh-connection-channel-open.test.ts +++ b/src/main/ssh/connection/ssh-connection-channel-open.test.ts @@ -5,41 +5,47 @@ import { pendingExecCallback, pendingSftpCallback, ssh2Mock -} from '../__tests__/ssh-connection-test-client' -import { resetSshConnectionMocks } from './ssh-connection-test-harness' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-client' +import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-direct-startup.test.ts b/src/main/ssh/connection/ssh-connection-direct-startup.test.ts index 5d89106fafd..7d2f9878b22 100644 --- a/src/main/ssh/connection/ssh-connection-direct-startup.test.ts +++ b/src/main/ssh/connection/ssh-connection-direct-startup.test.ts @@ -1,41 +1,54 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { EventEmitter } from 'node:events' -import { resetSshConnectionMocks, spawnSystemSshCommandMock } from './ssh-connection-test-harness' -import { createCallbacks, createResolvedConfig, createTarget } from './ssh-connection-test-fixtures' -import type { createSystemCommandChannel } from './ssh-connection-test-fixtures' +import { + resetSshConnectionMocks, + spawnSystemSshCommandMock +} from './testing/ssh-connection-test-harness' +import { + createCallbacks, + createResolvedConfig, + createTarget +} from './testing/ssh-connection-test-fixtures' +import type { createSystemCommandChannel } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' import { resolveWithSshG } from '../config/ssh-g-config-resolution' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-file-transfer.test.ts b/src/main/ssh/connection/ssh-connection-file-transfer.test.ts index d4cdbdb37a4..86c2a029738 100644 --- a/src/main/ssh/connection/ssh-connection-file-transfer.test.ts +++ b/src/main/ssh/connection/ssh-connection-file-transfer.test.ts @@ -1,44 +1,54 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' -import { resetSshConnectionMocks } from './ssh-connection-test-harness' -import { createCallbacks, createResolvedConfig, createTarget } from './ssh-connection-test-fixtures' +import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' +import { + createCallbacks, + createResolvedConfig, + createTarget +} from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' import { resolveWithSshG } from '../config/ssh-g-config-resolution' import { uploadDirectoryViaSystemSsh, writeFileViaSystemSsh -} from '../system-transport/system-ssh-file-transfer' +} from '../system-transport/file-transfer/system-ssh-file-transfer' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-generation.test.ts b/src/main/ssh/connection/ssh-connection-generation.test.ts deleted file mode 100644 index 0010006fb37..00000000000 --- a/src/main/ssh/connection/ssh-connection-generation.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { - advanceSshConnectionGeneration, - assertSshMutationExpectation, - forgetSshConnectionGeneration, - getSshConnectionGeneration, - getSshConnectionGenerationEntryCountForTests, - resetSshConnectionGenerations, - setSshConnectionGeneration -} from './ssh-connection-generation' - -const SESSION_COUNTER_STRIDE = 2 ** 13 -const MAX_SESSION_SCOPE = 2 ** 40 - 1 - -describe('SSH connection generation session scope', () => { - afterEach(() => resetSshConnectionGenerations()) - - it('does not reuse a target token when a restarted HUB reaches the same counter', () => { - resetSshConnectionGenerations(41) - const beforeRestart = advanceSshConnectionGeneration('ssh-a') - - resetSshConnectionGenerations(42) - const afterRestart = advanceSshConnectionGeneration('ssh-a') - - expect(afterRestart).not.toBe(beforeRestart) - expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', beforeRestart)).toThrow( - 'SSH connection changed; refresh and try again' - ) - expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', afterRestart)).not.toThrow() - }) - - it('starts a recreated target above every generation its removed incarnation issued', () => { - resetSshConnectionGenerations(7) - const targetId = 'runtime-ssh-vm-1' - advanceSshConnectionGeneration(targetId) - const staleGeneration = advanceSshConnectionGeneration(targetId) - - forgetSshConnectionGeneration(targetId) - expect(() => assertSshMutationExpectation(targetId, targetId, staleGeneration)).toThrow( - 'SSH connection changed; refresh and try again' - ) - - const replacementGeneration = advanceSshConnectionGeneration(targetId) - - expect(replacementGeneration).toBeGreaterThan(staleGeneration) - expect(() => assertSshMutationExpectation(targetId, targetId, staleGeneration)).toThrow( - 'SSH connection changed; refresh and try again' - ) - expect(() => - assertSshMutationExpectation(targetId, targetId, replacementGeneration) - ).not.toThrow() - }) - - it('keeps the floor at the highest forgotten generation across repeated recreation', () => { - resetSshConnectionGenerations(7) - const issued: number[] = [] - for (let incarnation = 0; incarnation < 3; incarnation += 1) { - issued.push(advanceSshConnectionGeneration('runtime-ssh-vm-1')) - forgetSshConnectionGeneration('runtime-ssh-vm-1') - } - const lowerForgotten = advanceSshConnectionGeneration('ssh-short-lived') - forgetSshConnectionGeneration('ssh-short-lived') - - const replacement = advanceSshConnectionGeneration('runtime-ssh-vm-1') - - expect(new Set(issued).size).toBe(issued.length) - expect(replacement).toBeGreaterThan(Math.max(...issued, lowerForgotten)) - expect(getSshConnectionGenerationEntryCountForTests()).toBe(1) - }) - - it('drops the forgotten floor when exhaustion rolls the session scope', () => { - resetSshConnectionGenerations(7) - setSshConnectionGeneration('ssh-old', 8 * SESSION_COUNTER_STRIDE - 1) - forgetSshConnectionGeneration('ssh-old') - - const rolledGeneration = advanceSshConnectionGeneration('ssh-a') - - expect(rolledGeneration).toBe(8 * SESSION_COUNTER_STRIDE + 1) - expect(advanceSshConnectionGeneration('ssh-b')).toBe(rolledGeneration) - }) - - it('rejects an SSH execution-host expectation when direct IPC resolves locally', () => { - expect(() => - assertSshMutationExpectation(undefined, undefined, undefined, 'ssh:ssh-a') - ).toThrow('Workspace host changed; refresh and try again') - }) - - it('rejects a local execution-host expectation when direct IPC resolves through SSH', () => { - expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', 0, 'local')).toThrow( - 'Workspace host changed; refresh and try again' - ) - }) - - it('invalidates other targets when exhaustion rolls the session scope', () => { - resetSshConnectionGenerations(11) - const otherTargetGeneration = advanceSshConnectionGeneration('ssh-b') - setSshConnectionGeneration('ssh-a', 12 * SESSION_COUNTER_STRIDE - 1) - - const rolledGeneration = advanceSshConnectionGeneration('ssh-a') - - expect(getSshConnectionGeneration('ssh-b')).toBe(12 * SESSION_COUNTER_STRIDE) - expect(rolledGeneration).toBe(12 * SESSION_COUNTER_STRIDE + 1) - expect(() => assertSshMutationExpectation('ssh-b', 'ssh-b', otherTargetGeneration)).toThrow( - 'SSH connection changed; refresh and try again' - ) - expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', rolledGeneration)).not.toThrow() - }) - - it('wraps the maximum safe numeric scope without reusing it', () => { - resetSshConnectionGenerations(MAX_SESSION_SCOPE) - setSshConnectionGeneration('ssh-a', Number.MAX_SAFE_INTEGER) - - const rolledGeneration = advanceSshConnectionGeneration('ssh-a') - - expect(rolledGeneration).toBe(1) - expect(Number.isSafeInteger(rolledGeneration)).toBe(true) - expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', Number.MAX_SAFE_INTEGER)).toThrow( - 'SSH connection changed; refresh and try again' - ) - }) -}) diff --git a/src/main/ssh/connection/ssh-connection-gssapi-fallback.test.ts b/src/main/ssh/connection/ssh-connection-gssapi-fallback.test.ts index 0fb7e1c9a33..4416b159f3d 100644 --- a/src/main/ssh/connection/ssh-connection-gssapi-fallback.test.ts +++ b/src/main/ssh/connection/ssh-connection-gssapi-fallback.test.ts @@ -3,47 +3,56 @@ import { EventEmitter } from 'node:events' import 'node:fs' import 'node:os' import 'node:path' -import { ssh2Mock } from '../__tests__/ssh-connection-test-client' -import { resetSshConnectionMocks, spawnSystemSshCommandMock } from './ssh-connection-test-harness' +import { ssh2Mock } from './testing/ssh-connection-test-client' +import { + resetSshConnectionMocks, + spawnSystemSshCommandMock +} from './testing/ssh-connection-test-harness' import { createCallbacks, createResolvedConfig, type createSystemCommandChannel, createTarget -} from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' import { resolveWithSshG } from '../config/ssh-g-config-resolution' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-host-key-pin-race.test.ts b/src/main/ssh/connection/ssh-connection-host-key-pin-race.test.ts index 383afbd3fac..ed948bdbd92 100644 --- a/src/main/ssh/connection/ssh-connection-host-key-pin-race.test.ts +++ b/src/main/ssh/connection/ssh-connection-host-key-pin-race.test.ts @@ -1,29 +1,34 @@ import { expect, it, vi } from 'vitest' -import { clientInstances, ssh2Mock } from '../__tests__/ssh-connection-test-client' -import { resetSshConnectionMocks, spawnSystemSshCommandMock } from './ssh-connection-test-harness' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +import { clientInstances, ssh2Mock } from './testing/ssh-connection-test-client' +import { + resetSshConnectionMocks, + spawnSystemSshCommandMock +} from './testing/ssh-connection-test-harness' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( + await importOriginal() + ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) const { installMock } = vi.hoisted(() => ({ installMock: vi.fn() })) -vi.mock('./ssh2-host-key-verification', () => ({ +vi.mock('../host-keys/ssh2-host-key-verification', () => ({ installSsh2HostKeyVerification: installMock, readHostKeyTrustSources: vi.fn() })) diff --git a/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts b/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts index 88517fb956d..9e3b3c3dd9c 100644 --- a/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts +++ b/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts @@ -21,7 +21,7 @@ let eventHandlers: Map void>> let presentedHostKey: Buffer let hostKeyAccepted: boolean | undefined -vi.mock('../ssh2-module-load', async () => { +vi.mock('../authentication/ssh2-module-load', async () => { const { utils } = await vi.importActual('ssh2') class MockSshClient { setNoDelay = vi.fn() @@ -66,7 +66,11 @@ vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => ({ })) import { SshConnection } from './ssh-connection' -import { initSshHostKeyStoreFile, isTrusted, loadTrustedHostKeys } from '../ssh-host-key-store' +import { + initSshHostKeyStoreFile, + isTrusted, + loadTrustedHostKeys +} from '../host-keys/ssh-host-key-store' import type { SshTarget } from '../../../shared/ssh-types' const target = (overrides?: Partial): SshTarget => ({ diff --git a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts index 8954e2e605d..83d9c88b553 100644 --- a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts +++ b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts @@ -2,41 +2,47 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { connectAttempts, ssh2Mock } from '../__tests__/ssh-connection-test-client' -import { resetSshConnectionMocks } from './ssh-connection-test-harness' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +import { connectAttempts, ssh2Mock } from './testing/ssh-connection-test-client' +import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-loopback-cancel.test.ts b/src/main/ssh/connection/ssh-connection-loopback-cancel.test.ts index 6d5abf21e93..e2eedc2446d 100644 --- a/src/main/ssh/connection/ssh-connection-loopback-cancel.test.ts +++ b/src/main/ssh/connection/ssh-connection-loopback-cancel.test.ts @@ -1,8 +1,8 @@ import { EventEmitter } from 'node:events' import { PassThrough } from 'node:stream' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { resetSshConnectionMocks } from './ssh-connection-test-harness' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' const { startForwardMock, waitForwardMock } = vi.hoisted(() => ({ @@ -10,42 +10,46 @@ const { startForwardMock, waitForwardMock } = vi.hoisted(() => ({ waitForwardMock: vi.fn() })) -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( + await importOriginal() + ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) // Keep admission from invoking this machine's real ssh -G/ssh-add. -vi.mock('../system-transport/system-ssh-loopback-route-admission', () => ({ +vi.mock('../system-transport/forwarding/system-ssh-loopback-route-admission', () => ({ admitSystemSshLoopbackRoute: async () => ({ admitted: true, sshdPort: 22, hostKeyAlias: 'example.com' }) })) -vi.mock('../system-transport/system-ssh-loopback-route', async (importOriginal) => ({ +vi.mock('../system-transport/forwarding/system-ssh-loopback-route', async (importOriginal) => ({ ...(await importOriginal()), shouldUseSystemSshLoopbackRoute: () => true })) -vi.mock('../system-transport/system-ssh-forward-process', () => ({ +vi.mock('../system-transport/forwarding/system-ssh-forward-process', () => ({ startSystemSshPortForwardProcess: startForwardMock, waitForSystemSshForwardStartup: waitForwardMock })) diff --git a/src/main/ssh/connection/ssh-connection-loopback-route.test.ts b/src/main/ssh/connection/ssh-connection-loopback-route.test.ts index b0527310ac4..665ecd93b4c 100644 --- a/src/main/ssh/connection/ssh-connection-loopback-route.test.ts +++ b/src/main/ssh/connection/ssh-connection-loopback-route.test.ts @@ -1,42 +1,48 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { resetSshConnectionMocks } from './ssh-connection-test-harness' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' -import type { SystemSshLoopbackRoute } from '../system-transport/system-ssh-loopback-route' -import { uploadFileViaSystemSsh } from '../system-transport/system-ssh-file-binary-transfer' +import type { SystemSshLoopbackRoute } from '../system-transport/forwarding/system-ssh-loopback-route' +import { uploadFileViaSystemSsh } from '../system-transport/file-transfer/system-ssh-file-binary-transfer' const { startRouteMock } = vi.hoisted(() => ({ startRouteMock: vi.fn() })) -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( await importOriginal() ) ) +vi.mock('../system-transport/system-ssh-command', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() +) +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) // Force the Windows-gated route on here to exercise lifecycle; its own suite covers selection. -vi.mock('../system-transport/system-ssh-loopback-route', () => ({ +vi.mock('../system-transport/forwarding/system-ssh-loopback-route', () => ({ shouldUseSystemSshLoopbackRoute: () => true, startSystemSshLoopbackRoute: startRouteMock })) diff --git a/src/main/ssh/connection/ssh-connection-manager-registry.test.ts b/src/main/ssh/connection/ssh-connection-manager-registry.test.ts index f042988be6a..a050d699e9c 100644 --- a/src/main/ssh/connection/ssh-connection-manager-registry.test.ts +++ b/src/main/ssh/connection/ssh-connection-manager-registry.test.ts @@ -1,38 +1,44 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' -import { resetSsh2ClientState } from '../__tests__/ssh-connection-test-client' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +import { resetSsh2ClientState } from './testing/ssh-connection-test-client' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnectionManager } from './ssh-connection-manager' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts b/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts index 0aa1bee5f5c..679155ab77e 100644 --- a/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts +++ b/src/main/ssh/connection/ssh-connection-manager-sign-in-reuse.test.ts @@ -4,45 +4,51 @@ import { emitSshEvent, eventHandlers, ssh2Mock -} from '../__tests__/ssh-connection-test-client' -import { resetSshConnectionMocks } from './ssh-connection-test-harness' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-client' +import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnectionManager } from './ssh-connection-manager' import { recordSshCredentialDeclined, resetSshCredentialDeclinesForTests -} from '../ssh-credential-decline' +} from '../authentication/ssh-credential-decline' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-manager.test.ts b/src/main/ssh/connection/ssh-connection-manager.test.ts index d2a1092a63d..455b1a06b53 100644 --- a/src/main/ssh/connection/ssh-connection-manager.test.ts +++ b/src/main/ssh/connection/ssh-connection-manager.test.ts @@ -53,10 +53,10 @@ import { recordSshCredentialDeclined, recordSshSignInAwaited, resetSshCredentialDeclinesForTests -} from '../ssh-credential-decline' -import { isAuthError } from '../ssh-reconnect-error-classification' -import '../ssh-session-start-failure' -import { recordSshUserDisconnected, resetSshUserDisconnectsForTests } from '../ssh-user-disconnect' +} from '../authentication/ssh-credential-decline' +import { isAuthError } from './reconnect/ssh-reconnect-error-classification' +import './ssh-session-start-failure' +import { recordSshUserDisconnected, resetSshUserDisconnectsForTests } from './ssh-user-disconnect' const target = { id: 'target-1', diff --git a/src/main/ssh/connection/ssh-connection-manager.ts b/src/main/ssh/connection/ssh-connection-manager.ts index 6cbc72b2612..514b3bc30e9 100644 --- a/src/main/ssh/connection/ssh-connection-manager.ts +++ b/src/main/ssh/connection/ssh-connection-manager.ts @@ -5,10 +5,10 @@ import { recordSshConnectionOpened, recordSshConnectionReused } from './ssh-conn import { createSshCredentialDeclinedError, isSshCredentialDeclined -} from '../ssh-credential-decline' -import { createSshUserDisconnectedError, isSshUserDisconnected } from '../ssh-user-disconnect' +} from '../authentication/ssh-credential-decline' +import { createSshUserDisconnectedError, isSshUserDisconnected } from './ssh-user-disconnect' import { SSH_CONNECT_IN_PROGRESS_SUFFIX } from '../../../shared/ssh-sign-in-required-copy' -import { markSshSessionStartFailure } from '../ssh-session-start-failure' +import { markSshSessionStartFailure } from './ssh-session-start-failure' /** A remembered sign-in only applies to the endpoint it was given for; an edited host must ask. */ function signInEndpoint(target: SshTarget): string { diff --git a/src/main/ssh/connection/ssh-connection-reconnect-ladder.test.ts b/src/main/ssh/connection/ssh-connection-reconnect-ladder.test.ts index 5dac1343ade..4261aa06bf0 100644 --- a/src/main/ssh/connection/ssh-connection-reconnect-ladder.test.ts +++ b/src/main/ssh/connection/ssh-connection-reconnect-ladder.test.ts @@ -3,44 +3,50 @@ import { advanceToNextSshClient, connectWithFakeTimers, resetSshConnectionMocks -} from './ssh-connection-test-harness' -import { clientInstances, emitSshEvent, ssh2Mock } from '../__tests__/ssh-connection-test-client' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-harness' +import { clientInstances, emitSshEvent, ssh2Mock } from './testing/ssh-connection-test-client' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' import { resolveWithSshG } from '../config/ssh-g-config-resolution' import { RECONNECT_BACKOFF_MS } from './ssh-connection-timing' import '../../../shared/ssh-types' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts b/src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts index c34190e9eff..d4612f44005 100644 --- a/src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts +++ b/src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts @@ -6,11 +6,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as SystemSshArgs from '../system-transport/system-ssh-args' -import type * as SystemSshFileBinaryTransfer from '../system-transport/system-ssh-file-binary-transfer' -import type * as SystemSshFileTransfer from '../system-transport/system-ssh-file-transfer' +import type * as SystemSshFileBinaryTransfer from '../system-transport/file-transfer/system-ssh-file-binary-transfer' +import type * as SystemSshFileTransfer from '../system-transport/file-transfer/system-ssh-file-transfer' import type * as SshGConfigResolution from '../config/ssh-g-config-resolution' -vi.mock('../ssh2-module-load', () => { +vi.mock('../authentication/ssh2-module-load', () => { const ssh2 = { BaseAgent: class {}, Client: class {}, @@ -28,29 +28,32 @@ vi.mock('../system-transport/system-ssh-command', () => ({ spawnSystemSsh: vi.fn(), spawnSystemSshCommand: vi.fn() })) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => ({ - ...(await importOriginal()), - downloadFileViaSystemSsh: vi.fn().mockResolvedValue(undefined), - uploadFileViaSystemSsh: vi.fn().mockResolvedValue(undefined), - writeBufferViaSystemSsh: vi.fn().mockResolvedValue(undefined) -})) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => ({ +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => ({ + ...(await importOriginal()), + downloadFileViaSystemSsh: vi.fn().mockResolvedValue(undefined), + uploadFileViaSystemSsh: vi.fn().mockResolvedValue(undefined), + writeBufferViaSystemSsh: vi.fn().mockResolvedValue(undefined) + }) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => ({ ...(await importOriginal()), uploadDirectoryViaSystemSsh: vi.fn().mockResolvedValue(undefined), writeFileViaSystemSsh: vi.fn().mockResolvedValue(undefined) })) -vi.mock('../ssh-control-socket', () => ({ removeControlSocketPath: vi.fn() })) +vi.mock('../system-transport/ssh-control-socket', () => ({ removeControlSocketPath: vi.fn() })) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => ({ ...(await importOriginal()), resolveWithSshG: vi.fn().mockResolvedValue(null) })) import { SshConnection } from './ssh-connection' -import type { SftpNamespacePathMapping } from '../sftp-namespace-resolution' -import { getRemoteHostPlatform } from '../ssh-remote-platform' -import '../ssh-session-limit-error' -import '../system-transport/system-ssh-file-transfer' +import type { SftpNamespacePathMapping } from '../file-transfer/sftp/sftp-namespace-resolution' +import { getRemoteHostPlatform } from '../remote-host/ssh-remote-platform' +import './ssh-session-limit-error' +import '../system-transport/file-transfer/system-ssh-file-transfer' import type { SshTarget } from '../../../shared/ssh-types' const SHELL_HOME = '/var/services/homes/alice' diff --git a/src/main/ssh/connection/ssh-connection-sftp-wire.test.ts b/src/main/ssh/connection/ssh-connection-sftp-wire.test.ts index 41f37d5e3d1..abc5d2a2bdc 100644 --- a/src/main/ssh/connection/ssh-connection-sftp-wire.test.ts +++ b/src/main/ssh/connection/ssh-connection-sftp-wire.test.ts @@ -5,8 +5,8 @@ import { Client, Server as Ssh2Server, utils, type Connection, type SFTPWrapper import { expect, it, vi } from 'vitest' import type { SshTarget } from '../../../shared/ssh-types' import { SshConnection } from './ssh-connection' -import type { SftpNamespacePathMapping } from '../sftp-namespace-resolution' -import { getRemoteHostPlatform } from '../ssh-remote-platform' +import type { SftpNamespacePathMapping } from '../file-transfer/sftp/sftp-namespace-resolution' +import { getRemoteHostPlatform } from '../remote-host/ssh-remote-platform' const SHELL_HOME = '/var/services/homes/alice' const SFTP_HOME = '/homes/alice' diff --git a/src/main/ssh/connection/ssh-connection-system-transport.test.ts b/src/main/ssh/connection/ssh-connection-system-transport.test.ts index 592753f739f..6daac261f7f 100644 --- a/src/main/ssh/connection/ssh-connection-system-transport.test.ts +++ b/src/main/ssh/connection/ssh-connection-system-transport.test.ts @@ -2,14 +2,14 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { clientInstances, ssh2Mock } from '../__tests__/ssh-connection-test-client' +import { clientInstances, ssh2Mock } from './testing/ssh-connection-test-client' import { findSystemSshMock, getOrcaControlSocketPathMock, removeControlSocketPathMock, resetSshConnectionMocks, spawnSystemSshCommandMock -} from './ssh-connection-test-harness' +} from './testing/ssh-connection-test-harness' import { createCallbacks, createFailingSystemCommandChannel, @@ -17,49 +17,55 @@ import { createResolvedConfig, createSystemCommandChannel, createTarget -} from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' -import '../ssh-transport-selection' +import '../system-transport/ssh-transport-selection' import { resolveWithSshG } from '../config/ssh-g-config-resolution' -import { writeFileViaSystemSsh } from '../system-transport/system-ssh-file-transfer' +import { writeFileViaSystemSsh } from '../system-transport/file-transfer/system-ssh-file-transfer' import { CONNECT_TIMEOUT_MS } from './ssh-connection-timing' -import { initSshHostKeyStoreFile, trustHostKey } from '../ssh-host-key-store' +import { initSshHostKeyStoreFile, trustHostKey } from '../host-keys/ssh-host-key-store' import type { SshTarget } from '../../../shared/ssh-types' import { createOpenSshPrivateKeyFixture, createOpenSshPublicKeyFixture -} from '../ssh-security-key-identity.test-fixture' +} from '../authentication/testing/ssh-security-key-identity.test-fixture' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection-wake-retry.test.ts b/src/main/ssh/connection/ssh-connection-wake-retry.test.ts index 2bb6f91660f..d00bc4305a7 100644 --- a/src/main/ssh/connection/ssh-connection-wake-retry.test.ts +++ b/src/main/ssh/connection/ssh-connection-wake-retry.test.ts @@ -5,50 +5,56 @@ import { nextSshClientCreation, resetSshConnectionMocks, spawnSystemSshCommandMock -} from './ssh-connection-test-harness' -import { clientInstances, emitSshEvent, ssh2Mock } from '../__tests__/ssh-connection-test-client' +} from './testing/ssh-connection-test-harness' +import { clientInstances, emitSshEvent, ssh2Mock } from './testing/ssh-connection-test-client' import { createCallbacks, createHangingSystemCommandChannel, createResolvedConfig, createTarget -} from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' import { resolveWithSshG } from '../config/ssh-g-config-resolution' import { RECONNECT_BACKOFF_MS } from './ssh-connection-timing' -import { recordSshUserDisconnected, resetSshUserDisconnectsForTests } from '../ssh-user-disconnect' +import { recordSshUserDisconnected, resetSshUserDisconnectsForTests } from './ssh-user-disconnect' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection.test.ts b/src/main/ssh/connection/ssh-connection.test.ts index 1f3c223f0e8..43f432054f4 100644 --- a/src/main/ssh/connection/ssh-connection.test.ts +++ b/src/main/ssh/connection/ssh-connection.test.ts @@ -5,41 +5,50 @@ import { eventHandlers, VALID_ED25519_HOST_KEY, ssh2Mock -} from '../__tests__/ssh-connection-test-client' -import { nextSshClientCreation, resetSshConnectionMocks } from './ssh-connection-test-harness' -import { createCallbacks, createTarget } from './ssh-connection-test-fixtures' +} from './testing/ssh-connection-test-client' +import { + nextSshClientCreation, + resetSshConnectionMocks +} from './testing/ssh-connection-test-harness' +import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' -vi.mock('../ssh2-module-load', async () => - (await import('../__tests__/ssh-connection-test-client')).createSsh2LoaderModule() +vi.mock('../authentication/ssh2-module-load', async () => + (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() ) vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./ssh-connection-test-harness')).createSystemSshBinaryModule() + (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() ) vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshArgsMocks(await importOriginal()) + (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( + await importOriginal() + ) ) vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshCommandMocks(await importOriginal()) -) -vi.mock('../system-transport/system-ssh-file-binary-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( await importOriginal() ) ) -vi.mock('../system-transport/system-ssh-file-transfer', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSystemSshFileTransferMocks( +vi.mock( + '../system-transport/file-transfer/system-ssh-file-binary-transfer', + async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( + await importOriginal() + ) +) +vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => + (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( await importOriginal() ) ) -vi.mock('../ssh-control-socket', async () => - (await import('./ssh-connection-test-harness')).createControlSocketModule() +vi.mock('../system-transport/ssh-control-socket', async () => + (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() ) vi.mock('../config/ssh-config-parser', async () => - (await import('./ssh-connection-test-harness')).createSshConfigParserModule() + (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() ) vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./ssh-connection-test-harness')).withSshGConfigResolutionMocks( + (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( await importOriginal() ) ) diff --git a/src/main/ssh/connection/ssh-connection.ts b/src/main/ssh/connection/ssh-connection.ts index 1297f605894..37a621f00d5 100644 --- a/src/main/ssh/connection/ssh-connection.ts +++ b/src/main/ssh/connection/ssh-connection.ts @@ -7,7 +7,7 @@ import { writeSshFile, type SshFileTransferHost, type SshRemoteFileOptions -} from './ssh-connection-file-transfers' +} from '../file-transfer/ssh-connection-file-transfers' import type { ChildProcess } from 'node:child_process' import type { Client as SshClient, @@ -28,31 +28,34 @@ import { shouldUseSystemSshLoopbackRoute, startSystemSshLoopbackRoute, type SystemSshLoopbackRoute -} from '../system-transport/system-ssh-loopback-route' -import { removeControlSocketPath } from '../ssh-control-socket' +} from '../system-transport/forwarding/system-ssh-loopback-route' +import { removeControlSocketPath } from '../system-transport/ssh-control-socket' import { INITIAL_RETRY_ATTEMPTS, INITIAL_RETRY_DELAY_MS, sleep } from './ssh-connection-timing' import { isTransientError, isAuthError, isPassphraseError, isDefiniteSystemSshHostFailure -} from '../ssh-reconnect-error-classification' +} from './reconnect/ssh-reconnect-error-classification' import { buildConnectConfig } from './ssh-connect-config' -import { withSkippedIdentityFileDetail, type SkippedIdentityFiles } from '../ssh-auth-resolution' +import { + withSkippedIdentityFileDetail, + type SkippedIdentityFiles +} from '../authentication/ssh-auth-resolution' import { createSshOperationAbortError, type SshExecOptions } from './ssh-exec-options' import type { SshConnectionCallbacks, SshCredentialKind } from './ssh-connection-callbacks' -import { collectKeyboardInteractiveResponses } from '../ssh-keyboard-interactive' -import { resolveEffectiveProxy, spawnProxyCommand } from '../ssh-proxy-command' +import { collectKeyboardInteractiveResponses } from '../authentication/ssh-keyboard-interactive' +import { resolveEffectiveProxy, spawnProxyCommand } from '../system-transport/ssh-proxy-command' import { resolveWithSshG, type SshResolvedConfig } from '../config/ssh-g-config-resolution' import { createCancelledConnectAttemptError, isCancelledConnectAttemptError -} from '../ssh-connect-attempt-cancellation' +} from './reconnect/ssh-connect-attempt-cancellation' import { mayUserSshConfigClaimAlias } from '../config/ssh-config-alias-claim' import { requiresSystemSshForSecurityKey, shouldUseSystemSshTransport -} from '../ssh-transport-selection' +} from '../system-transport/ssh-transport-selection' import type { FileUploadSession } from '../../providers/filesystem-provider-contract' import { openSshExecChannel, @@ -60,22 +63,22 @@ import { openSshShellChannel, spawnTrackedSystemSshChannel, type SshSessionChannelHost -} from './ssh-connection-session-channels' +} from './channels/ssh-connection-session-channels' import { SshConnectionReconnector, type SshConnectionReconnectHost -} from './ssh-connection-reconnect' +} from './reconnect/ssh-connection-reconnect' import { cloneResolvedConfig, waitForSystemSshProbe } from './ssh-system-ssh-probe' import { installSsh2HostKeyVerification, readHostKeyTrustSources, type HostKeyTrustSources -} from './ssh2-host-key-verification' -import { runSsh2Handshake } from './ssh2-handshake' +} from '../host-keys/ssh2-host-key-verification' +import { runSsh2Handshake } from '../authentication/ssh2-handshake' import { recoverFailedSsh2Attempt, type Ssh2CredentialFallbackHost -} from './ssh2-credential-fallback' +} from '../authentication/ssh2-credential-fallback' /** The sign-in a connection holds in memory, handed to the connection that replaces it. */ export type SshCachedCredentials = { password: string | null; passphrase: string | null } diff --git a/src/main/ssh/ssh-session-limit-error.ts b/src/main/ssh/connection/ssh-session-limit-error.ts similarity index 100% rename from src/main/ssh/ssh-session-limit-error.ts rename to src/main/ssh/connection/ssh-session-limit-error.ts diff --git a/src/main/ssh/ssh-session-start-failure.ts b/src/main/ssh/connection/ssh-session-start-failure.ts similarity index 100% rename from src/main/ssh/ssh-session-start-failure.ts rename to src/main/ssh/connection/ssh-session-start-failure.ts diff --git a/src/main/ssh/connection/ssh-system-ssh-probe.ts b/src/main/ssh/connection/ssh-system-ssh-probe.ts index 58f5faec5a6..b471c524ab1 100644 --- a/src/main/ssh/connection/ssh-system-ssh-probe.ts +++ b/src/main/ssh/connection/ssh-system-ssh-probe.ts @@ -2,7 +2,7 @@ import type { ClientChannel } from 'ssh2' import type { SshTarget } from '../../../shared/ssh-types' import { isOpenSshConfigBackedTarget } from '../system-transport/system-ssh-args' import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' -import { createCancelledConnectAttemptError } from '../ssh-connect-attempt-cancellation' +import { createCancelledConnectAttemptError } from './reconnect/ssh-connect-attempt-cancellation' import { CONNECT_TIMEOUT_MS } from './ssh-connection-timing' export function cloneResolvedConfig(config: SshResolvedConfig | null): SshResolvedConfig | null { diff --git a/src/main/ssh/ssh-user-disconnect.ts b/src/main/ssh/connection/ssh-user-disconnect.ts similarity index 91% rename from src/main/ssh/ssh-user-disconnect.ts rename to src/main/ssh/connection/ssh-user-disconnect.ts index a3d9dc55213..c5883d42598 100644 --- a/src/main/ssh/ssh-user-disconnect.ts +++ b/src/main/ssh/connection/ssh-user-disconnect.ts @@ -1,8 +1,8 @@ -import { formatSshUserDisconnectedMessage } from '../../shared/ssh-user-disconnect-message' +import { formatSshUserDisconnectedMessage } from '../../../shared/ssh-user-disconnect-message' import { getRuntimeSshAccess, type KnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../shared/remote-runtime/host-catalog/runtime-environments' /** Session-only disconnect blocks every background dial until explicit connect; restart clears both SSH and managed-server disconnects together. */ const userDisconnectedTargets = new Set() diff --git a/src/main/ssh/__tests__/ssh-connection-test-client.ts b/src/main/ssh/connection/testing/ssh-connection-test-client.ts similarity index 100% rename from src/main/ssh/__tests__/ssh-connection-test-client.ts rename to src/main/ssh/connection/testing/ssh-connection-test-client.ts diff --git a/src/main/ssh/connection/ssh-connection-test-fixtures.ts b/src/main/ssh/connection/testing/ssh-connection-test-fixtures.ts similarity index 95% rename from src/main/ssh/connection/ssh-connection-test-fixtures.ts rename to src/main/ssh/connection/testing/ssh-connection-test-fixtures.ts index c550ab40441..e0d8f2ffcff 100644 --- a/src/main/ssh/connection/ssh-connection-test-fixtures.ts +++ b/src/main/ssh/connection/testing/ssh-connection-test-fixtures.ts @@ -2,9 +2,9 @@ import { EventEmitter } from 'node:events' import { vi } from 'vitest' import type { Mock } from 'vitest' import type { AnyAuthMethod, AuthenticationType } from 'ssh2' -import type { SshConnectionCallbacks } from './ssh-connection-callbacks' -import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' -import type { SshTarget } from '../../../shared/ssh-types' +import type { SshConnectionCallbacks } from '../ssh-connection-callbacks' +import type { SshResolvedConfig } from '../../config/ssh-g-config-resolution' +import type { SshTarget } from '../../../../shared/ssh-types' export function createTarget(overrides?: Partial): SshTarget { return { diff --git a/src/main/ssh/connection/ssh-connection-test-harness.ts b/src/main/ssh/connection/testing/ssh-connection-test-harness.ts similarity index 85% rename from src/main/ssh/connection/ssh-connection-test-harness.ts rename to src/main/ssh/connection/testing/ssh-connection-test-harness.ts index 9289eb6e853..71d39576faa 100644 --- a/src/main/ssh/connection/ssh-connection-test-harness.ts +++ b/src/main/ssh/connection/testing/ssh-connection-test-harness.ts @@ -1,16 +1,16 @@ import { vi } from 'vitest' import { createSystemCommandChannel, createSystemSshProcess } from './ssh-connection-test-fixtures' -import type { SshConnection } from './ssh-connection' +import type { SshConnection } from '../ssh-connection' import type { MockSystemCommandChannel, MockSystemSshProcess } from './ssh-connection-test-fixtures' -import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' -import type { SystemSshBuildArgsOptions } from '../system-transport/system-ssh-args' -import type { SshTarget } from '../../../shared/ssh-types' -import type * as SystemSshArgs from '../system-transport/system-ssh-args' -import type * as SystemSshCommand from '../system-transport/system-ssh-command' -import type * as SystemSshFileBinaryTransfer from '../system-transport/system-ssh-file-binary-transfer' -import type * as SystemSshFileTransfer from '../system-transport/system-ssh-file-transfer' -import type * as SshGConfigResolution from '../config/ssh-g-config-resolution' -import { resetSsh2ClientState, ssh2Mock } from '../__tests__/ssh-connection-test-client' +import type { SshResolvedConfig } from '../../config/ssh-g-config-resolution' +import type { SystemSshBuildArgsOptions } from '../../system-transport/system-ssh-args' +import type { SshTarget } from '../../../../shared/ssh-types' +import type * as SystemSshArgs from '../../system-transport/system-ssh-args' +import type * as SystemSshCommand from '../../system-transport/system-ssh-command' +import type * as SystemSshFileBinaryTransfer from '../../system-transport/file-transfer/system-ssh-file-binary-transfer' +import type * as SystemSshFileTransfer from '../../system-transport/file-transfer/system-ssh-file-transfer' +import type * as SshGConfigResolution from '../../config/ssh-g-config-resolution' +import { resetSsh2ClientState, ssh2Mock } from './ssh-connection-test-client' export type SystemSshBinaryModuleMock = { findSystemSsh: typeof findSystemSshMock } diff --git a/src/main/ssh/config/vscode-ssh-authority.ts b/src/main/ssh/external-editors/vscode-ssh-authority.ts similarity index 100% rename from src/main/ssh/config/vscode-ssh-authority.ts rename to src/main/ssh/external-editors/vscode-ssh-authority.ts diff --git a/src/main/ssh/config/zed-ssh-url.test.ts b/src/main/ssh/external-editors/zed-ssh-url.test.ts similarity index 100% rename from src/main/ssh/config/zed-ssh-url.test.ts rename to src/main/ssh/external-editors/zed-ssh-url.test.ts diff --git a/src/main/ssh/config/zed-ssh-url.ts b/src/main/ssh/external-editors/zed-ssh-url.ts similarity index 100% rename from src/main/ssh/config/zed-ssh-url.ts rename to src/main/ssh/external-editors/zed-ssh-url.ts diff --git a/src/main/ssh/sftp-file-upload.ts b/src/main/ssh/file-transfer/sftp/sftp-file-upload.ts similarity index 98% rename from src/main/ssh/sftp-file-upload.ts rename to src/main/ssh/file-transfer/sftp/sftp-file-upload.ts index d1fe4788452..87e4acefeb2 100644 --- a/src/main/ssh/sftp-file-upload.ts +++ b/src/main/ssh/file-transfer/sftp/sftp-file-upload.ts @@ -4,7 +4,7 @@ import { lstat, open } from 'node:fs/promises' import { finished } from 'node:stream/promises' import type { SFTPWrapper } from 'ssh2' import { latchLateSftpStreamErrors, type SftpStreamErrorLatch } from './sftp-stream-late-error' -import { sftpSessionClosedError } from './ssh-file-transfer-abort' +import { sftpSessionClosedError } from '../ssh-file-transfer-abort' // Buffer 2 MiB so ssh2 _writev pipelines requests instead of waiting one RTT per chunk, matching fastPut's 64 × 32 KiB window. export const SFTP_UPLOAD_IN_FLIGHT_BYTES = 2 * 1024 * 1024 diff --git a/src/main/ssh/sftp-handshake-corruption.ts b/src/main/ssh/file-transfer/sftp/sftp-handshake-corruption.ts similarity index 100% rename from src/main/ssh/sftp-handshake-corruption.ts rename to src/main/ssh/file-transfer/sftp/sftp-handshake-corruption.ts diff --git a/src/main/ssh/sftp-namespace-resolution.ts b/src/main/ssh/file-transfer/sftp/sftp-namespace-resolution.ts similarity index 96% rename from src/main/ssh/sftp-namespace-resolution.ts rename to src/main/ssh/file-transfer/sftp/sftp-namespace-resolution.ts index c614a758fa2..0f0abaaac2c 100644 --- a/src/main/ssh/sftp-namespace-resolution.ts +++ b/src/main/ssh/file-transfer/sftp/sftp-namespace-resolution.ts @@ -1,9 +1,12 @@ // Map differing shell/SFTP namespaces, such as Synology /var/services/homes/alice vs /homes/alice. See docs/ssh-relay-sftp-namespace.md. import type { SFTPWrapper } from 'ssh2' -import { assertSafeRemotePathSegment, isWindowsRemoteHost } from './ssh-remote-platform' -import type { RemoteHostPlatform } from './ssh-remote-platform' -import { redactRelayInstallMarkerTokens } from '../managed-server/install/remote-install-marker' +import { + assertSafeRemotePathSegment, + isWindowsRemoteHost +} from '../../remote-host/ssh-remote-platform' +import type { RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' +import { redactRelayInstallMarkerTokens } from '../../../managed-server/install/remote-install-marker' export type SftpNamespacePathMapping = { homeRelativeNamespaceRoot: string diff --git a/src/main/ssh/sftp-stream-late-error.test.ts b/src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts similarity index 79% rename from src/main/ssh/sftp-stream-late-error.test.ts rename to src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts index f60141a8a05..60ab686b110 100644 --- a/src/main/ssh/sftp-stream-late-error.test.ts +++ b/src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts @@ -5,10 +5,11 @@ import { EventEmitter } from 'node:events' import { PassThrough } from 'node:stream' import type { SFTPWrapper } from 'ssh2' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { uploadBuffer, uploadFile, writeStringViaSftp } from './sftp-upload' -import { writeRemoteInstallFile } from '../managed-server/install/remote-install-transfers' -import type { SshConnection } from './connection/ssh-connection' -import { getRemoteHostPlatform } from './ssh-remote-platform' +import { uploadBuffer, writeStringViaSftp } from './sftp-upload' +import { uploadFile } from './sftp-file-upload' +import { writeRemoteInstallFile } from '../../../managed-server/install/remote-install-transfers' +import type { SshConnection } from '../../connection/ssh-connection' +import { getRemoteHostPlatform } from '../../remote-host/ssh-remote-platform' function sftpNoSuchFileError(): Error { return Object.assign(new Error('file does not exist'), { code: 2 }) @@ -98,20 +99,4 @@ describe('sandboxed SFTP subsystem diagnosis', () => { expect((failure as Error).message).toBe('permission denied') expect(failure).not.toHaveProperty('sandboxedSftpNamespace') }) - - it('replaces the bare SFTP status with an actionable relay-install message', async () => { - const conn = { - writeFile: () => Promise.reject(sftpNoSuchFileError()) - } as unknown as SshConnection - - // Windows hosts have no exec-stdin fallback; POSIX hosts stream instead (exec-fallback tests). - await expect( - writeRemoteInstallFile( - conn, - getRemoteHostPlatform('win32-x64'), - 'C:/Users/user/.orca-remote/relay-1/.version', - 'v1' - ) - ).rejects.toThrow(/SFTP subsystem sees a different filesystem/) - }) }) diff --git a/src/main/ssh/sftp-stream-late-error.ts b/src/main/ssh/file-transfer/sftp/sftp-stream-late-error.ts similarity index 100% rename from src/main/ssh/sftp-stream-late-error.ts rename to src/main/ssh/file-transfer/sftp/sftp-stream-late-error.ts diff --git a/src/main/ssh/sftp-upload-pipeline.test.ts b/src/main/ssh/file-transfer/sftp/sftp-upload-pipeline.test.ts similarity index 99% rename from src/main/ssh/sftp-upload-pipeline.test.ts rename to src/main/ssh/file-transfer/sftp/sftp-upload-pipeline.test.ts index a242c46c1b6..5bd15c88081 100644 --- a/src/main/ssh/sftp-upload-pipeline.test.ts +++ b/src/main/ssh/file-transfer/sftp/sftp-upload-pipeline.test.ts @@ -5,7 +5,7 @@ import { join, posix } from 'node:path' import type { SFTPWrapper, WriteStreamOptions } from 'ssh2' import { SFTP } from 'ssh2/lib/protocol/SFTP.js' import { describe, expect, it, vi } from 'vitest' -import { uploadSshDirectory } from './connection/ssh-connection-file-transfers' +import { uploadSshDirectory } from '../ssh-connection-file-transfers' import './sftp-upload' function uploadSession(options?: { diff --git a/src/main/ssh/sftp-upload.test.ts b/src/main/ssh/file-transfer/sftp/sftp-upload.test.ts similarity index 73% rename from src/main/ssh/sftp-upload.test.ts rename to src/main/ssh/file-transfer/sftp/sftp-upload.test.ts index 303ec826524..7ee08e40771 100644 --- a/src/main/ssh/sftp-upload.test.ts +++ b/src/main/ssh/file-transfer/sftp/sftp-upload.test.ts @@ -7,7 +7,8 @@ import { Writable } from 'node:stream' import { describe, expect, it, vi } from 'vitest' import type { SFTPWrapper, WriteStreamOptions } from 'ssh2' import { SFTP } from 'ssh2/lib/protocol/SFTP.js' -import { uploadDirectory, uploadFile } from './sftp-upload' +import { uploadDirectory } from './sftp-upload' +import { uploadFile } from './sftp-file-upload' function createWritable(): Writable { return new Writable({ @@ -102,39 +103,6 @@ describe('sftp-upload', () => { await rm(localDir, { recursive: true, force: true }) } }) - - it('never throws an uncaught error when a quit aborts an upload whose read already ended', async () => { - const localDir = await mkdtemp(join(tmpdir(), 'orca-sftp-upload-quit-')) - const localPath = join(localDir, 'orcad.js') - const controller = new AbortController() - // Accepts every byte but never finishes, as a remote write still flushing at quit does. - const flushing = new Writable({ - write(_chunk, _encoding, callback) { - callback() - }, - final() {} - }) - const sftp = createSftpMock() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the upload only pipes into and awaits this stream. - vi.mocked(sftp.createWriteStream).mockReturnValue(flushing as never) - const uncaught = vi.fn() - process.prependListener('uncaughtException', uncaught) - try { - await writeFile(localPath, Buffer.alloc(64 * 1024, 7)) - const upload = uploadFile(sftp, localPath, '/remote/orcad.js', { signal: controller.signal }) - upload.catch(() => {}) - await new Promise((resolve) => setTimeout(resolve, 50)) - - // The quit's disconnect aborts with the signal's own AbortError as the reason. - controller.abort() - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(uncaught).not.toHaveBeenCalled() - } finally { - process.off('uncaughtException', uncaught) - flushing.destroy() - await rm(localDir, { recursive: true, force: true }) - } - }) }) describe('uploadFile over a high-latency link', () => { @@ -187,27 +155,6 @@ describe('uploadFile over a high-latency link', () => { return { sftp: sftp as unknown as SFTPWrapper, written, maxInFlight: () => peak } } - it('keeps many writes in flight instead of one chunk per round trip', async () => { - const dir = await mkdtemp(join(tmpdir(), 'orca-sftp-upload-')) - const contents = Buffer.alloc(4 * 1024 * 1024) - for (let i = 0; i < contents.length; i += 4096) { - contents[i] = i % 251 - } - await writeFile(join(dir, 'node.tar.gz'), contents) - const { sftp, written, maxInFlight } = slowSftp(20) - try { - await uploadFile(sftp, join(dir, 'node.tar.gz'), '/remote/node.tar.gz') - // One 64 KiB read chunk per round trip would keep a single write in flight. - expect(maxInFlight()).toBeGreaterThanOrEqual(8) - const reassembled = Buffer.concat( - [...written.entries()].sort(([a], [b]) => a - b).map(([, chunk]) => chunk) - ) - expect(reassembled.equals(contents)).toBe(true) - } finally { - await rm(dir, { recursive: true, force: true }) - } - }) - it('fails, as contact lost, when the SSH session closes under a stalled upload', async () => { const dir = await mkdtemp(join(tmpdir(), 'orca-sftp-upload-')) await writeFile(join(dir, 'node.tar.gz'), Buffer.alloc(8 * 1024 * 1024)) diff --git a/src/main/ssh/sftp-upload.ts b/src/main/ssh/file-transfer/sftp/sftp-upload.ts similarity index 97% rename from src/main/ssh/sftp-upload.ts rename to src/main/ssh/file-transfer/sftp/sftp-upload.ts index 1cadc9fbfd6..6a32d66339d 100644 --- a/src/main/ssh/sftp-upload.ts +++ b/src/main/ssh/file-transfer/sftp/sftp-upload.ts @@ -2,15 +2,13 @@ import { lstat, readdir, realpath } from 'node:fs/promises' import { isAbsolute, join as pathJoin, relative, sep } from 'node:path' import { promisify } from 'node:util' import type { SFTPWrapper } from 'ssh2' -import { createSshOperationAbortError } from './connection/ssh-exec-options' +import { createSshOperationAbortError } from '../../connection/ssh-exec-options' import { SFTP_UPLOAD_IN_FLIGHT_BYTES, uploadFileWithWindow } from './sftp-file-upload' import { latchLateSftpStreamErrors } from './sftp-stream-late-error' import { createLinkedSshFileTransferSignal, raceSftpFileTransferWithAbort -} from './ssh-file-transfer-abort' - -export { SFTP_UPLOAD_IN_FLIGHT_BYTES, uploadFile } from './sftp-file-upload' +} from '../ssh-file-transfer-abort' function mkdirSftp( sftp: SFTPWrapper, diff --git a/src/main/ssh/connection/ssh-connection-file-transfer-session-lost.test.ts b/src/main/ssh/file-transfer/ssh-connection-file-transfer-session-lost.test.ts similarity index 74% rename from src/main/ssh/connection/ssh-connection-file-transfer-session-lost.test.ts rename to src/main/ssh/file-transfer/ssh-connection-file-transfer-session-lost.test.ts index f920b6184d2..d10c47bd10d 100644 --- a/src/main/ssh/connection/ssh-connection-file-transfer-session-lost.test.ts +++ b/src/main/ssh/file-transfer/ssh-connection-file-transfer-session-lost.test.ts @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { uploadSshDirectory, type SshFileTransferHost } from './ssh-connection-file-transfers' // Model ssh2 session loss: queued requests and write-stream CLOSE never answer, leaving transfers pending. -vi.mock('../sftp-upload', () => ({ uploadDirectory: vi.fn(() => new Promise(() => {})) })) +vi.mock('./sftp/sftp-upload', () => ({ uploadDirectory: vi.fn(() => new Promise(() => {})) })) function hostWith( sftp: EventEmitter, @@ -38,7 +38,7 @@ describe('an SFTP transfer whose SSH connection dies', () => { const sftp = fakeSession() const upload = uploadSshDirectory(hostWith(sftp), '/local/runtime', '/root/.orca-remote/x') await vi.waitFor(async () => { - const { uploadDirectory } = await import('../sftp-upload') + const { uploadDirectory } = await import('./sftp/sftp-upload') expect(uploadDirectory).toHaveBeenCalled() }) sftp.emit('close') @@ -48,7 +48,7 @@ describe('an SFTP transfer whose SSH connection dies', () => { }) expect(sftp.listenerCount('close')).toBe(0) // The abandoned transfer is cancelled too, so it stops and closes its local files. - const { uploadDirectory } = await import('../sftp-upload') + const { uploadDirectory } = await import('./sftp/sftp-upload') const transferSignal = vi.mocked(uploadDirectory).mock.calls[0]?.[4]?.signal expect(transferSignal?.aborted).toBe(true) }) @@ -57,21 +57,10 @@ describe('an SFTP transfer whose SSH connection dies', () => { const sftp = fakeSession() const cancel = new AbortController() const upload = uploadSshDirectory(hostWith(sftp, cancel.signal), '/local/r', '/root/r') - const { uploadDirectory } = await import('../sftp-upload') + const { uploadDirectory } = await import('./sftp/sftp-upload') await vi.waitFor(() => expect(uploadDirectory).toHaveBeenCalled()) cancel.abort() sftp.emit('close') await expect(upload).rejects.toMatchObject({ name: 'AbortError' }) }) - - it('ignores a session close after the transfer finished', async () => { - const { uploadDirectory } = await import('../sftp-upload') - vi.mocked(uploadDirectory).mockResolvedValueOnce(undefined) - const sftp = fakeSession() - await uploadSshDirectory(hostWith(sftp), '/local/r', '/root/r') - expect(sftp.ended).toBe(1) - // The close that ending the session produces is expected, so nothing is left listening. - sftp.emit('close') - expect(sftp.listenerCount('close')).toBe(0) - }) }) diff --git a/src/main/ssh/connection/ssh-connection-file-transfers.ts b/src/main/ssh/file-transfer/ssh-connection-file-transfers.ts similarity index 93% rename from src/main/ssh/connection/ssh-connection-file-transfers.ts rename to src/main/ssh/file-transfer/ssh-connection-file-transfers.ts index 9edfdc0fc7d..f03824f1381 100644 --- a/src/main/ssh/connection/ssh-connection-file-transfers.ts +++ b/src/main/ssh/file-transfer/ssh-connection-file-transfers.ts @@ -4,22 +4,22 @@ import type { FileUploadSession } from '../../providers/filesystem-provider-cont import { resolveSftpTransferPathIfMapped, type SftpNamespacePathMapping -} from '../sftp-namespace-resolution' +} from './sftp/sftp-namespace-resolution' import { createLinkedSshFileTransferSignal, raceSftpFileTransferWithAbort, sftpSessionClosedError -} from '../ssh-file-transfer-abort' -import type { RemoteHostPlatform } from '../ssh-remote-platform' +} from './ssh-file-transfer-abort' +import type { RemoteHostPlatform } from '../remote-host/ssh-remote-platform' import { downloadFileViaSystemSsh, uploadFileViaSystemSsh, writeBufferViaSystemSsh -} from '../system-transport/system-ssh-file-binary-transfer' +} from '../system-transport/file-transfer/system-ssh-file-binary-transfer' import { uploadDirectoryViaSystemSsh, writeFileViaSystemSsh -} from '../system-transport/system-ssh-file-transfer' +} from '../system-transport/file-transfer/system-ssh-file-transfer' import type { SystemSshBuildArgsOptions } from '../system-transport/system-ssh-args' export type SshRemoteFileOptions = { @@ -45,7 +45,7 @@ export async function uploadSshDirectory( ): Promise { await withLinkedSftpTransfer(host, remoteDir, options, { sftp: async (sftp, targetDir, signal, endSession) => { - const { uploadDirectory } = await import('../sftp-upload') + const { uploadDirectory } = await import('./sftp/sftp-upload') await uploadDirectory(sftp, localDir, targetDir, localDir, { signal, endSession }) }, system: (signal) => @@ -86,7 +86,7 @@ export async function createSshFileUploadSession( ): Promise { if (!host.usesSystemSshTransport()) { const sftp = await host.sftp() - const { uploadFile } = await import('../sftp-upload') + const { uploadFile } = await import('./sftp/sftp-file-upload') return { uploadFile: (localPath, remotePath, uploadOptions) => uploadFile(sftp, localPath, remotePath, uploadOptions), @@ -118,7 +118,7 @@ export async function writeSshFile( ): Promise { await withLinkedSftpTransfer(host, remotePath, options, { sftp: async (sftp, targetPath) => { - const { writeStringViaSftp } = await import('../sftp-upload') + const { writeStringViaSftp } = await import('./sftp/sftp-upload') await writeStringViaSftp(sftp, targetPath, contents) }, system: (signal) => @@ -225,7 +225,7 @@ export async function writeSshBuffer( if (!host.usesSystemSshTransport()) { const sftp = await host.sftp() try { - const { uploadBuffer } = await import('../sftp-upload') + const { uploadBuffer } = await import('./sftp/sftp-upload') await uploadBuffer(sftp, contents, remotePath, options) } finally { sftp.end() diff --git a/src/main/ssh/ssh-directory-transfer-budget.ts b/src/main/ssh/file-transfer/ssh-directory-transfer-budget.ts similarity index 100% rename from src/main/ssh/ssh-directory-transfer-budget.ts rename to src/main/ssh/file-transfer/ssh-directory-transfer-budget.ts diff --git a/src/main/ssh/ssh-exec-stdin-file-transfer.test.ts b/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts similarity index 75% rename from src/main/ssh/ssh-exec-stdin-file-transfer.test.ts rename to src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts index 854d533d085..1d35b327d27 100644 --- a/src/main/ssh/ssh-exec-stdin-file-transfer.test.ts +++ b/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts @@ -15,16 +15,13 @@ import { join } from 'node:path' import { Duplex } from 'node:stream' import { afterEach, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { SshConnection } from './connection/ssh-connection' +import type { SshConnection } from '../connection/ssh-connection' import { - EXEC_STDIN_WRITE_DONE, - makeExecStdinWriteFileCommand, uploadDirectoryViaExecStdin, uploadFileViaExecStdin, writeStringViaExecStdin } from './ssh-exec-stdin-file-transfer' -import { getRemoteHostPlatform } from './ssh-remote-platform' -import { makePosixWriteFileCommand } from './system-transport/system-ssh-file-binary-transfer' +import { getRemoteHostPlatform } from '../remote-host/ssh-remote-platform' const directories: string[] = [] afterEach(() => { @@ -81,34 +78,6 @@ function localShellConnection(rewrite: (command: string) => string = (c) => c): return conn as unknown as SshConnection } -describe('exec-stdin write command construction', () => { - it('keeps the system-SSH writer a plain cat redirection', () => { - expect(makePosixWriteFileCommand('/h/a b')).toBe("cat > '/h/a b'") - expect(makePosixWriteFileCommand('/h/x', { exclusive: true })).toBe("set -C; cat > '/h/x'") - }) - - it('wraps the same writer with a size check and an atomic rename for the ssh2 fallback', () => { - const command = makeExecStdinWriteFileCommand("/h/o'dd/file", 42, { token: 'abc' }) - expect(command).toBe( - [ - "{ mkdir -p '/h/o'\\''dd'", - "cat > '/h/o'\\''dd/file.orca-part-abc'", - `[ "$(wc -c < '/h/o'\\''dd/file.orca-part-abc' | tr -d ' ')" = 42 ]`, - "mv -f '/h/o'\\''dd/file.orca-part-abc' '/h/o'\\''dd/file'", - `echo ${EXEC_STDIN_WRITE_DONE}; } || { rm -f '/h/o'\\''dd/file.orca-part-abc'; exit 1; }` - ].join(' && ') - ) - }) - - it('keeps the executable bit when asked and rejects an impossible size', () => { - expect(makeExecStdinWriteFileCommand('/h/f', 1, { token: 't', executable: true })).toContain( - "chmod 755 '/h/f.orca-part-t'" - ) - expect(() => makeExecStdinWriteFileCommand('/h/f', -1, { token: 't' })).toThrow() - expect(() => makeExecStdinWriteFileCommand('/h/f', 1.5, { token: 't' })).toThrow() - }) -}) - describe.skipIf(process.platform === 'win32')('exec-stdin writer through a real shell', () => { it('streams a payload over 10 MB byte-for-byte', async () => { const dir = tempDir() diff --git a/src/main/ssh/ssh-exec-stdin-file-transfer.ts b/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.ts similarity index 86% rename from src/main/ssh/ssh-exec-stdin-file-transfer.ts rename to src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.ts index 5d4405d6ca2..564364c91a4 100644 --- a/src/main/ssh/ssh-exec-stdin-file-transfer.ts +++ b/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.ts @@ -4,13 +4,13 @@ import { constants } from 'node:fs' import { lstat, open } from 'node:fs/promises' import { posix } from 'node:path' import { Readable } from 'node:stream' -import type { RemoteInstallTransport } from '../managed-server/install/remote-install-transport' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { execCommand } from './remote-exec/remote-exec-command' -import { REMOTE_INSTALL_TIMEOUT_MS } from '../managed-server/install/remote-deploy-timing' -import type { RemoteHostPlatform } from './ssh-remote-platform' -import { makePosixWriteFileCommand } from './system-transport/system-ssh-file-binary-transfer' -import { collectLocalUploadPlan } from './system-transport/system-ssh-file-transfer' +import type { RemoteInstallTransport } from '../../managed-server/install/remote-install-transport' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { execCommand } from '../remote-exec/remote-exec-command' +import { REMOTE_INSTALL_TIMEOUT_MS } from '../../managed-server/install/remote-deploy-timing' +import type { RemoteHostPlatform } from '../remote-host/ssh-remote-platform' +import { makePosixWriteFileCommand } from '../system-transport/file-transfer/system-ssh-file-binary-transfer' +import { collectLocalUploadPlan } from '../system-transport/file-transfer/system-ssh-file-transfer' export const EXEC_STDIN_WRITE_DONE = 'ORCA_EXEC_STDIN_WRITE_DONE' diff --git a/src/main/ssh/ssh-file-transfer-abort.test.ts b/src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts similarity index 100% rename from src/main/ssh/ssh-file-transfer-abort.test.ts rename to src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts diff --git a/src/main/ssh/ssh-file-transfer-abort.ts b/src/main/ssh/file-transfer/ssh-file-transfer-abort.ts similarity index 97% rename from src/main/ssh/ssh-file-transfer-abort.ts rename to src/main/ssh/file-transfer/ssh-file-transfer-abort.ts index fbeabb583db..531a4c26326 100644 --- a/src/main/ssh/ssh-file-transfer-abort.ts +++ b/src/main/ssh/file-transfer/ssh-file-transfer-abort.ts @@ -1,4 +1,4 @@ -import { createSshOperationAbortError } from './connection/ssh-exec-options' +import { createSshOperationAbortError } from '../connection/ssh-exec-options' export function createLinkedSshFileTransferSignal(signals: readonly AbortSignal[]): { signal: AbortSignal diff --git a/src/main/ssh/ssh-remote-directory-browse.test.ts b/src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts similarity index 83% rename from src/main/ssh/ssh-remote-directory-browse.test.ts rename to src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts index 5b9f31dfc4d..04e49b7860e 100644 --- a/src/main/ssh/ssh-remote-directory-browse.test.ts +++ b/src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts @@ -1,6 +1,6 @@ import { spawn } from 'node:child_process' import { EventEmitter } from 'node:events' -import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -77,22 +77,4 @@ describe.skipIf(process.platform === 'win32')('browseSshDirectory over a POSIX s expect(linked.entries).toEqual([{ name: 'project', isDirectory: true }]) expect(empty.entries).toEqual([]) }) - - it('still fails instead of looking empty when the directory cannot be listed', async () => { - await expect( - browseSshDirectory(shellBackedManager(), 'ssh-1', join(root, 'missing')) - ).rejects.toThrow() - // Execute-only: `cd` and `pwd` succeed but `ls` cannot read it. - const unreadable = join(root, 'unreadable') - await mkdir(unreadable, { mode: 0o100 }) - try { - if (process.getuid?.() !== 0) { - await expect( - browseSshDirectory(shellBackedManager(), 'ssh-1', unreadable) - ).rejects.toThrow() - } - } finally { - await chmod(unreadable, 0o700) - } - }) }) diff --git a/src/main/ssh/ssh-remote-directory-browse.ts b/src/main/ssh/filesystem/ssh-remote-directory-browse.ts similarity index 93% rename from src/main/ssh/ssh-remote-directory-browse.ts rename to src/main/ssh/filesystem/ssh-remote-directory-browse.ts index 08ae3f0de3a..74d98978a7f 100644 --- a/src/main/ssh/ssh-remote-directory-browse.ts +++ b/src/main/ssh/filesystem/ssh-remote-directory-browse.ts @@ -1,11 +1,11 @@ -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import type { SshConnectionManager } from './connection/ssh-connection-manager' -import type { SshExecOptions } from './connection/ssh-exec-options' -import { powerShellCommand } from './ssh-remote-powershell' -import { quotePowerShellLiteral as powerShellLiteral } from '../../shared/powershell-native-argument' -import type { FilesystemPathFlavor } from '../../shared/file-access/filesystem-path-flavor' -import { sortDirEntries } from '../../shared/file-listing/file-name-sort' -import { buildPosixStdoutFence } from '../../shared/posix-stdout-fence' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import type { SshConnectionManager } from '../connection/ssh-connection-manager' +import type { SshExecOptions } from '../connection/ssh-exec-options' +import { powerShellCommand } from '../remote-exec/ssh-remote-powershell' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' +import type { FilesystemPathFlavor } from '../../../shared/file-access/filesystem-path-flavor' +import { sortDirEntries } from '../../../shared/file-listing/file-name-sort' +import { buildPosixStdoutFence } from '../../../shared/posix-stdout-fence' type RemoteDirEntry = { name: string diff --git a/src/main/ssh/ssh-host-key-decision.ts b/src/main/ssh/host-keys/ssh-host-key-decision.ts similarity index 97% rename from src/main/ssh/ssh-host-key-decision.ts rename to src/main/ssh/host-keys/ssh-host-key-decision.ts index da8d0dc8925..379af4de5a6 100644 --- a/src/main/ssh/ssh-host-key-decision.ts +++ b/src/main/ssh/host-keys/ssh-host-key-decision.ts @@ -1,7 +1,7 @@ /** Keep host-key policy independent of handshake wiring and inject trust evidence for deterministic decisions. */ -import { isEphemeralRuntimeSshOwner } from '../../shared/managed-orcad-ssh-owner' -import type { SshTargetOwner } from '../../shared/ssh-types' -import type { KnownHostsOutcome } from './config/ssh-known-hosts' +import { isEphemeralRuntimeSshOwner } from '../../../shared/managed-orcad-ssh-owner' +import type { SshTargetOwner } from '../../../shared/ssh-types' +import type { KnownHostsOutcome } from './ssh-known-hosts' /** Prompt is reserved for future UI; current decisions never produce it. */ type HostKeyAction = 'accept' | 'accept-and-remember' | 'reject' | 'prompt' diff --git a/src/main/ssh/ssh-host-key-store.test.ts b/src/main/ssh/host-keys/ssh-host-key-store.test.ts similarity index 100% rename from src/main/ssh/ssh-host-key-store.test.ts rename to src/main/ssh/host-keys/ssh-host-key-store.test.ts diff --git a/src/main/ssh/ssh-host-key-store.ts b/src/main/ssh/host-keys/ssh-host-key-store.ts similarity index 98% rename from src/main/ssh/ssh-host-key-store.ts rename to src/main/ssh/host-keys/ssh-host-key-store.ts index 75dd8fdecca..1d77b768757 100644 --- a/src/main/ssh/ssh-host-key-store.ts +++ b/src/main/ssh/host-keys/ssh-host-key-store.ts @@ -2,13 +2,16 @@ import { createHash } from 'node:crypto' import { mkdir, readFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { withSidecarSnapshotQueue, writeSidecarSnapshot } from '../filesystem/sidecar-snapshot-file' +import { + withSidecarSnapshotQueue, + writeSidecarSnapshot +} from '../../filesystem/sidecar-snapshot-file' import { formatHostKeyFingerprint, readHostKeyType, type KnownHostsOutcome, type KnownHostsQuery -} from './config/ssh-known-hosts' +} from './ssh-known-hosts' const STORE_FILE_NAME = 'ssh-host-keys.json' const STORE_VERSION = 1 diff --git a/src/main/ssh/ssh-host-key-verifier.test.ts b/src/main/ssh/host-keys/ssh-host-key-verifier.test.ts similarity index 98% rename from src/main/ssh/ssh-host-key-verifier.test.ts rename to src/main/ssh/host-keys/ssh-host-key-verifier.test.ts index 304765dedf7..4ca89e12e8e 100644 --- a/src/main/ssh/ssh-host-key-verifier.test.ts +++ b/src/main/ssh/host-keys/ssh-host-key-verifier.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import { parseKnownHosts } from './config/ssh-known-hosts' +import { parseKnownHosts } from './ssh-known-hosts' import { createHostKeyVerifier, orderServerHostKeyAlgorithms, diff --git a/src/main/ssh/ssh-host-key-verifier.ts b/src/main/ssh/host-keys/ssh-host-key-verifier.ts similarity index 99% rename from src/main/ssh/ssh-host-key-verifier.ts rename to src/main/ssh/host-keys/ssh-host-key-verifier.ts index 29aba915688..2a74bb298e0 100644 --- a/src/main/ssh/ssh-host-key-verifier.ts +++ b/src/main/ssh/host-keys/ssh-host-key-verifier.ts @@ -6,7 +6,7 @@ import { readHostKeyType, type KnownHostsEntry, type KnownHostsOutcome -} from './config/ssh-known-hosts' +} from './ssh-known-hosts' import { decideHostKey, type HostKeyDecision, type HostKeyPolicy } from './ssh-host-key-decision' type TrustedHostKeyLookup = (query: { diff --git a/src/main/ssh/config/ssh-known-hosts-source.test.ts b/src/main/ssh/host-keys/ssh-known-hosts-source.test.ts similarity index 99% rename from src/main/ssh/config/ssh-known-hosts-source.test.ts rename to src/main/ssh/host-keys/ssh-known-hosts-source.test.ts index 888bf04e926..176ed1feae4 100644 --- a/src/main/ssh/config/ssh-known-hosts-source.test.ts +++ b/src/main/ssh/host-keys/ssh-known-hosts-source.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import './ssh-g-config-resolution' +import '../config/ssh-g-config-resolution' import { matchKnownHosts, readHostKeyType, type KnownHostsEntry } from './ssh-known-hosts' import { loadKnownHostsEvidence, resolveKnownHostsFiles } from './ssh-known-hosts-source' diff --git a/src/main/ssh/config/ssh-known-hosts-source.ts b/src/main/ssh/host-keys/ssh-known-hosts-source.ts similarity index 98% rename from src/main/ssh/config/ssh-known-hosts-source.ts rename to src/main/ssh/host-keys/ssh-known-hosts-source.ts index 60789519754..b81e8842d13 100644 --- a/src/main/ssh/config/ssh-known-hosts-source.ts +++ b/src/main/ssh/host-keys/ssh-known-hosts-source.ts @@ -2,7 +2,7 @@ import { access, readFile } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' -import type { SshResolvedConfig } from './ssh-g-config-resolution' +import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' import { parseKnownHosts, type KnownHostsEntry } from './ssh-known-hosts' /** OpenSSH's explicit opt-out for one list; the other list still applies. */ diff --git a/src/main/ssh/config/ssh-known-hosts.test.ts b/src/main/ssh/host-keys/ssh-known-hosts.test.ts similarity index 100% rename from src/main/ssh/config/ssh-known-hosts.test.ts rename to src/main/ssh/host-keys/ssh-known-hosts.test.ts diff --git a/src/main/ssh/config/ssh-known-hosts.ts b/src/main/ssh/host-keys/ssh-known-hosts.ts similarity index 100% rename from src/main/ssh/config/ssh-known-hosts.ts rename to src/main/ssh/host-keys/ssh-known-hosts.ts diff --git a/src/main/ssh/connection/ssh2-host-key-verification.ts b/src/main/ssh/host-keys/ssh2-host-key-verification.ts similarity index 98% rename from src/main/ssh/connection/ssh2-host-key-verification.ts rename to src/main/ssh/host-keys/ssh2-host-key-verification.ts index 28d179686b5..314f6c02d6f 100644 --- a/src/main/ssh/connection/ssh2-host-key-verification.ts +++ b/src/main/ssh/host-keys/ssh2-host-key-verification.ts @@ -5,8 +5,8 @@ import { createHostKeyVerifier, getDefaultServerHostKeyAlgorithms, orderServerHostKeyAlgorithms -} from '../ssh-host-key-verifier' -import { HostKeyVerificationError, hostKeyPolicyForOwner } from '../ssh-host-key-decision' +} from './ssh-host-key-verifier' +import { HostKeyVerificationError, hostKeyPolicyForOwner } from './ssh-host-key-decision' import { siteConfigMayRestrictHostKeys, sshGArgsForHost, @@ -18,12 +18,12 @@ import { matchTrustedHostKeys, storedKeyTypesForEndpoint, trustHostKey -} from '../ssh-host-key-store' +} from './ssh-host-key-store' import { loadKnownHostsEvidence, resolveKnownHostsFiles, resolveKnownHostsLookupHost -} from '../config/ssh-known-hosts-source' +} from './ssh-known-hosts-source' export type HostKeyTrustSources = { /** Whether the system-wide ssh_config could be restricting host keys; doubt reads as true. */ diff --git a/src/main/ssh/managed-server-fence-recheck.ts b/src/main/ssh/host-server/managed-server-fence-recheck.ts similarity index 97% rename from src/main/ssh/managed-server-fence-recheck.ts rename to src/main/ssh/host-server/managed-server-fence-recheck.ts index f626f054229..4a815fefaae 100644 --- a/src/main/ssh/managed-server-fence-recheck.ts +++ b/src/main/ssh/host-server/managed-server-fence-recheck.ts @@ -1,5 +1,5 @@ /** Recheck transient update fences until released so connect status clears without reconnecting. */ -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' import { checkManagedServerUpdate } from './managed-server-update-check' import { managedResultAfterUpdate, unservedManagedResult } from './managed-server-serving-gate' import type { diff --git a/src/main/ssh/managed-server-serving-gate.ts b/src/main/ssh/host-server/managed-server-serving-gate.ts similarity index 95% rename from src/main/ssh/managed-server-serving-gate.ts rename to src/main/ssh/host-server/managed-server-serving-gate.ts index 2a651548ad8..cbd91bd2da4 100644 --- a/src/main/ssh/managed-server-serving-gate.ts +++ b/src/main/ssh/host-server/managed-server-serving-gate.ts @@ -3,7 +3,7 @@ import { MANAGED_ORCAD_FENCED_DETAIL, MANAGED_ORCAD_NOT_ACTIVATED_DETAIL, type OrcadManagedServing -} from '../managed-server/lifecycle/orcad-managed-serving' +} from '../../managed-server/lifecycle/orcad-managed-serving' import type { HostServerOnConnectResult } from './ssh-host-server-on-connect' type ManagedRoute = Extract diff --git a/src/main/ssh/managed-server-update-check.ts b/src/main/ssh/host-server/managed-server-update-check.ts similarity index 94% rename from src/main/ssh/managed-server-update-check.ts rename to src/main/ssh/host-server/managed-server-update-check.ts index 46166289546..93bd8b0e035 100644 --- a/src/main/ssh/managed-server-update-check.ts +++ b/src/main/ssh/host-server/managed-server-update-check.ts @@ -1,7 +1,7 @@ -import type { SshManagedServerUpdateNote, SshTarget } from '../../shared/ssh-types' -import type { ManagedOrcadAutoUpdateOutcome } from '../managed-server/lifecycle/orcad-managed-auto-update' +import type { SshManagedServerUpdateNote, SshTarget } from '../../../shared/ssh-types' +import type { ManagedOrcadAutoUpdateOutcome } from '../../managed-server/lifecycle/orcad-managed-auto-update' import type { HostServerUpdateReason } from './ssh-host-server-connect-events' -import { ORCAD_ACTIVATION_FENCE_BUSY_CODE } from '../managed-server/activation/orcad-activation-fence-hold' +import { ORCAD_ACTIVATION_FENCE_BUSY_CODE } from '../../managed-server/activation/orcad-activation-fence-hold' export type ManagedServerUpdateDeps = { autoUpdate: ( diff --git a/src/main/ssh/managed-server-update-deps.ts b/src/main/ssh/host-server/managed-server-update-deps.ts similarity index 79% rename from src/main/ssh/managed-server-update-deps.ts rename to src/main/ssh/host-server/managed-server-update-deps.ts index bf188fd96b5..a6dd6085e84 100644 --- a/src/main/ssh/managed-server-update-deps.ts +++ b/src/main/ssh/host-server/managed-server-update-deps.ts @@ -1,11 +1,11 @@ -import { getAppEnvironment } from '../../shared/app-environment' +import { getAppEnvironment } from '../../../shared/app-environment' import type { ManagedServerUpdateDeps } from './managed-server-update-check' -import { autoUpdateManagedOrcadEnvironment } from '../managed-server/lifecycle/orcad-managed-auto-update' -import { requireManagedOrcadTargetStore } from '../managed-server/lifecycle/orcad-managed-runtime-context' +import { autoUpdateManagedOrcadEnvironment } from '../../managed-server/lifecycle/orcad-managed-auto-update' +import { requireManagedOrcadTargetStore } from '../../managed-server/lifecycle/orcad-managed-runtime-context' import { orcadUpdateFailedThisLaunch, recordOrcadUpdateFailedThisLaunch -} from '../managed-server/lifecycle/orcad-managed-update-failure-memory' +} from '../../managed-server/lifecycle/orcad-managed-update-failure-memory' export function managedServerUpdateDeps(userDataPath: string): ManagedServerUpdateDeps { const registry = requireManagedOrcadTargetStore() diff --git a/src/main/ssh/ssh-host-server-bridged-unserved.ts b/src/main/ssh/host-server/ssh-host-server-bridged-unserved.ts similarity index 85% rename from src/main/ssh/ssh-host-server-bridged-unserved.ts rename to src/main/ssh/host-server/ssh-host-server-bridged-unserved.ts index 3732f84359e..c6d934abe0b 100644 --- a/src/main/ssh/ssh-host-server-bridged-unserved.ts +++ b/src/main/ssh/host-server/ssh-host-server-bridged-unserved.ts @@ -1,10 +1,10 @@ /** COMPAT(legacy-relay-bridge, revisit 2027-01-15): keep blocked same-checkout relinks connected/unmoved while old tabs still need bridged terminals. Reconnect after exit can link the server's existing project. */ -import type { SshManagedServerRelayReason } from '../../shared/ssh-types' +import type { SshManagedServerRelayReason } from '../../../shared/ssh-types' import type { HostServerOnConnectResult, HostServerTerminalVerdict } from './ssh-host-server-on-connect' -import { isBridgedTerminalLinkConflict } from './orcad-migration-conflict-guidance' +import { isBridgedTerminalLinkConflict } from '../../managed-server/migration/cutover/orcad-migration-conflict-guidance' export function relayTerminalReason(verdict: 'live' | 'unverifiable'): SshManagedServerRelayReason { return verdict === 'live' ? 'relay_terminals_live' : 'relay_terminals_unverifiable' diff --git a/src/main/ssh/ssh-host-server-connect-events.ts b/src/main/ssh/host-server/ssh-host-server-connect-events.ts similarity index 96% rename from src/main/ssh/ssh-host-server-connect-events.ts rename to src/main/ssh/host-server/ssh-host-server-connect-events.ts index 8803b55eee0..cb46e501da6 100644 --- a/src/main/ssh/ssh-host-server-connect-events.ts +++ b/src/main/ssh/host-server/ssh-host-server-connect-events.ts @@ -2,10 +2,10 @@ import type { OrcadManagedConversionResult, OrcadManagedDeployResult -} from '../../shared/orcad-managed-runtime' -import type { SshTarget } from '../../shared/ssh-types' +} from '../../../shared/orcad-managed-runtime' +import type { SshTarget } from '../../../shared/ssh-types' import type { HostServerOnConnectResult } from './ssh-host-server-on-connect' -import { classifyOrcadHostUnavailable } from '../orcad/orcad-host-unavailable' +import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' export type HostServerConnectEvent = | { diff --git a/src/main/ssh/ssh-host-server-on-connect-held-move.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts similarity index 62% rename from src/main/ssh/ssh-host-server-on-connect-held-move.test.ts rename to src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts index fa29d0327e8..5e8f7bd16ba 100644 --- a/src/main/ssh/ssh-host-server-on-connect-held-move.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts @@ -1,13 +1,9 @@ /** #27267: stopped conversions must release their fence or report it retained and resume next connect. */ import { describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' -import { - resolveHostServerOnConnect, - type HostServerOnConnectDeps -} from './ssh-host-server-on-connect' -import { hostServerDepsStub } from './ssh-host-server-on-connect-test-deps' +import type { SshTarget } from '../../../shared/ssh-types' +import { resolveHostServerOnConnect } from './ssh-host-server-on-connect' +import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' import { unservedHostServerMessage, unservedServerStatus } from './ssh-host-unserved-status' -import { admitSshManagedServerStatus } from '../../shared/ssh-managed-server-status-admission' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } @@ -75,43 +71,4 @@ describe('a move to the managed server that stops short', () => { } warn.mockRestore() }) - - it('releases a fence whose server never registered when the deploy fails or defers', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const stops: HostServerOnConnectDeps['convert'][] = [ - async () => { - throw new Error('upload failed') - }, - async () => ({ - outcome: 'deferred' as const, - candidateVersion: '0.1.0+abc', - code: 'orcad_update_fence_held', - reason: 'Another desktop is updating this host.' - }) - ] - for (const convert of stops) { - const { host, deps } = fencedHost('source-fenced', false) - const d = deps({ - convert, - abandonConversion: vi.fn(async () => { - host.phase = null - }) - }) - const result = await resolveHostServerOnConnect(target, d) - expect(result).toMatchObject({ route: 'unserved' }) - expect(result).not.toHaveProperty('held') - expect(d.abandonConversion).toHaveBeenCalledWith(target) - expect(host.phase).toBeNull() - } - warn.mockRestore() - }) - - it('carries the lock to the renderer, and drops anything but a literal true', () => { - expect(admitSshManagedServerStatus({ kind: 'relay', reason: 'failed', held: true })).toEqual({ - managedServer: { kind: 'relay', reason: 'failed', held: true } - }) - expect(admitSshManagedServerStatus({ kind: 'relay', reason: 'failed', held: 'yes' })).toEqual({ - managedServer: { kind: 'relay', reason: 'failed' } - }) - }) }) diff --git a/src/main/ssh/ssh-host-server-on-connect-node-download.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts similarity index 87% rename from src/main/ssh/ssh-host-server-on-connect-node-download.test.ts rename to src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts index cfeb2db6752..e7ddac1f80e 100644 --- a/src/main/ssh/ssh-host-server-on-connect-node-download.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts @@ -1,11 +1,11 @@ /** Carry structured Node-download failure for the mirror offer; never infer it from message text. */ import { describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' import { resolveHostServerOnConnect } from './ssh-host-server-on-connect' -import { hostServerDepsStub } from './ssh-host-server-on-connect-test-deps' +import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' import { unservedHostServerMessage } from './ssh-host-unserved-status' -import { sftpSessionClosedError } from './ssh-file-transfer-abort' -import { NodeRuntimeUnreachableError } from '../managed-server/install/remote-node-runtime-host-download' +import { sftpSessionClosedError } from '../file-transfer/ssh-file-transfer-abort' +import { NodeRuntimeUnreachableError } from '../../managed-server/install/remote-node-runtime-host-download' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } diff --git a/src/main/ssh/ssh-host-server-on-connect-telemetry.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect-telemetry.test.ts similarity index 90% rename from src/main/ssh/ssh-host-server-on-connect-telemetry.test.ts rename to src/main/ssh/host-server/ssh-host-server-on-connect-telemetry.test.ts index 2e0efec9ae1..28600ff30d3 100644 --- a/src/main/ssh/ssh-host-server-on-connect-telemetry.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect-telemetry.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' import type { HostServerConnectEvent } from './ssh-host-server-connect-events' import { resolveHostServerOnConnect, type HostServerOnConnectDeps } from './ssh-host-server-on-connect' -import { hostServerDepsStub } from './ssh-host-server-on-connect-test-deps' +import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } diff --git a/src/main/ssh/ssh-host-server-on-connect.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts similarity index 58% rename from src/main/ssh/ssh-host-server-on-connect.test.ts rename to src/main/ssh/host-server/ssh-host-server-on-connect.test.ts index 5963e28906c..1010b5b15dd 100644 --- a/src/main/ssh/ssh-host-server-on-connect.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts @@ -1,38 +1,20 @@ -import type { ManagedServerUpdateDeps } from './managed-server-update-check' import { describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' import { OrcadHostUnsupportedError, OrcadStdioBridgeUnavailableError -} from '../orcad/orcad-host-unavailable' +} from '../../orcad/orcad-host-unavailable' import { resolveHostServerOnConnect, type HostServerOnConnectDeps } from './ssh-host-server-on-connect' -import { hostServerDepsStub } from './ssh-host-server-on-connect-test-deps' -import { unservedServerStatus } from './ssh-host-unserved-status' -import { sshHostServerSetupRemedy } from '../../shared/ssh-host-server-setup-remedy' -import { admitSshManagedServerStatus } from '../../shared/ssh-managed-server-status-admission' - -// Read the final callback because retry eligibility is decided under lifecycle lock. -const failedBeforeOf = (autoUpdate: ManagedServerUpdateDeps['autoUpdate']) => - vi.mocked(autoUpdate).mock.lastCall?.[1].failedBefore() +import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } const deps = hostServerDepsStub describe('which server an SSH host runs on connect', () => { - it('connects a converted host through its tunnel', async () => { - const d = deps({ managedEnvironmentId: () => 'env-9' }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-9' - }) - expect(d.ensureTunnel).toHaveBeenCalledWith('env-9') - expect(d.convert).not.toHaveBeenCalled() - }) - it('keeps a host whose stopped server could not be started managed, with the reason', async () => { const detail = 'orcad did not become ready.\nLast lines of orcad.log:\nboom' const d = deps({ @@ -49,22 +31,6 @@ describe('which server an SSH host runs on connect', () => { expect(d.autoUpdate).not.toHaveBeenCalled() }) - it('deploys an empty host directly, and converts a host with state', async () => { - const empty = deps({ isEmptyHost: () => true }) - await expect(resolveHostServerOnConnect(target, empty)).resolves.toMatchObject({ - route: 'managed' - }) - expect(empty.deploy).toHaveBeenCalled() - expect(empty.relayTerminals).not.toHaveBeenCalled() - - const withState = deps() - await expect(resolveHostServerOnConnect(target, withState)).resolves.toMatchObject({ - route: 'managed' - }) - expect(withState.convert).toHaveBeenCalled() - expect(withState.progress).toHaveBeenCalledWith(target, 'converting') - }) - it('checks for an update right after pairing with a server another version runs', async () => { const d = deps({ isEmptyHost: () => true, @@ -89,39 +55,6 @@ describe('which server an SSH host runs on connect', () => { expect(d.abandonDeploy).not.toHaveBeenCalled() }) - it('keeps the relay while relay terminals are live or unproven', async () => { - for (const verdict of ['live', 'unverifiable'] as const) { - const d = deps({ relayTerminals: async () => ({ verdict, count: 2 }) }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'unserved', - reason: verdict === 'live' ? 'relay_terminals_live' : 'relay_terminals_unverifiable', - terminals: 2 - }) - expect(d.convert).not.toHaveBeenCalled() - } - const elsewhere = deps({ - relayTerminals: async () => ({ verdict: 'live', count: 1, elsewhere: true }) - }) - await expect(resolveHostServerOnConnect(target, elsewhere)).resolves.toEqual({ - route: 'unserved', - reason: 'relay_terminals_live', - terminals: 1, - terminalsElsewhere: true - }) - const raced = deps({ - convert: async () => ({ - outcome: 'refused', - verdict: 'live', - code: 'orcad_migration_terminals', - reason: 'A relay terminal is still running.' - }) - }) - await expect(resolveHostServerOnConnect(target, raced)).resolves.toEqual({ - route: 'unserved', - reason: 'relay_terminals_live' - }) - }) - // COMPAT(legacy-relay-bridge): the census only reports; converting leaves relay terminals running. it('converts anyway when the bridge takes the live or unproven relay terminals', async () => { for (const verdict of ['live', 'unverifiable'] as const) { @@ -279,54 +212,6 @@ describe('which server an SSH host runs on connect', () => { warn.mockRestore() }) - it('names relay terminals that hold a linked project, and how to end them', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const d = deps({ - convert: async () => { - throw new Error('orcad_migration_linked_project_terminals:/root/my repo') - } - }) - const result = await resolveHostServerOnConnect(target, d) - expect(result).toMatchObject({ route: 'unserved', reason: 'refused' }) - const detail = result.route === 'unserved' ? result.detail : '' - expect(detail).toContain('started in /root/my repo are still running') - expect(detail).toContain('remove that project from this desktop and connect again') - warn.mockRestore() - }) - - it('keeps a host connected for the bridge when only its relay terminals stop the link (STA-10604)', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - for (const code of ['linked_project_terminals', 'linked_project_unowned_terminals']) { - const d = deps({ - relayTerminals: vi.fn(async () => ({ - verdict: 'live' as const, - count: 1, - bridged: true as const - })), - convert: async () => { - throw new Error(`orcad_migration_${code}:/root/my repo`) - } - }) - const result = await resolveHostServerOnConnect(target, d) - expect(result).toMatchObject({ - route: 'unserved', - reason: 'relay_terminals_live', - terminals: 1, - bridged: true - }) - expect(result.route === 'unserved' ? result.detail : '').toContain('/root/my repo') - // What the renderer admits keeps the mark its bridged panes and status line read. - if (result.route === 'unserved') { - expect(admitSshManagedServerStatus(unservedServerStatus(result))).toMatchObject({ - managedServer: { kind: 'relay', bridged: true } - }) - } - // The fence goes, so the next connect after the terminal exits links the project. - expect(d.abandonConversion).toHaveBeenCalledWith(target) - } - warn.mockRestore() - }) - it('never keeps a host connected for the bridge on any other refusal or a held move', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const bridgedTerminals = vi.fn(async () => ({ @@ -356,22 +241,6 @@ describe('which server an SSH host runs on connect', () => { warn.mockRestore() }) - it('never pins a relay terminal of unknown project on the linked one, and offers the way out', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const d = deps({ - convert: async () => { - throw new Error('orcad_migration_linked_project_unowned_terminals:/root/my repo') - } - }) - const result = await resolveHostServerOnConnect(target, d) - expect(result).toMatchObject({ route: 'unserved', reason: 'refused' }) - const detail = result.route === 'unserved' ? result.detail : '' - expect(detail).toContain('can’t tell which project it belongs to') - expect(detail).not.toContain('started in /root/my repo') - expect(detail).toContain('copy of /root/my repo, remove that project from this desktop') - warn.mockRestore() - }) - it('keeps a staged claim of another desktop’s move a retry, since it expires', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const d = deps({ @@ -385,35 +254,6 @@ describe('which server an SSH host runs on connect', () => { warn.mockRestore() }) - it('publishes the code setup stopped on, so only a cause a retry clears says to retry', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const remedyFor = async (code: string) => { - const decision = await resolveHostServerOnConnect( - target, - deps({ - isEmptyHost: () => true, - deploy: async () => ({ - outcome: 'deferred' as const, - candidateVersion: '1.0.0', - code, - reason: `host said ${code}` - }) - }) - ) - const { managedServer } = admitSshManagedServerStatus( - decision.route === 'unserved' ? unservedServerStatus(decision) : null - ) - expect(managedServer).toMatchObject({ reason: 'deferred', code, detail: `host said ${code}` }) - return sshHostServerSetupRemedy(managedServer?.kind === 'relay' ? managedServer.code : '') - } - - expect(await remedyFor('orcad_activation_fence_busy')).toBe('retry') - expect(await remedyFor('orcad_snapshot_space_insufficient')).toBe('free-host-space') - // Thrown errors and older hosts publish no code. - expect(sshHostServerSetupRemedy(undefined)).toBe('retry') - warn.mockRestore() - }) - it('records why when even the stdio bridge cannot reach the deployed server', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const d = deps({ @@ -461,18 +301,6 @@ describe('which server an SSH host runs on connect', () => { expect(d.releaseUnreachableSetup).not.toHaveBeenCalled() }) - it('resumes an uncommitted conversion before routing to its registered server', async () => { - const d = deps({ managedEnvironmentId: () => 'env-9', hasUnfinishedConversion: () => true }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-1' - }) - // No census ran, so the conversion must prove the host's terminals itself. - expect(d.convert).toHaveBeenCalledWith(target, null) - expect(d.relayTerminals).not.toHaveBeenCalled() - expect(d.retainCommittedSource).not.toHaveBeenCalled() - }) - it('backs an uncommitted conversion out to the relay when its commit fails', async () => { const d = deps({ managedEnvironmentId: () => 'env-9', @@ -493,31 +321,6 @@ describe('which server an SSH host runs on connect', () => { const managed = (overrides: Partial) => deps({ managedEnvironmentId: () => 'env-9', ...overrides }) - it('connects without a note when the host already runs this build', async () => { - const d = managed({}) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-9' - }) - expect(failedBeforeOf(d.autoUpdate)).toBe(false) - expect(d.progress).not.toHaveBeenCalledWith(target, 'updating') - }) - - it('updates an older idle host, showing the update in the status line', async () => { - const d = managed({ - autoUpdate: vi.fn(async (_id, options) => { - options.onUpdating() - return { outcome: 'updated' as const, activeVersion: '0.1.0+b' } - }) - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-9' - }) - expect(d.progress).toHaveBeenCalledWith(target, 'updating') - expect(d.recordUpdateFailure).not.toHaveBeenCalled() - }) - it('starts a stopped server before the update counts its terminals, as after a reboot', async () => { const order: string[] = [] const d = managed({ @@ -556,35 +359,6 @@ describe('which server an SSH host runs on connect', () => { expect(d.recordUpdateFailure).not.toHaveBeenCalled() }) - it('records a rolled-back update so the same app version does not retry it', async () => { - const reason = 'Candidate failed readiness. orcad 0.1.0+a was restarted and is serving again.' - const failed = managed({ autoUpdate: async () => ({ outcome: 'failed', reason }) }) - await expect(resolveHostServerOnConnect(target, failed)).resolves.toMatchObject({ - route: 'managed', - update: { state: 'failed', detail: reason } - }) - expect(failed.recordUpdateFailure).toHaveBeenCalledWith(target, reason) - - const later = managed({ - recordedUpdateFailure: () => reason, - autoUpdate: vi.fn(async () => ({ - outcome: 'skipped' as const, - reason: 'failed-before' as const - })) - }) - await expect(resolveHostServerOnConnect(target, later)).resolves.toMatchObject({ - update: { state: 'failed', detail: reason } - }) - expect(failedBeforeOf(later.autoUpdate)).toBe(true) - expect(later.recordUpdateFailure).not.toHaveBeenCalled() - }) - - it('clears a recorded failure once the host runs this build', async () => { - const d = managed({ recordedUpdateFailure: () => 'earlier' }) - await resolveHostServerOnConnect(target, d) - expect(d.clearUpdateFailure).toHaveBeenCalledWith(target) - }) - it('still connects when the update check itself throws', async () => { const d = managed({ autoUpdate: async () => { diff --git a/src/main/ssh/ssh-host-server-on-connect.ts b/src/main/ssh/host-server/ssh-host-server-on-connect.ts similarity index 97% rename from src/main/ssh/ssh-host-server-on-connect.ts rename to src/main/ssh/host-server/ssh-host-server-on-connect.ts index e8f2e2dc9a7..e0214aaabba 100644 --- a/src/main/ssh/ssh-host-server-on-connect.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect.ts @@ -2,7 +2,7 @@ import type { OrcadManagedConversionResult, OrcadManagedDeployResult -} from '../../shared/orcad-managed-runtime' +} from '../../../shared/orcad-managed-runtime' import type { SshManagedServerRelayReason, SshManagedServerLinkedProject, @@ -10,8 +10,8 @@ import type { SshManagedServerServingNote, SshManagedServerUpdateNote, SshTarget -} from '../../shared/ssh-types' -import type { OrcadManagedServing } from '../managed-server/lifecycle/orcad-managed-serving' +} from '../../../shared/ssh-types' +import type { OrcadManagedServing } from '../../managed-server/lifecycle/orcad-managed-serving' import { checkManagedServerUpdate, type ManagedServerUpdateDeps @@ -22,7 +22,7 @@ import { deferred, setupFailed } from './ssh-host-server-setup-outcome' import { classifyOrcadHostUnavailable, ORCAD_TUNNEL_UNAVAILABLE_REASON -} from '../orcad/orcad-host-unavailable' +} from '../../orcad/orcad-host-unavailable' import { decidedEvent, reportHostServerConversion, diff --git a/src/main/ssh/ssh-host-server-setup-failure.ts b/src/main/ssh/host-server/ssh-host-server-setup-failure.ts similarity index 91% rename from src/main/ssh/ssh-host-server-setup-failure.ts rename to src/main/ssh/host-server/ssh-host-server-setup-failure.ts index 4a455db0b0d..caaf67633aa 100644 --- a/src/main/ssh/ssh-host-server-setup-failure.ts +++ b/src/main/ssh/host-server/ssh-host-server-setup-failure.ts @@ -1,6 +1,6 @@ -import type { SshManagedServerNodeDownloadBlocked } from '../../shared/ssh-types' -import { isNodeDistMirrorAttempt } from '../../shared/node-dist-mirror' -import { isSftpSessionClosedError } from './ssh-file-transfer-abort' +import type { SshManagedServerNodeDownloadBlocked } from '../../../shared/ssh-types' +import { isNodeDistMirrorAttempt } from '../../../shared/node-dist-mirror' +import { isSftpSessionClosedError } from '../file-transfer/ssh-file-transfer-abort' // Bounds a failure's detail; the host log tail inside it is already capped. const MAX_FAILURE_DETAIL_CHARS = 16_000 diff --git a/src/main/ssh/ssh-host-server-setup-outcome.ts b/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts similarity index 91% rename from src/main/ssh/ssh-host-server-setup-outcome.ts rename to src/main/ssh/host-server/ssh-host-server-setup-outcome.ts index fdc90c7e067..bb1f592b654 100644 --- a/src/main/ssh/ssh-host-server-setup-outcome.ts +++ b/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts @@ -1,13 +1,13 @@ /** How a managed-server setup that did not finish ends: with SSH's own reason, or as an unserved status. */ -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' import type { HostServerOnConnectDeps, HostServerOnConnectResult } from './ssh-host-server-on-connect' -import { orcadMigrationConflictGuidance } from './orcad-migration-conflict-guidance' +import { orcadMigrationConflictGuidance } from '../../managed-server/migration/cutover/orcad-migration-conflict-guidance' import { boundedDetail, setupFailure, type SetupFailure } from './ssh-host-server-setup-failure' -import { isSshSessionStartFailure } from './ssh-session-start-failure' -import { classifyOrcadHostUnavailable } from '../orcad/orcad-host-unavailable' +import { isSshSessionStartFailure } from '../connection/ssh-session-start-failure' +import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' import { reportHostServerSetupError, type HostServerDecisionTrace diff --git a/src/main/ssh/ssh-host-server-status.ts b/src/main/ssh/host-server/ssh-host-server-status.ts similarity index 94% rename from src/main/ssh/ssh-host-server-status.ts rename to src/main/ssh/host-server/ssh-host-server-status.ts index ef62b347135..539373340ff 100644 --- a/src/main/ssh/ssh-host-server-status.ts +++ b/src/main/ssh/host-server/ssh-host-server-status.ts @@ -1,4 +1,4 @@ -import type { SshManagedServerStatus } from '../../shared/ssh-types' +import type { SshManagedServerStatus } from '../../../shared/ssh-types' const statuses = new Map() let servedListener: ((targetId: string) => void) | null = null diff --git a/src/main/ssh/ssh-host-server-telemetry.test.ts b/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts similarity index 75% rename from src/main/ssh/ssh-host-server-telemetry.test.ts rename to src/main/ssh/host-server/ssh-host-server-telemetry.test.ts index e00646ff188..a3f2e379c2b 100644 --- a/src/main/ssh/ssh-host-server-telemetry.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts @@ -1,9 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { eventSchemas } from '../../shared/telemetry-event-registry' +import { eventSchemas } from '../../../shared/telemetry-event-registry' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -const { track } = await import('../telemetry/client') +const { track } = await import('../../telemetry/client') const { hostServerFailure, hostServerRefusal, trackSshHostServerEvent } = await import('./ssh-host-server-telemetry') @@ -47,12 +47,4 @@ describe('ssh host server telemetry', () => { ) expect(expectSchemaValid()).toMatchObject({ reason: 'other' }) }) - - it('never throws into a connect when tracking fails', () => { - vi.mocked(track).mockImplementation(() => { - throw new Error('invalid') - }) - trackSshHostServerEvent({ kind: 'conversion', phase: 'started' }, null) - expect(track).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/ssh/ssh-host-server-telemetry.ts b/src/main/ssh/host-server/ssh-host-server-telemetry.ts similarity index 90% rename from src/main/ssh/ssh-host-server-telemetry.ts rename to src/main/ssh/host-server/ssh-host-server-telemetry.ts index 81090a3d1f1..2f7419f4245 100644 --- a/src/main/ssh/ssh-host-server-telemetry.ts +++ b/src/main/ssh/host-server/ssh-host-server-telemetry.ts @@ -1,14 +1,14 @@ /** Narrow raw connect/setup codes to fixed enums; unknowns become other, never host/user strings. */ -import type { EventProps } from '../../shared/telemetry-events' +import type { EventProps } from '../../../shared/telemetry-event-classification' import { SSH_HOST_SERVER_FAILURE_VALUES, SSH_HOST_SERVER_REASON_VALUES, SSH_HOST_SERVER_REFUSAL_VALUES -} from '../../shared/telemetry-ssh-host-server-event-schemas' -import { track } from '../telemetry/client' +} from '../../../shared/telemetry-ssh-host-server-event-schemas' +import { track } from '../../telemetry/client' import type { HostServerConnectEvent } from './ssh-host-server-connect-events' -import type { SshHostPlatformFacts } from './ssh-host-platform-memo' -import type { OrcadTunnelTransport } from './orcad-tunnel-transport-memo' +import type { SshHostPlatformFacts } from '../remote-host/ssh-host-platform-memo' +import type { OrcadTunnelTransport } from '../../managed-server/lifecycle/orcad-tunnel-transport-memo' type HostProps = Pick, 'host_os' | 'host_arch' | 'host_libc'> type FailureCode = (typeof SSH_HOST_SERVER_FAILURE_VALUES)[number] diff --git a/src/main/ssh/ssh-host-unserved-status.ts b/src/main/ssh/host-server/ssh-host-unserved-status.ts similarity index 96% rename from src/main/ssh/ssh-host-unserved-status.ts rename to src/main/ssh/host-server/ssh-host-unserved-status.ts index 197f452df70..32fa3839dae 100644 --- a/src/main/ssh/ssh-host-unserved-status.ts +++ b/src/main/ssh/host-server/ssh-host-unserved-status.ts @@ -1,10 +1,10 @@ -import type { NodeDistMirrorAttempt } from '../../shared/node-dist-mirror' -import type { SshManagedServerStatus } from '../../shared/ssh-types' +import type { NodeDistMirrorAttempt } from '../../../shared/node-dist-mirror' +import type { SshManagedServerStatus } from '../../../shared/ssh-types' import type { HostServerOnConnectResult } from './ssh-host-server-on-connect' import { sshHostServerSetupRemedy, type SshHostServerSetupRemedy -} from '../../shared/ssh-host-server-setup-remedy' +} from '../../../shared/ssh-host-server-setup-remedy' type UnservedDecision = Extract diff --git a/src/main/ssh/ssh-host-server-on-connect-test-deps.ts b/src/main/ssh/host-server/testing/ssh-host-server-on-connect-test-deps.ts similarity index 95% rename from src/main/ssh/ssh-host-server-on-connect-test-deps.ts rename to src/main/ssh/host-server/testing/ssh-host-server-on-connect-test-deps.ts index 0b5b491e71c..410c5a934ce 100644 --- a/src/main/ssh/ssh-host-server-on-connect-test-deps.ts +++ b/src/main/ssh/host-server/testing/ssh-host-server-on-connect-test-deps.ts @@ -1,5 +1,5 @@ import { vi } from 'vitest' -import type { HostServerOnConnectDeps } from './ssh-host-server-on-connect' +import type { HostServerOnConnectDeps } from '../ssh-host-server-on-connect' // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the orchestrator reads only the environment id. const environment = { id: 'env-1' } as never diff --git a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts index 27e89c81244..7429b761518 100644 --- a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts +++ b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts @@ -10,9 +10,12 @@ import type { SshTarget } from '../../../shared/ssh-types' import { readOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record-store' import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' import { managedOrcadSlot } from '../../managed-server/lifecycle/orcad-managed-runtime-context' -import { orcadSlotDir, type OrcadSlotOptions } from '../orcad-recovery-slot' +import { + orcadSlotDir, + type OrcadSlotOptions +} from '../../managed-server/activation/orcad-recovery-slot' import { resolveOrcadRemoteContext } from '../../managed-server/install/orcad-remote-context' -import { deployOrcad } from '../orcad-remote-deploy' +import { deployOrcad } from '../../managed-server/install/orcad-remote-deploy' import { getMainHttpClient, setMainHttpClient } from '../../network/http-client' import { orcadLivenessProbeCommand, diff --git a/src/main/ssh/ssh-windows-host-cells.ts b/src/main/ssh/hostile-host-test-support/ssh-windows-host-cells.ts similarity index 97% rename from src/main/ssh/ssh-windows-host-cells.ts rename to src/main/ssh/hostile-host-test-support/ssh-windows-host-cells.ts index 7042e5247ac..43266b4beaf 100644 --- a/src/main/ssh/ssh-windows-host-cells.ts +++ b/src/main/ssh/hostile-host-test-support/ssh-windows-host-cells.ts @@ -1,7 +1,7 @@ /** Real Win32-OpenSSH cells provisioned by config/ci/windows-ssh-provider/ and run by ssh-windows-hosts.yml. */ import { readFileSync } from 'node:fs' -import { isWindowsServerTarget, type WindowsServerTarget } from '../../shared/node-runtime-pin' -import type { SshTarget } from '../../shared/ssh-types' +import { isWindowsServerTarget, type WindowsServerTarget } from '../../../shared/node-runtime-pin' +import type { SshTarget } from '../../../shared/ssh-types' /** Pinned node.exe lifecycle under each DefaultShell. */ const WINDOWS_ORCAD_CELL_IDS = ['orcad-cmd', 'orcad-powershell'] as const diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-connections.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-connections.ts similarity index 96% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-connections.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-connections.ts index f4d0ce04380..4fe178ea365 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-connections.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-connections.ts @@ -5,9 +5,9 @@ * COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ import type { ClientChannel } from 'ssh2' -import { SshConnection } from '../connection/ssh-connection' -import type { SshExecOptions } from '../connection/ssh-exec-options' -import { isSshSessionLimitError } from '../ssh-session-limit-error' +import { SshConnection } from '../../connection/ssh-connection' +import type { SshExecOptions } from '../../connection/ssh-exec-options' +import { isSshSessionLimitError } from '../../connection/ssh-session-limit-error' /** Below OpenSSH's default 10, leaving each side connection room for its own short execs. */ export const RELAY_CHANNELS_PER_SIDE_CONNECTION = 8 diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-ipc.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-ipc.ts similarity index 89% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-ipc.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-ipc.ts index 6bb8653ff88..c76348f5a2c 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-ipc.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-ipc.ts @@ -4,16 +4,16 @@ */ import { ipcMain, type BrowserWindow } from 'electron' import { z } from 'zod' -import { LEGACY_RELAY_BRIDGE_CHANNELS as CHANNELS } from '../../../shared/legacy-relay-bridge-contract' -import { isRemoteCliControlAllowed } from '../../../shared/ssh-remote-cli-control' -import type { Store } from '../../persistence/loading-store/store' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { PtyRetirementWithoutProof } from '../../pty/process-retirement/pty-exit-proof' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import { track } from '../../telemetry/client' -import type { SshConnection } from '../connection/ssh-connection' -import { knownSshHostPlatform } from '../ssh-host-platform-memo' -import { hostProps } from '../ssh-host-server-telemetry' +import { LEGACY_RELAY_BRIDGE_CHANNELS as CHANNELS } from '../../../../shared/legacy-relay-bridge-contract' +import { isRemoteCliControlAllowed } from '../../../../shared/ssh-remote-cli-control' +import type { Store } from '../../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { PtyRetirementWithoutProof } from '../../../pty/process-retirement/pty-exit-proof' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import { track } from '../../../telemetry/client' +import type { SshConnection } from '../../connection/ssh-connection' +import { knownSshHostPlatform } from '../../remote-host/ssh-host-platform-memo' +import { hostProps } from '../../host-server/ssh-host-server-telemetry' import { attachLegacyRelayPane, closeLegacyRelayPane, diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-leases.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-leases.ts similarity index 95% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-leases.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-leases.ts index e1d2db12a9b..3c6411658e2 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-leases.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-leases.ts @@ -2,12 +2,12 @@ * Which relay-era leases the bridge may serve. * COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import type { LegacyRelayBridgedPane } from '../../../shared/legacy-relay-bridge-contract' -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import type { LegacyRelayBridgedPane } from '../../../../shared/legacy-relay-bridge-contract' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import type { LegacyRelayClient, LegacyRelayPty } from './legacy-relay-client' -import { isEpochScopedRelayPtyId } from '../../../shared/ssh-pending-pty-kill' +import { isEpochScopedRelayPtyId } from '../../../../shared/ssh-pending-pty-kill' import type { LegacyRelayPaneOwners } from './legacy-relay-pane-owners' /** A relay's listing row: the endpoint that answered, and the connection the answer came on. */ diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-registry.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-registry.ts similarity index 94% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-registry.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-registry.ts index 05e80cfd1e6..1986845326b 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-registry.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-registry.ts @@ -2,21 +2,21 @@ * Every SSH target's legacy relay bridge, and the one seam the rest of main calls. * COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import type { EventProps } from '../../../shared/telemetry-events' +import type { EventProps } from '../../../../shared/telemetry-event-classification' import type { LegacyRelayBridgeAttachResult, LegacyRelayBridgeCloseResult, LegacyRelayBridgedPane -} from '../../../shared/legacy-relay-bridge-contract' -import { parseAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshPendingPtyKill } from '../../../shared/ssh-pending-pty-kill' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import type { SshConnection } from '../connection/ssh-connection' -import { waitForSentinel } from './ssh-relay-sentinel' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +} from '../../../../shared/legacy-relay-bridge-contract' +import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' +import type { SshPendingPtyKill } from '../../../../shared/ssh-pending-pty-kill' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import type { SshConnection } from '../../connection/ssh-connection' +import { waitForSentinel } from '../handshake/ssh-relay-sentinel' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { LegacyRelayClient } from './legacy-relay-client' -import { createLegacyRelayCliServer } from './legacy-relay-cli-server' -import { listLegacyRelayEndpoints, posixEndpointExited } from './legacy-relay-endpoints' +import { createLegacyRelayCliServer } from '../cli/legacy-relay-cli-server' +import { listLegacyRelayEndpoints, posixEndpointExited } from '../endpoints/legacy-relay-endpoints' import { LegacyRelayTargetBridge } from './legacy-relay-target-bridge' import { LegacyRelayHiddenOutput } from './legacy-relay-hidden-output' import { LegacyRelayPaneStops, type LegacyRelayStopProof } from './legacy-relay-pane-stops' @@ -33,7 +33,7 @@ import { legacyRelayChannels } from './legacy-relay-bridge-connections' import { PtyExitProof, type PtyRetirementEvidence -} from '../../pty/process-retirement/pty-exit-proof' +} from '../../../pty/process-retirement/pty-exit-proof' /** How long a connect waits for the first look at its relays before publishing the host. */ const START_BUDGET_MS = 20_000 diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-relay-restart.test.ts similarity index 92% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-relay-restart.test.ts index a7be8df24f4..4412260178c 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-relay-restart.test.ts @@ -1,7 +1,7 @@ /** Relay restarts reuse socket and pty-1 ids; identify panes by endpoint plus relay-reported incarnation. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' +import '../../../../shared/ssh-pty-id' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' import { ENDPOINT, type FakeRelay, @@ -10,13 +10,11 @@ import { newFakeRelay, PTY, TARGET -} from './legacy-relay-fake-relay.test-fixture' +} from './testing/legacy-relay-fake-relay.test-fixture' import { LegacyRelayPaneOwners } from './legacy-relay-pane-owners' import { LegacyRelayPaneStops } from './legacy-relay-pane-stops' -import { - LegacyRelayTargetBridge, - type LegacyRelayTargetBridgeDeps -} from './legacy-relay-target-bridge' +import { LegacyRelayTargetBridge } from './legacy-relay-target-bridge' +import type { LegacyRelayTargetBridgeDeps } from './legacy-relay-target-bridge-contract' let relay: FakeRelay let owners: LegacyRelayPaneOwners diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-restart-stop.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-restart-stop.test.ts similarity index 90% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-restart-stop.test.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-restart-stop.test.ts index afbd1de0a84..b2033f41e61 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-restart-stop.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-restart-stop.test.ts @@ -1,8 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { getRemoteHostPlatform } from '../ssh-remote-platform' -import { unusedSshConnection } from '../unused-host-transport.test-fixture' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import { getRemoteHostPlatform } from '../../remote-host/ssh-remote-platform' +import { unusedSshConnection } from '../../../managed-server/testing/managed-host-transport.test-fixture' const TARGET = 'ssh-box' const RELAY_PTY = 'pty2:epoch:1' @@ -13,7 +13,7 @@ const relay = vi.hoisted(() => { return { ptys: new Set(), shutdowns } }) -vi.mock('./legacy-relay-endpoints', () => ({ +vi.mock('../endpoints/legacy-relay-endpoints', () => ({ listLegacyRelayEndpoints: async () => ({ kind: 'listed', exhaustive: true, diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-runtime-exit.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-runtime-exit.test.ts similarity index 83% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-runtime-exit.test.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-runtime-exit.test.ts index 489d1e6b901..e3371d8e1b9 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-runtime-exit.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-runtime-exit.test.ts @@ -3,13 +3,13 @@ * listener for it: the bridge must tell the runtime itself, whichever route closed the tab. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { getRemoteHostPlatform } from '../ssh-remote-platform' -import type { PtyRuntimeControllerDeps } from '../../ipc/pty/runtime/controller-deps' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { LEGACY_RELAY_BRIDGE_CHANNELS } from '../../../shared/legacy-relay-bridge-contract' -import { unusedSshConnection } from '../unused-host-transport.test-fixture' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import { getRemoteHostPlatform } from '../../remote-host/ssh-remote-platform' +import type { PtyRuntimeControllerDeps } from '../../../ipc/pty/runtime/controller-deps' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { LEGACY_RELAY_BRIDGE_CHANNELS } from '../../../../shared/legacy-relay-bridge-contract' +import { unusedSshConnection } from '../../../managed-server/testing/managed-host-transport.test-fixture' const TARGET = 'ssh-box' const RELAY_PTY = 'pty2:epoch:1' @@ -33,8 +33,8 @@ vi.mock('electron', () => ({ removeAllListeners: vi.fn() } })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('./legacy-relay-endpoints', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../endpoints/legacy-relay-endpoints', () => ({ listLegacyRelayEndpoints: async () => ({ kind: 'listed', exhaustive: true, @@ -72,8 +72,7 @@ vi.mock('./legacy-relay-client', () => ({ const registry = await import('./legacy-relay-bridge-registry') const { registerLegacyRelayBridgeIpc } = await import('./legacy-relay-bridge-ipc') -const { killPtyFromRuntimeController, stopAndWaitPtyFromRuntimeController } = - await import('../../ipc/pty/runtime/kill') +const { killPtyFromRuntimeController } = await import('../../../ipc/pty/runtime/kill') let leases: SshRemotePtyLease[] let runtime: { @@ -161,18 +160,6 @@ describe('a bridged terminal the old relay proves exited', () => { expect(runtime.onPtyExit).toHaveBeenCalledWith(PTY, 0, undefined, { hostExitConfirmed: true }) }) - it('reaches the runtime once from a stop-and-wait, not again from the stop', async () => { - await startBridge() - - await expect( - stopAndWaitPtyFromRuntimeController(controllerDeps(), PTY, { - deadlineMs: Date.now() + 5_000 - }) - ).resolves.toBe(true) - - expect(runtime.onPtyExit).toHaveBeenCalledTimes(1) - }) - it('records a renderer bridge close as a deliberate stop before sending it', async () => { await startBridge() diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-timers.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-timers.ts similarity index 100% rename from src/main/ssh/legacy-relay/legacy-relay-bridge-timers.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-bridge-timers.ts diff --git a/src/main/ssh/legacy-relay/legacy-relay-client.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts similarity index 63% rename from src/main/ssh/legacy-relay/legacy-relay-client.test.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts index 3f9883a87c7..af7b544c86c 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-client.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts @@ -18,7 +18,7 @@ const fake = vi.hoisted(() => { } }) -vi.mock('../ssh-channel-multiplexer', () => ({ +vi.mock('../../protocol/ssh-channel-multiplexer', () => ({ SshChannelMultiplexer: class { private readonly notificationHandlers: (( method: string, @@ -103,15 +103,6 @@ beforeEach(() => { }) describe('the legacy relay client', () => { - it('asks for the owner role without flow control and accepts any build’s grant', async () => { - const client = await open() - expect(client.ownerClaim).toEqual({ ownerGeneration: 3, ownerLease: 'lease-a' }) - const [openClient] = fake.requests - expect(openClient.method).toBe('pty.openClient') - expect(openClient.params).toMatchObject({ requestedRole: 'session-owner' }) - expect(openClient.params).not.toHaveProperty('capabilities') - }) - it('never displaces an attached owner', async () => { fake.respond = () => { throw rpcError(-32044) @@ -120,33 +111,6 @@ describe('the legacy relay client', () => { expect(fake.requests).toHaveLength(1) }) - it('waits out a holder that disconnected within its grace', async () => { - let calls = 0 - fake.respond = () => { - calls += 1 - if (calls < 3) { - throw rpcError(-32045) - } - return GRANT - } - await expect(open()).resolves.toBeInstanceOf(LegacyRelayClient) - expect(calls).toBe(3) - }) - - it('drops a resume claim the relay no longer knows and asks for a fresh one', async () => { - let calls = 0 - fake.respond = (_method, params) => { - calls += 1 - if (params && 'resume' in params) { - throw rpcError(-32041) - } - return GRANT - } - await open({ ownerGeneration: 1, ownerLease: 'old' }) - expect(calls).toBe(2) - expect(fake.requests[1].params).not.toHaveProperty('resume') - }) - it('talks to a relay that predates owner claims', async () => { fake.respond = (method) => { if (method === 'pty.openClient') { @@ -161,30 +125,4 @@ describe('the legacy relay client', () => { fake.respond = () => ({ ...GRANT, role: 'subscriber' }) await expect(open()).rejects.toThrow('did not grant the terminal owner role') }) - - it('stops a terminal with the old relay’s own pty.shutdown request', async () => { - const client = await open() - fake.respond = () => undefined - await client.shutdown('pty-1') - expect(fake.requests.at(-1)).toEqual({ - method: 'pty.shutdown', - params: { id: 'pty-1', immediate: false, keepHistory: false } - }) - await client.shutdown('pty-1', 'inc-1') - expect(fake.requests.at(-1)).toEqual({ - method: 'pty.shutdown', - params: { id: 'pty-1', immediate: false, keepHistory: false, expectedIncarnationId: 'inc-1' } - }) - }) - - it('hangs up only itself on close', async () => { - const client = await open() - const closed = vi.fn() - client.onClose(closed) - client.close() - expect(client.closed).toBe(true) - expect(closed).toHaveBeenCalledTimes(1) - const methods = fake.requests.map((request: Request) => request.method) - expect(methods).not.toContain('pty.shutdown') - }) }) diff --git a/src/main/ssh/legacy-relay/legacy-relay-client.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-client.ts similarity index 98% rename from src/main/ssh/legacy-relay/legacy-relay-client.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-client.ts index 936ad047e4c..8907f26f2eb 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-client.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-client.ts @@ -1,7 +1,7 @@ /** Drive only already-listening legacy relays using their own relay.js --connect and matching bundle hash; deploy/start nothing. COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ import { z } from 'zod' -import type { MultiplexerTransport } from '../ssh-channel-multiplexer' -import { SshChannelMultiplexer } from '../ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../../protocol/ssh-multiplexer-transport-writer' +import { SshChannelMultiplexer } from '../../protocol/ssh-channel-multiplexer' const PROTOCOL_VERSION = 1 const OPEN_CLIENT_TIMEOUT_MS = 10_000 diff --git a/src/main/ssh/legacy-relay/legacy-relay-daily-activity.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-daily-activity.ts similarity index 94% rename from src/main/ssh/legacy-relay/legacy-relay-daily-activity.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-daily-activity.ts index a852ed2ec72..def11748949 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-daily-activity.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-daily-activity.ts @@ -1,5 +1,5 @@ /** Report active bridging once per target per UTC day to measure relay retirement. COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import type { EventProps } from '../../../shared/telemetry-events' +import type { EventProps } from '../../../../shared/telemetry-event-classification' type TerminalsBucket = EventProps<'ssh_host_server_legacy_relay_bridge'>['terminals'] type ActivityReport = (targetId: string, phase: 'active', terminals: number) => void diff --git a/src/main/ssh/legacy-relay/legacy-relay-hidden-output.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts similarity index 95% rename from src/main/ssh/legacy-relay/legacy-relay-hidden-output.test.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts index 722ba2bab25..7b181ff9b13 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-hidden-output.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts @@ -117,15 +117,6 @@ describe('a bridged pane no visible view shows', () => { expect(sent).toEqual(['data:\x1b]133;D;0\x07', 'data:\x1b]0;title\x1b\\\x07', 'data:\x07']) }) - it('re-reads nothing when a reattach’s screen already covered what was dropped', async () => { - subject.setPaused(PTY, true) - subject.onData(PTY, 'hidden') - subject.screenSent(PTY) - subject.setPaused(PTY, false) - await Promise.resolve() - expect(reread).not.toHaveBeenCalled() - }) - it('re-reads output a hidden pane printed after its reattach’s screen', async () => { subject.setPaused(PTY, true) subject.screenSent(PTY) diff --git a/src/main/ssh/legacy-relay/legacy-relay-hidden-output.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.ts similarity index 100% rename from src/main/ssh/legacy-relay/legacy-relay-hidden-output.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.ts diff --git a/src/main/ssh/legacy-relay/legacy-relay-move-retry.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.test.ts similarity index 69% rename from src/main/ssh/legacy-relay/legacy-relay-move-retry.test.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.test.ts index f1754108f23..5d710c43870 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-move-retry.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.test.ts @@ -1,8 +1,8 @@ /** #29626: only the relay's proof that the last bridged terminal ended retries the waiting move. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { unusedSshConnection } from '../unused-host-transport.test-fixture' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import { unusedSshConnection } from '../../../managed-server/testing/managed-host-transport.test-fixture' import { ENDPOINT, type FakeRelay, @@ -11,23 +11,19 @@ import { newFakeRelay, PTY, TARGET -} from './legacy-relay-fake-relay.test-fixture' +} from './testing/legacy-relay-fake-relay.test-fixture' import { installLegacyRelayBridge, legacyRelayBridgedPanes, startLegacyRelayBridge } from './legacy-relay-bridge-registry' -import { - type BridgedMoveRetryDeps, - onLastBridgedTerminalExit, - retryMoveAfterLastBridgedExit -} from './legacy-relay-move-retry' +import { onLastBridgedTerminalExit } from './legacy-relay-move-retry' let relay: FakeRelay let leases: SshRemotePtyLease[] let lastExits: string[] -vi.mock('./legacy-relay-endpoints', () => ({ +vi.mock('../endpoints/legacy-relay-endpoints', () => ({ listLegacyRelayEndpoints: async () => ({ kind: 'listed', exhaustive: true, @@ -118,28 +114,3 @@ describe('the last bridged relay terminal', () => { expect(lastExits).toEqual([TARGET]) }) }) - -function retryDeps(overrides: Partial = {}): BridgedMoveRetryDeps { - return { - waitingOnBridgedTerminals: () => true, - connectInFlight: () => undefined, - connect: vi.fn(async () => {}), - ...overrides - } -} - -describe('retrying the move', () => { - it('runs one automatic connect even when exits overlap', async () => { - let finish = (): void => {} - const connect = vi.fn(() => new Promise((resolve) => (finish = resolve))) - const deps = retryDeps({ connect }) - - const first = retryMoveAfterLastBridgedExit(TARGET, deps) - await vi.waitFor(() => expect(connect).toHaveBeenCalledTimes(1)) - await expect(retryMoveAfterLastBridgedExit(TARGET, deps)).resolves.toBe(false) - finish() - - await expect(first).resolves.toBe(true) - expect(connect).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/ssh/legacy-relay/legacy-relay-move-retry.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.ts similarity index 100% rename from src/main/ssh/legacy-relay/legacy-relay-move-retry.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.ts diff --git a/src/main/ssh/legacy-relay/legacy-relay-output-salvage.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-output-salvage.ts similarity index 95% rename from src/main/ssh/legacy-relay/legacy-relay-output-salvage.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-output-salvage.ts index 709e9ee1380..cf53461d295 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-output-salvage.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-output-salvage.ts @@ -2,8 +2,8 @@ import { findCsiFinalByteIndex, isStatefulRendererReplyCsiQuery -} from '../../../shared/terminal/protocol/queries/terminal-reply-query-extraction' -import { isReplayableCsi } from '../../../shared/terminal/protocol/queries/terminal-reply-query-scan' +} from '../../../../shared/terminal/protocol/queries/terminal-reply-query-extraction' +import { isReplayableCsi } from '../../../../shared/terminal/protocol/queries/terminal-reply-query-scan' const MAX_CSI_CHARS = 64 // Inline images are huge painting OSCs; bound their retained payload. diff --git a/src/main/ssh/legacy-relay/legacy-relay-pane-owners.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-pane-owners.ts similarity index 97% rename from src/main/ssh/legacy-relay/legacy-relay-pane-owners.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-pane-owners.ts index 36c608f1bbf..ec93e922c2d 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-pane-owners.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-pane-owners.ts @@ -1,6 +1,6 @@ /** Remember owners across reconnects by endpoint plus incarnation: pty-N ids repeat across relays and restarts. Never serve a replacement process under a known id. COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ import type { LegacyRelayClient } from './legacy-relay-client' -import { isEpochScopedRelayPtyId } from '../../../shared/ssh-pending-pty-kill' +import { isEpochScopedRelayPtyId } from '../../../../shared/ssh-pending-pty-kill' type Owner = { endpoint: string diff --git a/src/main/ssh/legacy-relay/legacy-relay-pane-stops.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-pane-stops.ts similarity index 95% rename from src/main/ssh/legacy-relay/legacy-relay-pane-stops.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-pane-stops.ts index 529c5cdf6ac..24a9b0a0f40 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-pane-stops.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-pane-stops.ts @@ -1,14 +1,14 @@ /** Retain closed-pane stops across reconnects until relay exit/absence is proven; lost contact stays unverifiable. Persist restart-fenced intent as pendingKill; connection-only identity cannot survive restart. COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import { parseAppSshPtyId, toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshPendingPtyKill } from '../../../shared/ssh-pending-pty-kill' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import type { LegacyRelayBridgeCloseResult } from '../../../shared/legacy-relay-bridge-contract' +import { parseAppSshPtyId, toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import type { SshPendingPtyKill } from '../../../../shared/ssh-pending-pty-kill' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import type { LegacyRelayBridgeCloseResult } from '../../../../shared/legacy-relay-bridge-contract' import { isStoppingLease, listedAppPtyIds } from './legacy-relay-bridge-leases' import { LegacyRelayExitProofs, LegacyRelayRetry } from './legacy-relay-bridge-timers' import type { LegacyRelayClient } from './legacy-relay-client' import type { LegacyRelayBridgeHost } from './legacy-relay-bridge-registry' import type { LegacyRelayTargetBridge } from './legacy-relay-target-bridge' -import { PtyRetirementWithoutProof } from '../../pty/process-retirement/pty-exit-proof' +import { PtyRetirementWithoutProof } from '../../../pty/process-retirement/pty-exit-proof' type StopTarget = Pick< LegacyRelayTargetBridge, diff --git a/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge-contract.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge-contract.ts new file mode 100644 index 00000000000..b1a04d63404 --- /dev/null +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge-contract.ts @@ -0,0 +1,27 @@ +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import type { LegacyRelayClient, LegacyRelayOwnerClaim } from './legacy-relay-client' +import type { + LegacyRelayEndpoint, + LegacyRelayEndpointListing +} from '../endpoints/legacy-relay-endpoints' +import type { LegacyRelayPaneOwners } from './legacy-relay-pane-owners' + +export type LegacyRelayTargetBridgeDeps = { + targetId: string + leases: () => SshRemotePtyLease[] + /** Only on the relay's word: its exit report, or every relay answered and none holds it. */ + retireLease: (relayPtyId: string, proof: 'exit-observed' | 'absent') => void + listEndpoints: (signal: AbortSignal) => Promise + openClient: ( + endpoint: LegacyRelayEndpoint, + resume: LegacyRelayOwnerClaim | null + ) => Promise + /** Only a dead socket proves its relay gone; anything else about a failed open is unverifiable. */ + endpointExited: (endpoint: LegacyRelayEndpoint) => Promise + onPanesChanged: () => void + onData: (ptyId: string, data: string) => void + onExit: (ptyId: string, code: number) => void + onTerminalExited: () => void + /** Ownership survives bridge replacement on reconnect. */ + owners: LegacyRelayPaneOwners +} diff --git a/src/main/ssh/legacy-relay/legacy-relay-target-bridge.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts similarity index 96% rename from src/main/ssh/legacy-relay/legacy-relay-target-bridge.test.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts index 78d2fbf3dd7..af50a39637a 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-target-bridge.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts @@ -1,7 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import type { LegacyRelayEndpoint, LegacyRelayEndpointListing } from './legacy-relay-endpoints' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import type { + LegacyRelayEndpoint, + LegacyRelayEndpointListing +} from '../endpoints/legacy-relay-endpoints' import { ENDPOINT, type FakeRelay, @@ -10,13 +13,11 @@ import { newFakeRelay, PTY, TARGET -} from './legacy-relay-fake-relay.test-fixture' +} from './testing/legacy-relay-fake-relay.test-fixture' import { LegacyRelayPaneStops } from './legacy-relay-pane-stops' import { LegacyRelayPaneOwners } from './legacy-relay-pane-owners' -import { - LegacyRelayTargetBridge, - type LegacyRelayTargetBridgeDeps -} from './legacy-relay-target-bridge' +import { LegacyRelayTargetBridge } from './legacy-relay-target-bridge' +import type { LegacyRelayTargetBridgeDeps } from './legacy-relay-target-bridge-contract' let relay: FakeRelay let owners: LegacyRelayPaneOwners @@ -253,13 +254,6 @@ describe('one target’s legacy relay bridge', () => { expect(leases[0].pendingKill).toBeUndefined() }) - it('never lists a relay for a lease a newer pane won', async () => { - leases = [lease({ supersededBy: 'pty-3' }), lease({ ptyId: 'pty-4', tabId: undefined })] - relay.ptys = new Set(['pty-1', 'pty-4']) - await bridge().refresh() - expect(relay.clients).toEqual([]) - }) - it('stops a closed tab’s shell through the relay and retires it on the relay’s exit report', async () => { const subject = bridge() await subject.refresh() @@ -476,16 +470,6 @@ describe('one target’s legacy relay bridge', () => { expect(leases[0].pendingKill).toBeUndefined() }) - it('keeps the first close’s record when the tab’s close repeats', async () => { - const epochPty = toAppSshPtyId(TARGET, 'pty2:epoch:1') - leases = [lease({ ptyId: 'pty2:epoch:1' })] - await stops.stop(epochPty, null) - const first = leases[0].pendingKill - await vi.advanceTimersByTimeAsync(5_000) - await stops.stop(epochPty, null) - expect(leases[0].pendingKill).toBe(first) - }) - it('restores a fenced stop across a restart and sends it only to the same process', async () => { relay.incarnations.set('pty-1', 'inc-1') const subject = bridge() diff --git a/src/main/ssh/legacy-relay/legacy-relay-target-bridge.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.ts similarity index 89% rename from src/main/ssh/legacy-relay/legacy-relay-target-bridge.ts rename to src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.ts index 71c6d703c84..9fd0bce1d93 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-target-bridge.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.ts @@ -1,12 +1,13 @@ +import type { LegacyRelayTargetBridgeDeps } from './legacy-relay-target-bridge-contract' /** Bridge leased legacy panes until relay-proven exit or a complete census proves absence. Lost contact stays unverifiable (docs/reference/ssh-execution-boundary.md). COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' + import type { LegacyRelayBridgeAttachResult, LegacyRelayBridgedPane -} from '../../../shared/legacy-relay-bridge-contract' +} from '../../../../shared/legacy-relay-bridge-contract' import type { LegacyRelayClient, LegacyRelayOwnerClaim } from './legacy-relay-client' -import type { LegacyRelayEndpoint, LegacyRelayEndpointListing } from './legacy-relay-endpoints' +import type { LegacyRelayEndpoint } from '../endpoints/legacy-relay-endpoints' import { LegacyRelayRetry, LegacyRelayWaiters } from './legacy-relay-bridge-timers' import { ATTACH_WAIT_MS, @@ -21,27 +22,6 @@ import { servedBridgedPanes, type Pane } from './legacy-relay-bridge-leases' -import type { LegacyRelayPaneOwners } from './legacy-relay-pane-owners' - -export type LegacyRelayTargetBridgeDeps = { - targetId: string - leases: () => SshRemotePtyLease[] - /** Only on the relay's word: its exit report, or every relay answered and none holds it. */ - retireLease: (relayPtyId: string, proof: 'exit-observed' | 'absent') => void - listEndpoints: (signal: AbortSignal) => Promise - openClient: ( - endpoint: LegacyRelayEndpoint, - resume: LegacyRelayOwnerClaim | null - ) => Promise - /** Only a dead socket proves its relay gone; anything else about a failed open is unverifiable. */ - endpointExited: (endpoint: LegacyRelayEndpoint) => Promise - onPanesChanged: () => void - onData: (ptyId: string, data: string) => void - onExit: (ptyId: string, code: number) => void - onTerminalExited: () => void - /** Ownership survives bridge replacement on reconnect. */ - owners: LegacyRelayPaneOwners -} // Viewer acquisitions must stay unique across bridges so late releases cannot affect successors. let lastAcquisitionId = 0 diff --git a/src/main/ssh/legacy-relay/legacy-relay-fake-relay.test-fixture.ts b/src/main/ssh/legacy-relay/bridge/testing/legacy-relay-fake-relay.test-fixture.ts similarity index 90% rename from src/main/ssh/legacy-relay/legacy-relay-fake-relay.test-fixture.ts rename to src/main/ssh/legacy-relay/bridge/testing/legacy-relay-fake-relay.test-fixture.ts index 26fe5a7962f..5c63caaab00 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-fake-relay.test-fixture.ts +++ b/src/main/ssh/legacy-relay/bridge/testing/legacy-relay-fake-relay.test-fixture.ts @@ -1,8 +1,8 @@ -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { getRemoteHostPlatform } from '../ssh-remote-platform' -import type { LegacyRelayClient } from './legacy-relay-client' -import type { LegacyRelayEndpoint } from './legacy-relay-endpoints' +import { toAppSshPtyId } from '../../../../../shared/ssh-pty-id' +import type { SshRemotePtyLease } from '../../../../../shared/ssh-types' +import { getRemoteHostPlatform } from '../../../remote-host/ssh-remote-platform' +import type { LegacyRelayClient } from '../legacy-relay-client' +import type { LegacyRelayEndpoint } from '../../endpoints/legacy-relay-endpoints' export const TARGET = 'ssh-box' export const PTY = toAppSshPtyId(TARGET, 'pty-1') diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-args.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-args.ts similarity index 95% rename from src/main/ssh/legacy-relay/legacy-relay-cli-args.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-args.ts index 968b5db4e94..9bff2cf70ca 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-args.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-args.ts @@ -2,11 +2,11 @@ * Reads the argv an older relay forwards for one `orca` command run in its terminal. * COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import { CLI_BOOLEAN_FLAGS } from '../../../shared/cli-argument-boundary' +import { CLI_BOOLEAN_FLAGS } from '../../../../shared/cli-argument-boundary' import { isOrchestrationRetryRequestId, RETRY_REQUEST_ID_GUIDANCE -} from '../../../shared/orchestration/orchestration-retry-request-id' +} from '../../../../shared/orchestration/orchestration-retry-request-id' type LegacyRelayCliArgs = { command: string; flags: Map } diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-call-limits.test.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.test.ts similarity index 75% rename from src/main/ssh/legacy-relay/legacy-relay-cli-call-limits.test.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.test.ts index 0379f6bdc06..dbf1850dc00 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-call-limits.test.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.test.ts @@ -2,15 +2,14 @@ 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 { toAppSshPtyId } from '../../../shared/ssh-pty-id' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' -import { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' -import '../../runtime/orchestration/db/contract-constants' -import '../../runtime/orchestration/db/messages/mailbox-routing-page' -import '../../runtime/orchestration/db/dispatch-row-writer' -import '../../runtime/orchestration/db/attempt-outcome-projection' -import { LEGACY_RELAY_CLI_BUSY, runLegacyRelayCliCall } from './legacy-relay-cli-call-limits' +import { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' +import '../../../runtime/orchestration/db/contract-constants' +import '../../../runtime/orchestration/db/messages/mailbox-routing-page' +import '../../../runtime/orchestration/db/dispatch-row-writer' +import '../../../runtime/orchestration/db/attempt-outcome-projection' import { createLegacyRelayCliServer } from './legacy-relay-cli-server' const TARGET = 'target-1' @@ -66,45 +65,6 @@ const server = () => }) describe('limits on relay-era CLI calls', () => { - it('caps how many calls one host may hold open', async () => { - const release: (() => void)[] = [] - const held = Array.from({ length: 16 }, () => - runLegacyRelayCliCall( - TARGET, - () => true, - new AbortController().signal, - () => new Promise((resolve) => release.push(resolve)) - ) - ) - await expect( - runLegacyRelayCliCall( - TARGET, - () => true, - new AbortController().signal, - async () => {} - ) - ).rejects.toThrow(LEGACY_RELAY_CLI_BUSY) - // Another host is unaffected. - await expect( - runLegacyRelayCliCall( - 'other-target', - () => true, - new AbortController().signal, - async () => 1 - ) - ).resolves.toBe(1) - release.forEach((resolve) => resolve()) - await Promise.all(held) - await expect( - runLegacyRelayCliCall( - TARGET, - () => true, - new AbortController().signal, - async () => 2 - ) - ).resolves.toBe(2) - }) - it('scopes a reused retry id whose payload differs from the committed one', async () => { const retry = ['--retry-request', '66666666-6666-4666-8666-666666666666'] await server().cli( diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-call-limits.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts similarity index 87% rename from src/main/ssh/legacy-relay/legacy-relay-cli-call-limits.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts index 4c23e31d7e2..36579cbd252 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-call-limits.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts @@ -3,16 +3,16 @@ * that may skip part of the scope check. * COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import { ORCHESTRATION_ASK_MAX_TIMEOUT_MS } from '../../../shared/orchestration/mailbox/orchestration-ask-timeout' -import { isDurableMutation } from '../../../shared/orchestration/orchestration-rpc-contract' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { ALL_RPC_METHODS } from '../../runtime/rpc/methods/rpc-method-registry' +import { ORCHESTRATION_ASK_MAX_TIMEOUT_MS } from '../../../../shared/orchestration/mailbox/orchestration-ask-timeout' +import { isDurableMutation } from '../../../../shared/orchestration/orchestration-rpc-contract' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { ALL_RPC_METHODS } from '../../../runtime/rpc/methods/rpc-method-registry' import { hashCanonical, readPromptBasePayloadHash, replayStableCallerParams -} from '../../runtime/rpc/orchestration-mutation-receipt' -import { getCompiledSchema } from '../../schema-validation/zod-schema-compilation' +} from '../../../runtime/rpc/orchestration-mutation-receipt' +import { getCompiledSchema } from '../../../schema-validation/zod-schema-compilation' import type { LegacyRelayCliCall } from './legacy-relay-cli-caller' /** Enough for a coordinator and its workers' waits; past it a host is flooding this desktop. */ diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-caller.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-caller.ts similarity index 95% rename from src/main/ssh/legacy-relay/legacy-relay-cli-caller.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-caller.ts index edf6e23c3ae..22f8b01ece9 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-caller.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-caller.ts @@ -7,15 +7,15 @@ * the claimed handle (as a Dispatch assignee or a Run coordinator). It then reaches only its own * mailboxes, its own Dispatch or Run, and the other party of that same orchestration. */ -import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import type { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' -import { isEquivalentPaneKey } from '../../runtime/orchestration/db/pane-key-match' +import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import type { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' +import { isEquivalentPaneKey } from '../../../runtime/orchestration/db/pane-key-match' import type { DispatchContextRow, RunRow -} from '../../runtime/orchestration/db/orchestration-records' -import type { LegacyRelayLivePane } from './legacy-relay-bridge-leases' +} from '../../../runtime/orchestration/db/orchestration-records' +import type { LegacyRelayLivePane } from '../bridge/legacy-relay-bridge-leases' const MAX_IDENTITY_LENGTH = 512 diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-legacy-records.test.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-legacy-records.test.ts similarity index 93% rename from src/main/ssh/legacy-relay/legacy-relay-cli-legacy-records.test.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-legacy-records.test.ts index 4477d1eb6e0..8d307aad479 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-legacy-records.test.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-legacy-records.test.ts @@ -3,15 +3,15 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import Database from '../../sqlite/sync-database' -import { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' -import '../../runtime/orchestration/db/contract-constants' -import '../../runtime/orchestration/db/messages/mailbox-routing-page' -import '../../runtime/orchestration/db/dispatch-row-writer' -import '../../runtime/orchestration/db/attempt-outcome-projection' -import { createRootDispatch } from '../../runtime/orchestration/db/root-dispatch-test-fixture' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import Database from '../../../sqlite/sync-database' +import { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' +import '../../../runtime/orchestration/db/contract-constants' +import '../../../runtime/orchestration/db/messages/mailbox-routing-page' +import '../../../runtime/orchestration/db/dispatch-row-writer' +import '../../../runtime/orchestration/db/attempt-outcome-projection' +import { createRootDispatch } from '../../../runtime/orchestration/db/root-dispatch-test-fixture' import { LEGACY_RELAY_CLI_UNVERIFIED } from './legacy-relay-cli-caller' import { createLegacyRelayCliServer } from './legacy-relay-cli-server' diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-output.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-output.ts similarity index 97% rename from src/main/ssh/legacy-relay/legacy-relay-cli-output.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-output.ts index 4984d7eb9ec..76624ce6bd6 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-output.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-output.ts @@ -7,8 +7,8 @@ import { formatOrchestrationCheckText, prepareOrchestrationCheckOutput, type OrchestrationCheckOutput -} from '../../../shared/orchestration/mailbox/orchestration-check-output' -import type { RpcResponse } from '../../runtime/rpc/core' +} from '../../../../shared/orchestration/mailbox/orchestration-check-output' +import type { RpcResponse } from '../../../runtime/rpc/core' import { stringFlag } from './legacy-relay-cli-args' import type { LegacyRelayCliCall, LegacyRelayCliCaller } from './legacy-relay-cli-caller' diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-server.test.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts similarity index 81% rename from src/main/ssh/legacy-relay/legacy-relay-cli-server.test.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts index b55412daba8..d56582aeb35 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-server.test.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts @@ -2,22 +2,22 @@ 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 { CONNECTOR_REPLY_UNAVAILABLE } from '../../../shared/rpc-contract/connector-params' -import { toAppSshPtyId } from '../../../shared/ssh-pty-id' -import '../../../shared/ssh-remote-cli-control' -import { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { OrchestrationDb } from '../../runtime/orchestration/db/orchestration-db' -import '../../runtime/orchestration/db/contract-constants' -import '../../runtime/orchestration/db/messages/mailbox-routing-page' -import '../../runtime/orchestration/db/dispatch-row-writer' -import '../../runtime/orchestration/db/attempt-outcome-projection' +import { CONNECTOR_REPLY_UNAVAILABLE } from '../../../../shared/rpc-contract/connector-params' +import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' +import '../../../../shared/ssh-remote-cli-control' +import { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' +import '../../../runtime/orchestration/db/contract-constants' +import '../../../runtime/orchestration/db/messages/mailbox-routing-page' +import '../../../runtime/orchestration/db/dispatch-row-writer' +import '../../../runtime/orchestration/db/attempt-outcome-projection' import { LEGACY_RELAY_CLI_UNVERIFIED } from './legacy-relay-cli-caller' import { createLegacyRelayCliServer, LEGACY_RELAY_CLI_CONTROL_OFF, LEGACY_RELAY_CLI_UNSUPPORTED } from './legacy-relay-cli-server' -import type { LegacyRelayLivePane } from './legacy-relay-bridge-leases' +import type { LegacyRelayLivePane } from '../bridge/legacy-relay-bridge-leases' const TARGET = 'target-1' const WORKER = 'term_relay_worker' @@ -236,26 +236,6 @@ describe('the relay-era orca CLI on the desktop runtime', () => { ).rejects.toThrow(LEGACY_RELAY_CLI_UNVERIFIED) }) - it('replays a completed worker_done after the terminal took a new assignment', async () => { - const retry = ['--retry-request', '44444444-4444-4444-8444-444444444444'] - const first = await run([...workerDone(), ...retry]) - const next = db.createTask({ - runId: ids.runId, - spec: 'next', - createdByTerminalHandle: COORDINATOR - }) - db.createDispatchContext({ - taskId: next.id, - assigneeHandle: WORKER, - assigneePaneKey: WORKER_PANE, - processIncarnation: `${PTY_ID}:inc-1`, - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER - }) - const replay = await run([...workerDone(), ...retry]) - expect(json(replay).result?.message).toEqual(json(first).result?.message) - }) - it("never lets a completed retry id unlock another caller's mailbox", async () => { const retry = ['--retry-request', '55555555-5555-4555-8555-555555555555'] await run(['orchestration', 'send', '--to', COORDINATOR, '--subject', 'hi', ...retry]) @@ -266,17 +246,4 @@ describe('the relay-era orca CLI on the desktop runtime', () => { run(['orchestration', 'check', '--terminal', COORDINATOR, ...retry]) ).rejects.toThrow(/outside it/) }) - - it('stops a waiting check when the relay connection closes', async () => { - const closed = new AbortController() - const waiting = run( - ['orchestration', 'check', '--wait', '--timeout-ms', '60000', '--json'], - ENV, - closed.signal - ) - await new Promise((resolve) => setTimeout(resolve, 50)) - closed.abort() - const result = await waiting - expect(json(result).result).toMatchObject({ cancelled: true }) - }) }) diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-server.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.ts similarity index 93% rename from src/main/ssh/legacy-relay/legacy-relay-cli-server.ts rename to src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.ts index 4a4c4e82163..c45e9bcd49d 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-server.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.ts @@ -8,12 +8,12 @@ * no grants (the desktop browser bridge's shape), after legacy-relay-cli-caller.ts bound them. */ import { createHash, randomUUID } from 'node:crypto' -import { ORCHESTRATION_CONTRACT_VERSION } from '../../../shared/orchestration/orchestration-runtime-capabilities' -import { DESKTOP_BROWSER_BRIDGE_SETTING_LABEL } from '../../../shared/desktop-browser-bridge-protocol' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import type { RpcResponse } from '../../runtime/rpc/core' -import { RpcDispatcher } from '../../runtime/rpc/dispatcher' -import { ALL_RPC_METHODS } from '../../runtime/rpc/methods/rpc-method-registry' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/orchestration/orchestration-runtime-capabilities' +import { DESKTOP_BROWSER_BRIDGE_SETTING_LABEL } from '../../../../shared/desktop-browser-bridge-protocol' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import type { RpcResponse } from '../../../runtime/rpc/core' +import { RpcDispatcher } from '../../../runtime/rpc/dispatcher' +import { ALL_RPC_METHODS } from '../../../runtime/rpc/methods/rpc-method-registry' import { assertLegacyRelayCliScope, resolveLegacyRelayCliCaller, @@ -27,8 +27,8 @@ import { retryRequestFlag, stringFlag } from './legacy-relay-cli-args' -import type { LegacyRelayCliServer } from './legacy-relay-client' -import { CONNECTOR_REPLY_UNAVAILABLE } from '../../../shared/rpc-contract/connector-params' +import type { LegacyRelayCliServer } from '../bridge/legacy-relay-client' +import { CONNECTOR_REPLY_UNAVAILABLE } from '../../../../shared/rpc-contract/connector-params' import { cappedInboxLimit, cappedWait, @@ -36,7 +36,7 @@ import { runLegacyRelayCliCall } from './legacy-relay-cli-call-limits' import { formatLegacyRelayCliResult, isRecord } from './legacy-relay-cli-output' -import type { LegacyRelayLivePane } from './legacy-relay-bridge-leases' +import type { LegacyRelayLivePane } from '../bridge/legacy-relay-bridge-leases' const METHODS: ReadonlySet = new Set([ 'orchestration.check', diff --git a/src/main/ssh/legacy-relay/legacy-relay-endpoints.ts b/src/main/ssh/legacy-relay/endpoints/legacy-relay-endpoints.ts similarity index 90% rename from src/main/ssh/legacy-relay/legacy-relay-endpoints.ts rename to src/main/ssh/legacy-relay/endpoints/legacy-relay-endpoints.ts index a487ce51dde..fd1fa84f9f4 100644 --- a/src/main/ssh/legacy-relay/legacy-relay-endpoints.ts +++ b/src/main/ssh/legacy-relay/endpoints/legacy-relay-endpoints.ts @@ -1,21 +1,21 @@ /** List this target's legacy sockets/pipes and their own bridge commands without changing them; other desktops hash different target ids. COMPAT(legacy-relay-bridge): revisit 2027-01-15. */ -import type { SshConnection } from '../connection/ssh-connection' -import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { RELAY_REMOTE_DIR } from '../remote-exec/remote-frame-protocol' -import { SHORT_RELAY_SOCKET_DIR_PREFIX } from '../relay-socket-path-limit' -import { execCommand } from '../remote-exec/remote-exec-command' +import type { SshConnection } from '../../connection/ssh-connection' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { RELAY_REMOTE_DIR } from '../../../managed-server/install/remote-install-root' +import { SHORT_RELAY_SOCKET_DIR_PREFIX } from './relay-socket-path-limit' +import { execCommand } from '../../remote-exec/remote-exec-command' import { readRelayDaemonRuntimes } from './ssh-relay-endpoint-runtime' import { relaySocketNameForInstanceId } from './ssh-relay-instance-id' import { probeRelayEndpointIncumbent } from './ssh-relay-endpoint-incumbent' -import { readRemoteHomeCommand } from '../ssh-remote-commands' -import { resolveRemoteNodePath } from '../ssh-remote-node-resolution' -import { detectRemoteHostPlatform } from '../ssh-remote-platform-detection' +import { readRemoteHomeCommand } from '../../remote-exec/ssh-remote-commands' +import { resolveRemoteNodePath } from '../../remote-host/node-toolchain/ssh-remote-node-resolution' +import { detectRemoteHostPlatform } from '../../remote-host/ssh-remote-platform-detection' import { isWindowsRemoteHost, normalizeRemoteHome, validateRemoteHome, type RemoteHostPlatform -} from '../ssh-remote-platform' +} from '../../remote-host/ssh-remote-platform' import { parseWindowsRelayInventory, windowsRelayInventoryCommand diff --git a/src/main/ssh/relay-daemon-service-children.ts b/src/main/ssh/legacy-relay/endpoints/relay-daemon-service-children.ts similarity index 94% rename from src/main/ssh/relay-daemon-service-children.ts rename to src/main/ssh/legacy-relay/endpoints/relay-daemon-service-children.ts index 733d7cc004d..c6eea63feec 100644 --- a/src/main/ssh/relay-daemon-service-children.ts +++ b/src/main/ssh/legacy-relay/endpoints/relay-daemon-service-children.ts @@ -1,6 +1,6 @@ /** Exclude only positively identified daemon service children from reap decisions. Persistent AI Vault sidecars made raw childCount===0 unreachable (#13614); unknown argv/children still retain the relay (docs/reference/ssh-execution-boundary.md). */ import { RELAY_DAEMON_SERVICE_ENTRY_FILENAMES } from './relay-install-artifacts' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' export const RELAY_CHILD_COUNT_VAR = 'kids' diff --git a/src/main/ssh/relay-install-artifacts.ts b/src/main/ssh/legacy-relay/endpoints/relay-install-artifacts.ts similarity index 90% rename from src/main/ssh/relay-install-artifacts.ts rename to src/main/ssh/legacy-relay/endpoints/relay-install-artifacts.ts index dc4c19633fd..52c9ae01999 100644 --- a/src/main/ssh/relay-install-artifacts.ts +++ b/src/main/ssh/legacy-relay/endpoints/relay-install-artifacts.ts @@ -1,6 +1,6 @@ /** Classify legacy relay installs (≤1.4.224) left by older clients; Orca no longer builds/deploys them. Retire this inventory with the host census. */ -import { ORCAD_WINDOWS_PROCESS_TREE_FILENAME } from '../../shared/orcad-artifacts' -import { OPENCODE_SQLITE_READER_FILENAME } from '../../shared/remote-bundle-artifacts' +import { ORCAD_WINDOWS_PROCESS_TREE_FILENAME } from '../../../../shared/orcad-artifacts' +import { OPENCODE_SQLITE_READER_FILENAME } from '../../../../shared/remote-bundle-artifacts' type RelayArtifact = { filename: string diff --git a/src/main/ssh/relay-socket-path-limit.ts b/src/main/ssh/legacy-relay/endpoints/relay-socket-path-limit.ts similarity index 100% rename from src/main/ssh/relay-socket-path-limit.ts rename to src/main/ssh/legacy-relay/endpoints/relay-socket-path-limit.ts diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-census-for-target.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.test.ts similarity index 62% rename from src/main/ssh/legacy-relay/ssh-host-relay-census-for-target.test.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.test.ts index 861425e7a53..0fa1e5f2e85 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-census-for-target.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { SshConnection } from '../connection/ssh-connection' -import type { SshTarget } from '../../../shared/ssh-types' -import { unusedSshConnection } from '../unused-host-transport.test-fixture' +import type { SshConnection } from '../../connection/ssh-connection' +import type { SshTarget } from '../../../../shared/ssh-types' +import { unusedSshConnection } from '../../../managed-server/testing/managed-host-transport.test-fixture' const mocks = vi.hoisted(() => ({ connect: vi.fn(), @@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({ disconnectConnection: vi.fn(async () => undefined), census: vi.fn() })) -vi.mock('../../managed-server/lifecycle/orcad-managed-runtime-context', () => ({ +vi.mock('../../../managed-server/lifecycle/orcad-managed-runtime-context', () => ({ requireManagedOrcadInfrastructure: () => ({ connectionManager: { connect: mocks.connect, @@ -24,7 +24,7 @@ vi.mock('./ssh-host-relay-terminals-on-connect', () => ({ })) const { censusHostRelayTerminalsFor } = await import('./ssh-host-relay-census-for-target') -const attribution = await import('../connection/ssh-connection-attribution') +const attribution = await import('../../connection/ssh-connection-attribution') const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } const transport = (): SshConnection => unusedSshConnection() @@ -50,33 +50,6 @@ describe('a host census outside any connect', () => { expect(mocks.disconnectConnection).toHaveBeenCalledWith('ssh-1', opened) }) - it('leaves a transport a connect or tunnel adopted while it ran', async () => { - const opened = transport() - mocks.connect.mockImplementation(async () => { - attribution.recordSshConnectionOpened(opened) - mocks.getConnection.mockReturnValue(opened) - return opened - }) - mocks.census.mockImplementation(async () => { - attribution.adoptSshConnection(opened, Symbol('connect')) - return {} - }) - await censusHostRelayTerminalsFor(target)() - expect(mocks.disconnectConnection).not.toHaveBeenCalled() - }) - - it('leaves a transport it only reused', async () => { - const existing = transport() - mocks.getConnection.mockReturnValue(existing) - mocks.connect.mockImplementation(async () => { - attribution.recordSshConnectionReused(existing) - return existing - }) - mocks.census.mockResolvedValue({}) - await censusHostRelayTerminalsFor(target)() - expect(mocks.disconnectConnection).not.toHaveBeenCalled() - }) - it("inside a connect's decision leaves the transport to that connect", async () => { const opened = transport() const decision = Symbol('decision') diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-census-for-target.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.ts similarity index 83% rename from src/main/ssh/legacy-relay/ssh-host-relay-census-for-target.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.ts index 43d87e9ad5c..63e4c5d65d0 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-census-for-target.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.ts @@ -1,12 +1,12 @@ -import type { SshTarget } from '../../../shared/ssh-types' -import type { CensusHostRelayTerminals } from '../orcad-migration-terminal-gate' -import { requireManagedOrcadInfrastructure } from '../../managed-server/lifecycle/orcad-managed-runtime-context' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { CensusHostRelayTerminals } from '../../migration-source/orcad-migration-terminal-gate' +import { requireManagedOrcadInfrastructure } from '../../../managed-server/lifecycle/orcad-managed-runtime-context' import { beginSshHostCensus, currentSshOwner, isSshConnectionSolelyOwnedBy, runAttributedToSshOwner -} from '../connection/ssh-connection-attribution' +} from '../../connection/ssh-connection-attribution' import { censusSshHostRelaysBeforeSession, hostTerminalProofFromCensus diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-endpoint-census.ts similarity index 91% rename from src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-endpoint-census.ts index 627d5a431bb..d65baecb91e 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-endpoint-census.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-endpoint-census.ts @@ -1,9 +1,9 @@ /** Census all account-owned relays, including other desktops, before a session exists. Failed/truncated listings and unknown endpoints stay unverifiable; lost contact never proves exit (docs/reference/ssh-execution-boundary.md). */ -import type { SshConnection } from '../connection/ssh-connection' -import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { RELAY_REMOTE_DIR } from '../remote-exec/remote-frame-protocol' -import { SHORT_RELAY_SOCKET_DIR_PREFIX } from '../relay-socket-path-limit' -import { execCommand } from '../remote-exec/remote-exec-command' +import type { SshConnection } from '../../connection/ssh-connection' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { RELAY_REMOTE_DIR } from '../../../managed-server/install/remote-install-root' +import { SHORT_RELAY_SOCKET_DIR_PREFIX } from './relay-socket-path-limit' +import { execCommand } from '../../remote-exec/remote-exec-command' import { isReapableRelayHusk, probeRelayEndpointIncumbent, @@ -11,7 +11,7 @@ import { } from './ssh-relay-endpoint-incumbent' import { countRelayEndpointPtys } from './ssh-relay-endpoint-pty-count' import { readRelayDaemonRuntimes } from './ssh-relay-endpoint-runtime' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../ssh-remote-platform' +import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' /** `unenumerable`: Windows named pipes cannot be listed, so the caller keeps today's path. */ type HostRelayEndpointVerdict = 'none' | 'idle' | 'live' | 'unverifiable' | 'unenumerable' diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-terminals-on-connect.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-terminals-on-connect.ts similarity index 79% rename from src/main/ssh/legacy-relay/ssh-host-relay-terminals-on-connect.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-terminals-on-connect.ts index e85b9982f3a..773c0ed9d35 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-terminals-on-connect.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-terminals-on-connect.ts @@ -1,26 +1,26 @@ /** Let host-owned endpoints decide conversion safety, including terminals another desktop opened. */ -import type { Store } from '../../persistence/loading-store/store' -import type { HostServerTerminalVerdict } from '../ssh-host-server-on-connect' +import type { Store } from '../../../persistence/loading-store/store' +import type { HostServerTerminalVerdict } from '../../host-server/ssh-host-server-on-connect' import { censusHostRelayEndpoints, type HostRelayEndpointCensus } from './ssh-host-relay-endpoint-census' -import type { SshConnection } from '../connection/ssh-connection' +import type { SshConnection } from '../../connection/ssh-connection' import { censusWindowsHostRelays, windowsCensusNodePath } from './ssh-host-relay-windows-census' -import { execCommand } from '../remote-exec/remote-exec-command' -import { readRemoteHomeCommand } from '../ssh-remote-commands' -import { resolveRemoteNodePath } from '../ssh-remote-node-resolution' -import { detectRemoteHostPlatform } from '../ssh-remote-platform-detection' +import { execCommand } from '../../remote-exec/remote-exec-command' +import { readRemoteHomeCommand } from '../../remote-exec/ssh-remote-commands' +import { resolveRemoteNodePath } from '../../remote-host/node-toolchain/ssh-remote-node-resolution' +import { detectRemoteHostPlatform } from '../../remote-host/ssh-remote-platform-detection' import { isWindowsRemoteHost, normalizeRemoteHome, validateRemoteHome -} from '../ssh-remote-platform' +} from '../../remote-host/ssh-remote-platform' import { assessOrcadMigrationTerminals, terminalsRunElsewhere, type HostRelayTerminalProof -} from '../orcad-migration-terminal-gate' +} from '../../migration-source/orcad-migration-terminal-gate' export async function relayTerminalsOnConnect(args: { store: Pick diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-windows-census.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts similarity index 91% rename from src/main/ssh/legacy-relay/ssh-host-relay-windows-census.test.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts index 4b35c62643f..ab23d5622cc 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-windows-census.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts @@ -1,24 +1,27 @@ -import type * as ExecCommandModule from '../remote-exec/remote-exec-command' +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 type { SshConnection } from '../../connection/ssh-connection' import { relaySocketNameForInstanceId } from './ssh-relay-instance-id' import { windowsRelayPipePathsForSocketName } from './ssh-relay-endpoints' -import { getRemoteHostPlatform, joinRemotePath } from '../ssh-remote-platform' +import { getRemoteHostPlatform, joinRemotePath } from '../../remote-host/ssh-remote-platform' const { execCommand, countRelayPtysOverBridge } = vi.hoisted(() => ({ execCommand: vi.fn(), countRelayPtysOverBridge: vi.fn() })) -vi.mock('../remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../../remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand })) vi.mock('./ssh-relay-endpoint-pty-count', () => ({ countRelayPtysOverBridge })) -vi.mock('../ssh-remote-commands', async (importOriginal) => ({ - ...(await importOriginal>()), - listRemoteInstallBaseDirsCommand: () => 'LIST' -})) +vi.mock( + '../../../managed-server/install/remote-install-gc-listing-command', + async (importOriginal) => ({ + ...(await importOriginal>()), + listRemoteInstallBaseDirsCommand: () => 'LIST' + }) +) vi.mock('./ssh-host-relay-windows-inventory', async (importOriginal) => ({ ...(await importOriginal>()), windowsRelayInventoryCommand: () => 'INVENTORY', diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-windows-census.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.ts similarity index 81% rename from src/main/ssh/legacy-relay/ssh-host-relay-windows-census.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.ts index 4966c9c5ebc..29c8227e0ef 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-windows-census.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.ts @@ -1,7 +1,7 @@ /** Ask every account-owned relay pipe, including other desktops, through its own bridge/credential. Unmapped pipes stay unverifiable unless proven foreign or gone; unseen shells must block conversion. */ -import type { SshConnection } from '../connection/ssh-connection' -import { RELAY_REMOTE_DIR } from '../remote-exec/remote-frame-protocol' -import { RELAY_INSTALL_MODEL } from '../../managed-server/install/remote-install-model' +import type { SshConnection } from '../../connection/ssh-connection' +import { RELAY_REMOTE_DIR } from '../../../managed-server/install/remote-install-root' +import { RELAY_INSTALL_MODEL } from '../../../managed-server/install/remote-install-model' import type { HostRelayEndpointCensus } from './ssh-host-relay-endpoint-census' import { windowsPipesNotRunHere, @@ -10,19 +10,19 @@ import { windowsRelayInventoryCommand } from './ssh-host-relay-windows-inventory' import { countRelayPtysOverBridge } from './ssh-relay-endpoint-pty-count' -import { execCommand } from '../remote-exec/remote-exec-command' +import { execCommand } from '../../remote-exec/remote-exec-command' import { relaySocketNameForInstanceId } from './ssh-relay-instance-id' import { windowsRelayConnectCommand } from './ssh-relay-windows-launch-command' -import { listRemoteInstallBaseDirsCommand } from '../ssh-remote-commands' -import { joinRemotePath, type RemoteHostPlatform } from '../ssh-remote-platform' -import { isNodeRuntimeTarget } from '../../../shared/node-runtime-pin' -import { orcadNodeRuntimeExecutable } from '../../../shared/orcad-artifacts' +import { listRemoteInstallBaseDirsCommand } from '../../../managed-server/install/remote-install-gc-listing-command' +import { joinRemotePath, type RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' +import { isNodeRuntimeTarget } from '../../../../shared/node-runtime-pin' +import { orcadNodeRuntimeExecutable } from '../../../../shared/orcad-artifacts' import { nodeRuntimeStoreDir, remoteNodeRuntimePresentCommand -} from '../../managed-server/install/orcad-remote-node-runtime' -import { REMOTE_NODE_RUNTIME_READY } from '../orcad-remote-node-runtime-report' -import { resolveRemoteNodePath } from '../ssh-remote-node-resolution' +} from '../../../managed-server/install/orcad-remote-node-runtime' +import { REMOTE_NODE_RUNTIME_READY } from '../../../managed-server/install/orcad-remote-node-runtime-report' +import { resolveRemoteNodePath } from '../../remote-host/node-toolchain/ssh-remote-node-resolution' const MAX_CENSUS_PIPES = 32 diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-windows-inventory.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts similarity index 70% rename from src/main/ssh/legacy-relay/ssh-host-relay-windows-inventory.test.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts index 62b4945cc24..35a329449d9 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-windows-inventory.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts @@ -9,15 +9,11 @@ import { parseWindowsRelayInventory, WINDOWS_RELAY_INVENTORY_JS } from './ssh-host-relay-windows-inventory' - -import { relaySocketNameForInstanceId } from './ssh-relay-instance-id' -import { windowsRelayPipePathsForSocketName } from './ssh-relay-endpoints' -import { getRemoteHostPlatform, joinRemotePath } from '../ssh-remote-platform' +import { getRemoteHostPlatform } from '../../remote-host/ssh-remote-platform' const host = getRemoteHostPlatform('win32-x64') const HOME = 'C:\\Users\\dev' const VERSION = 'relay-0.1.0+aaaaaaaaaaaa' -const DIR = joinRemotePath(host, HOME, '.orca-remote', VERSION) describe('the Windows relay inventory', () => { let base: string | null = null @@ -51,26 +47,6 @@ describe('the Windows relay inventory', () => { }) }) - it("maps another desktop's pipes to its own instance and credential", () => { - const sockName = relaySocketNameForInstanceId('desktop-b') - const [primary] = windowsRelayPipePathsForSocketName(host, DIR, sockName) - const inventory = parseWindowsRelayInventory( - host, - HOME, - [], - JSON.stringify({ - pipes: [primary.slice('\\\\.\\pipe\\'.length)], - dirs: { [VERSION]: { credentials: [`${sockName}.credential`], markers: {} } } - }) - ) - - expect(inventory?.pipes).toEqual([primary]) - expect(inventory?.owners.get(primary.toLowerCase())).toEqual({ - dir: DIR, - credentialFile: joinRemotePath(host, DIR, `${sockName}.credential`) - }) - }) - it('treats an unlisted pipe table or an unreadable directory as incomplete', () => { expect(parseWindowsRelayInventory(host, HOME, [], 'not json')).toBeNull() expect(parseWindowsRelayInventory(host, HOME, [], '{"pipes":null,"dirs":{}}')).toBeNull() diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-windows-inventory.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.ts similarity index 94% rename from src/main/ssh/legacy-relay/ssh-host-relay-windows-inventory.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.ts index 66fa5d68dc2..a6bfad6c057 100644 --- a/src/main/ssh/legacy-relay/ssh-host-relay-windows-inventory.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.ts @@ -1,16 +1,16 @@ /** Map machine-wide relay pipes to this account's version-directory credentials/markers. Deriving pipe names from this desktop's target id misses other desktops' relays. */ -import { RELAY_REMOTE_DIR } from '../remote-exec/remote-frame-protocol' -import { commandWithNodePath } from '../ssh-remote-commands' +import { RELAY_REMOTE_DIR } from '../../../managed-server/install/remote-install-root' +import { commandWithNodePath } from '../../remote-exec/ssh-remote-commands' import { quotePowerShellLiteral as powerShellLiteral, quotePowerShellNativeArgument as powerShellNativeArg -} from '../../../shared/powershell-native-argument' +} from '../../../../shared/powershell-native-argument' import { windowsRelayPipePathsForSocketName } from './ssh-relay-endpoints' import { RELAY_INSTALL_MODEL, remoteInstallVersionDirRegex -} from '../../managed-server/install/remote-install-model' -import { joinRemotePath, type RemoteHostPlatform } from '../ssh-remote-platform' +} from '../../../managed-server/install/remote-install-model' +import { joinRemotePath, type RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' type WindowsRelayPipeOwner = { dir: string; credentialFile: string } diff --git a/src/main/ssh/legacy-relay/ssh-host-relay-windows-pipe-access.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-pipe-access.test.ts similarity index 100% rename from src/main/ssh/legacy-relay/ssh-host-relay-windows-pipe-access.test.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-pipe-access.test.ts diff --git a/src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts similarity index 96% rename from src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts index 9e0e4d41fdc..dbd35d2561e 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts @@ -10,7 +10,7 @@ import { relayEndpointIncumbentProbeCommand, type RelayEndpointIncumbent } from './ssh-relay-endpoint-incumbent' -import { RELAY_DAEMON_SERVICE_ENTRY_FILENAMES } from '../relay-install-artifacts' +import { RELAY_DAEMON_SERVICE_ENTRY_FILENAMES } from './relay-install-artifacts' const posixOnly = process.platform === 'win32' ? describe.skip : describe @@ -115,11 +115,6 @@ afterAll(() => { rmSync(workDir, { recursive: true, force: true }) }) -it('runs the holder-enumeration assertions on this machine', () => { - // Require lsof so these cases exercise the reap gate rather than silently degrading to verdict checks. - expect(hasLsof).toBe(true) -}) - posixOnly('relay endpoint probe against a real socket', () => { it('reports live, and identifies the holding process, for a listening relay', async () => { const sockPath = join(workDir, 'live.sock') diff --git a/src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts similarity index 96% rename from src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts index 2b2c29e8133..3e29de8f0ac 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts @@ -1,15 +1,18 @@ /** Probe this endpoint only: unlinking a refusing live socket strands its relay/PTYs (#8585). Exit requires refused connect, complete no-holder evidence and local storage; shared-home sockets may live on another kernel. Missing tools or ambiguous failures stay unverifiable and never authorize cleanup (docs/reference/ssh-execution-boundary.md). */ import { RELAY_LSOF_PROBE_JS } from '@orca/process-host/posix-lsof-probe' -import type { SshConnection } from '../connection/ssh-connection' -import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import type { SshConnection } from '../../connection/ssh-connection' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import { RELAY_CHILD_COUNT_VAR, RELAY_UNRECOGNIZED_CHILD_COUNT_VAR, relayDaemonChildCensusShell -} from '../relay-daemon-service-children' -import { execCommand, isUnconfirmedSshCommandTermination } from '../remote-exec/remote-exec-command' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../ssh-remote-platform' -import { filesystemTypeIsLocalDisk } from '../../orcad/orcad-data-root-locality' +} from './relay-daemon-service-children' +import { + execCommand, + isUnconfirmedSshCommandTermination +} from '../../remote-exec/remote-exec-command' +import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' +import { filesystemTypeIsLocalDisk } from '../../../orcad/orcad-data-root-locality' type RelayEndpointVerdict = 'live' | 'unverifiable' | 'exited' diff --git a/src/main/ssh/legacy-relay/ssh-relay-endpoint-pty-count.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-pty-count.ts similarity index 84% rename from src/main/ssh/legacy-relay/ssh-relay-endpoint-pty-count.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-pty-count.ts index f90ec470c70..00af6418177 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-endpoint-pty-count.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-pty-count.ts @@ -1,9 +1,9 @@ /** Ask via the relay's own bridge/hash when process-table evidence is incomplete. pty.listProcesses needs no owner role and cannot take another desktop's PTYs. */ -import type { SshConnection } from '../connection/ssh-connection' -import { SshChannelMultiplexer } from '../ssh-channel-multiplexer' -import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { SHORT_RELAY_SOCKET_DIR_PREFIX } from '../relay-socket-path-limit' -import { waitForSentinel } from './ssh-relay-sentinel' +import type { SshConnection } from '../../connection/ssh-connection' +import { SshChannelMultiplexer } from '../../protocol/ssh-channel-multiplexer' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { SHORT_RELAY_SOCKET_DIR_PREFIX } from './relay-socket-path-limit' +import { waitForSentinel } from '../handshake/ssh-relay-sentinel' const RELAY_PTY_COUNT_TIMEOUT_MS = 10_000 diff --git a/src/main/ssh/legacy-relay/ssh-relay-endpoint-runtime.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts similarity index 100% rename from src/main/ssh/legacy-relay/ssh-relay-endpoint-runtime.test.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts diff --git a/src/main/ssh/legacy-relay/ssh-relay-endpoint-runtime.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.ts similarity index 89% rename from src/main/ssh/legacy-relay/ssh-relay-endpoint-runtime.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.ts index 6ff4907b6ff..0149afd8a24 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-endpoint-runtime.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.ts @@ -1,6 +1,6 @@ /** Read runtimes from daemon argv so pinned-runtime hosts without Node on PATH can still answer relay probes. */ -import type { SshConnection } from '../connection/ssh-connection' -import { execCommand } from '../remote-exec/remote-exec-command' +import type { SshConnection } from '../../connection/ssh-connection' +import { execCommand } from '../../remote-exec/remote-exec-command' const RELAY_DAEMON_MARKER = ' relay.js --detached ' diff --git a/src/main/ssh/legacy-relay/ssh-relay-endpoints.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoints.ts similarity index 94% rename from src/main/ssh/legacy-relay/ssh-relay-endpoints.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoints.ts index 6efd5d5bf34..248c2dfa0a3 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-endpoints.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoints.ts @@ -3,7 +3,7 @@ import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../ssh-remote-platform' +} from '../../remote-host/ssh-remote-platform' function relayEndpointForHost( hostPlatform: RemoteHostPlatform, diff --git a/src/main/ssh/legacy-relay/ssh-relay-incumbent-process.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-incumbent-process.test.ts similarity index 60% rename from src/main/ssh/legacy-relay/ssh-relay-incumbent-process.test.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-incumbent-process.test.ts index d5f3370f30d..f78d346896a 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-incumbent-process.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-incumbent-process.test.ts @@ -1,11 +1,11 @@ -import type * as ExecCommandModule from '../remote-exec/remote-exec-command' -import { mkdtempSync, writeFileSync, rmSync, readFileSync } from 'node:fs' +import type * as ExecCommandModule from '../../remote-exec/remote-exec-command' +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { createServer } from 'node:net' import { describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -vi.mock('../remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../../remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand: vi.fn() })) @@ -19,7 +19,7 @@ async function probe(script: string, listening = false) { const dir = mkdtempSync(join(tmpdir(), 'orca-incumbent-')) const socket = join(dir, 'socket with spaces.sock') const server = createServer((s) => s.end()) - const pidFile = join(dir, 'probe.pid') + try { writeFileSync(join(dir, 'lsof'), `#!/bin/sh\n${script}`, { mode: 0o755 }) if (listening) { @@ -28,64 +28,28 @@ async function probe(script: string, listening = false) { server.listen(socket, resolve) }) } - const start = performance.now() + const result = await runProcess({ program: '/bin/sh', args: ['-c', relayEndpointIncumbentProbeCommand(process.execPath, socket)], - env: { ...process.env, PATH: `${dir}:${process.env.PATH}`, FIXTURE_PID: pidFile }, + env: { ...process.env, PATH: `${dir}:${process.env.PATH}` }, timeoutMs: 12000, detached: true, terminationBarrier: true }) const verdict = parseRelayEndpointIncumbentProbe(socket, result.stdout) - let pidAlive: boolean | null = null - try { - const pid = Number(readFileSync(pidFile, 'utf8')) - const state = await runProcess({ - program: 'ps', - args: ['-o', 'state=', '-p', String(pid)], - timeoutMs: 2000 - }) - pidAlive = !( - (state.code === 1 && !state.stdout.trim()) || - (state.code === 0 && state.stdout.trim().startsWith('Z')) - ) - } catch {} - return { result, verdict, elapsedMs: performance.now() - start, pidAlive } + + return { result, verdict } } finally { if (listening) { await new Promise((resolve) => server.close(() => resolve())) } - try { - const pid = Number(readFileSync(pidFile, 'utf8')) - if (Number.isInteger(pid) && pid > 0) { - process.kill(pid, 'SIGKILL') - } - } catch {} + rmSync(dir, { recursive: true, force: true }) } } // Each probe owns its socket, shim and process group; overlap the real lsof deadlines. describe.skipIf(process.platform === 'win32').concurrent('real generated incumbent probe', () => { - it('bounds hung lsof and preserves live connect evidence', async () => { - const p = await probe('echo $$ > "$FIXTURE_PID"\nexec sleep 60\n', true) - expect(p.result.timedOut).toBe(false) - expect(p.result.code).toBe(0) - expect(p.verdict).toMatchObject({ - verdict: 'live', - holdersEnumerable: false, - evidence: 'accepted-connection' - }) - expect(p.pidAlive).toBe(false) - expect(p.elapsedMs).toBeLessThan(10000) - }) - it('stops a hung lsof helper as well as its parent', async () => { - const p = await probe('sleep 60 &\necho $! > "$FIXTURE_PID"\nwait\n', true) - expect(p.result.timedOut).toBe(false) - expect(p.verdict).toMatchObject({ verdict: 'live', holdersEnumerable: false }) - expect(p.pidAlive).toBe(false) - expect(p.elapsedMs).toBeLessThan(10000) - }) it('does not mistake diagnostic enumeration failure for proven absence', async () => { const p = await probe('echo "lsof: access denied" >&2\nexit 1\n') expect(p.verdict).toMatchObject({ verdict: 'unverifiable', holdersEnumerable: false }) diff --git a/src/main/ssh/legacy-relay/ssh-relay-instance-id.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-instance-id.ts similarity index 100% rename from src/main/ssh/legacy-relay/ssh-relay-instance-id.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-instance-id.ts diff --git a/src/main/ssh/legacy-relay/ssh-relay-windows-launch-command.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-windows-launch-command.ts similarity index 70% rename from src/main/ssh/legacy-relay/ssh-relay-windows-launch-command.ts rename to src/main/ssh/legacy-relay/endpoints/ssh-relay-windows-launch-command.ts index 9378940013d..4e4b757c362 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-windows-launch-command.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-windows-launch-command.ts @@ -1,6 +1,6 @@ -import { commandWithNodePath } from '../ssh-remote-commands' -import type { RemoteHostPlatform } from '../ssh-remote-platform' -import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' +import { commandWithNodePath } from '../../remote-exec/ssh-remote-commands' +import type { RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../../shared/powershell-native-argument' export function windowsRelayConnectCommand( hostPlatform: RemoteHostPlatform, diff --git a/src/main/ssh/legacy-relay/ssh-relay-credential-mismatch-error.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-credential-mismatch-error.ts similarity index 100% rename from src/main/ssh/legacy-relay/ssh-relay-credential-mismatch-error.ts rename to src/main/ssh/legacy-relay/handshake/ssh-relay-credential-mismatch-error.ts diff --git a/src/main/ssh/legacy-relay/ssh-relay-handshake-mismatch.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-handshake-mismatch.ts similarity index 100% rename from src/main/ssh/legacy-relay/ssh-relay-handshake-mismatch.ts rename to src/main/ssh/legacy-relay/handshake/ssh-relay-handshake-mismatch.ts diff --git a/src/main/ssh/legacy-relay/ssh-relay-sentinel-copy-budget.test.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts similarity index 93% rename from src/main/ssh/legacy-relay/ssh-relay-sentinel-copy-budget.test.ts rename to src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts index 3d9388ac8c9..5d6552b4ae4 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-sentinel-copy-budget.test.ts +++ b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import type { ClientChannel } from 'ssh2' import { expect, it, vi } from 'vitest' -import { RELAY_SENTINEL } from '../remote-exec/remote-frame-protocol' +import { RELAY_SENTINEL } from '../../protocol/relay-handshake' import { waitForSentinel } from './ssh-relay-sentinel' it.each(Array.from({ length: RELAY_SENTINEL.length + 1 }, (_, i) => i))( diff --git a/src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts similarity index 97% rename from src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts rename to src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts index bb41dfbe72a..ba5d82ceb3a 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-sentinel.test.ts +++ b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' 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 { RELAY_SENTINEL } from '../../protocol/relay-handshake' import './ssh-relay-version-mismatch-error' import './ssh-relay-credential-mismatch-error' diff --git a/src/main/ssh/legacy-relay/ssh-relay-sentinel.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.ts similarity index 96% rename from src/main/ssh/legacy-relay/ssh-relay-sentinel.ts rename to src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.ts index 454e4cf6665..bcc41fd9a24 100644 --- a/src/main/ssh/legacy-relay/ssh-relay-sentinel.ts +++ b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.ts @@ -1,7 +1,7 @@ import type { ClientChannel } from 'ssh2' -import { createSshOperationAbortError } from '../connection/ssh-exec-options' -import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../remote-exec/remote-frame-protocol' -import type { MultiplexerTransport } from '../ssh-channel-multiplexer' +import { createSshOperationAbortError } from '../../connection/ssh-exec-options' +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../../protocol/relay-handshake' +import type { MultiplexerTransport } from '../../protocol/ssh-multiplexer-transport-writer' import { buildRelayHandshakeRefusalError } from './ssh-relay-handshake-mismatch' const MAX_RELAY_STARTUP_BUFFER_BYTES = 64 * 1024 diff --git a/src/main/ssh/legacy-relay/ssh-relay-version-mismatch-error.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-version-mismatch-error.ts similarity index 100% rename from src/main/ssh/legacy-relay/ssh-relay-version-mismatch-error.ts rename to src/main/ssh/legacy-relay/handshake/ssh-relay-version-mismatch-error.ts diff --git a/src/main/ssh/legacy-relay/legacy-relay-bridge-timers.test.ts b/src/main/ssh/legacy-relay/legacy-relay-bridge-timers.test.ts deleted file mode 100644 index ab3baa81c04..00000000000 --- a/src/main/ssh/legacy-relay/legacy-relay-bridge-timers.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { LegacyRelayExitProofs } from './legacy-relay-bridge-timers' - -beforeEach(() => { - vi.useFakeTimers() -}) - -afterEach(() => { - vi.useRealTimers() -}) - -describe('waiting on a bridged pane’s exit proof', () => { - it('settles every overlapping waiter on one exit', async () => { - const proofs = new LegacyRelayExitProofs() - const first = proofs.wait('pty', 5_000) - const second = proofs.wait('pty', 5_000) - proofs.observe('pty') - await expect(Promise.all([first, second])).resolves.toEqual([true, true]) - }) - - it('never lets an earlier waiter’s deadline drop a later one', async () => { - const proofs = new LegacyRelayExitProofs() - const stale = proofs.wait('pty', 1_000) - await vi.advanceTimersByTimeAsync(500) - const retry = proofs.wait('pty', 5_000) - await vi.advanceTimersByTimeAsync(600) - await expect(stale).resolves.toBe(false) - proofs.observe('pty') - await expect(retry).resolves.toBe(true) - }) - - it('answers false on dispose', async () => { - const proofs = new LegacyRelayExitProofs() - const waiting = proofs.wait('pty', 5_000) - proofs.dispose() - await expect(waiting).resolves.toBe(false) - }) -}) diff --git a/src/main/ssh/legacy-relay/legacy-relay-cli-output.test.ts b/src/main/ssh/legacy-relay/legacy-relay-cli-output.test.ts deleted file mode 100644 index c5b1dc0f434..00000000000 --- a/src/main/ssh/legacy-relay/legacy-relay-cli-output.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { expect, it } from 'vitest' -import { formatLegacyRelayCliResult } from './legacy-relay-cli-output' - -// Relay-era terminals keep the full check text; the CLI's concise view must not leak into it. -it('prints a relay-era check with its reply hints and the ack an older batch needs', () => { - const output = formatLegacyRelayCliResult( - { method: 'orchestration.check', params: {} }, - { - id: 'req_1', - ok: true, - result: { - messages: [ - { - id: 'msg_q', - run_id: 'run_1', - from_handle: 'dispatch:ctx_1', - to_handle: 'run:run_1', - subject: 'Question', - body: 'Proceed?', - type: 'question', - payload: '{"options":["yes","no"]}' - } - ], - count: 1, - deliveryId: 'delivery_1' - }, - _meta: { runtimeId: 'runtime_1' } - }, - { handle: 'term_coord', paneKey: 'tab:leaf', ptyId: 'pty_1' }, - new Map() - ) - - expect(output).toEqual({ - stdout: [ - 'Delivery delivery_1', - 'msg_q [question] from=dispatch:ctx_1', - '[subject]', - ' Question', - '[body]', - ' Proceed?', - '[payload]', - ' {"options":["yes","no"]}', - '[Reply: orca orchestration reply --id msg_q --body "..."]', - 'This Orca version does not acknowledge batches automatically. After handling every message, rerun this check with --ack delivery_1.', - '' - ].join('\n'), - stderr: '', - exitCode: 0 - }) -}) diff --git a/src/main/ssh/managed-server-fence-recheck.test.ts b/src/main/ssh/managed-server-fence-recheck.test.ts deleted file mode 100644 index 2a2d017140c..00000000000 --- a/src/main/ssh/managed-server-fence-recheck.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' -import { - FENCE_RECHECK_INTERVAL_MS, - recheckFencedManagedServer, - scheduleManagedServerFenceRecheck -} from './managed-server-fence-recheck' -import { MANAGED_ORCAD_FENCED_DETAIL } from '../managed-server/lifecycle/orcad-managed-serving' - -const TARGET: SshTarget = { id: 'box', label: 'Box', host: 'box', port: 22, username: 'me' } - -function hostDeps(states: ('fenced' | 'serving')[], update: 'fence-busy' | 'current') { - return { - ensureServing: vi.fn(async () => - states.shift() === 'fenced' - ? { state: 'unverifiable' as const, detail: MANAGED_ORCAD_FENCED_DETAIL } - : { state: 'serving' as const } - ), - autoUpdate: vi.fn(async () => - update === 'fence-busy' - ? { - outcome: 'deferred' as const, - code: 'orcad_activation_fence_busy', - reason: 'Another update holds this host.' - } - : { outcome: 'skipped' as const, reason: 'current' as const } - ), - recordedUpdateFailure: () => null, - failedThisLaunch: () => true, - recordUpdateFailure: vi.fn(), - clearUpdateFailure: vi.fn() - } -} - -beforeEach(() => { - vi.useFakeTimers() -}) -afterEach(() => { - vi.useRealTimers() -}) - -describe('a desktop that met another desktop’s update fence', () => { - it('rechecks until the host serves again, then publishes it without the note', async () => { - const deps = hostDeps(['fenced', 'fenced', 'serving'], 'current') - const publish = vi.fn() - scheduleManagedServerFenceRecheck(TARGET.id, { - stillCurrent: () => true, - recheck: () => recheckFencedManagedServer(TARGET, 'env-1', deps), - publish - }) - - await vi.advanceTimersByTimeAsync(FENCE_RECHECK_INTERVAL_MS * 2) - expect(publish).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(FENCE_RECHECK_INTERVAL_MS) - expect(publish).toHaveBeenCalledWith({ route: 'managed', environmentId: 'env-1' }) - await vi.advanceTimersByTimeAsync(FENCE_RECHECK_INTERVAL_MS * 3) - expect(deps.ensureServing).toHaveBeenCalledTimes(3) - }) - - it('keeps rechecking while the update is still deferred on the fence', async () => { - const deps = hostDeps(['serving', 'serving'], 'fence-busy') - const publish = vi.fn() - scheduleManagedServerFenceRecheck(TARGET.id, { - stillCurrent: () => true, - recheck: () => recheckFencedManagedServer(TARGET, 'env-1', deps), - publish - }) - await vi.advanceTimersByTimeAsync(FENCE_RECHECK_INTERVAL_MS * 2) - expect(publish).not.toHaveBeenCalled() - expect(deps.autoUpdate).toHaveBeenCalledTimes(2) - }) - - it('stops once the host disconnected or another connect took over', async () => { - const deps = hostDeps(['serving'], 'current') - const publish = vi.fn() - scheduleManagedServerFenceRecheck(TARGET.id, { - stillCurrent: () => false, - recheck: () => recheckFencedManagedServer(TARGET, 'env-1', deps), - publish - }) - await vi.advanceTimersByTimeAsync(FENCE_RECHECK_INTERVAL_MS * 3) - expect(deps.ensureServing).not.toHaveBeenCalled() - expect(publish).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ssh/managed-server-update-check.test.ts b/src/main/ssh/managed-server-update-check.test.ts deleted file mode 100644 index 722782ff58f..00000000000 --- a/src/main/ssh/managed-server-update-check.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' -import { - checkManagedServerUpdate, - type ManagedServerUpdateDeps -} from './managed-server-update-check' -import type { ManagedOrcadAutoUpdateOutcome } from '../managed-server/lifecycle/orcad-managed-auto-update' - -const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } - -function deps( - outcome: ManagedOrcadAutoUpdateOutcome | Error, - overrides: Partial = {} -): ManagedServerUpdateDeps { - return { - autoUpdate: vi.fn(async () => { - if (outcome instanceof Error) { - throw outcome - } - return outcome - }), - recordedUpdateFailure: () => null, - failedThisLaunch: () => true, - recordUpdateFailure: vi.fn(), - clearUpdateFailure: vi.fn(), - ...overrides - } -} - -const check = (d: ManagedServerUpdateDeps) => checkManagedServerUpdate(target, 'env-1', d, vi.fn()) - -describe('a recorded update failure', () => { - it.each([ - ['a failure recorded by an earlier launch', 'old'], - ['no recorded failure', null] - ])('with %s, lets only one of two overlapping checks try the update', async (_name, recorded) => { - const failedThisLaunch = new Set() - let failure: string | null = recorded - let lock: Promise = Promise.resolve() - let attempts = 0 - const d = deps( - { outcome: 'failed', reason: 'bad' }, - { - recordedUpdateFailure: () => failure, - failedThisLaunch: (t) => failedThisLaunch.has(t.id), - recordUpdateFailure: (t, reason) => { - failure = reason - failedThisLaunch.add(t.id) - }, - // Serialize like the host lifecycle lock, reading each decision after the preceding update. - autoUpdate: (_id, options) => { - const run = lock.then(async (): Promise => { - if (options.failedBefore()) { - return { outcome: 'skipped', reason: 'failed-before' } - } - attempts += 1 - return { outcome: 'failed', reason: 'bad' } - }) - lock = run - return run - } - } - ) - const results = await Promise.all([check(d), check(d)]) - expect(attempts).toBe(1) - // The waiting check must observe the newly recorded failure. - expect(results[1].note).toEqual({ state: 'failed', detail: 'bad' }) - }) -}) diff --git a/src/main/ssh/managed-server-update-deps.test.ts b/src/main/ssh/managed-server-update-deps.test.ts deleted file mode 100644 index 7a5d4ff9324..00000000000 --- a/src/main/ssh/managed-server-update-deps.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' -import { managedServerUpdateDeps } from './managed-server-update-deps' -import { checkManagedServerUpdate } from './managed-server-update-check' - -vi.mock('../../shared/app-environment', () => ({ - getAppEnvironment: () => ({ getVersion: () => '1.4.300' }) -})) - -const stored = new Map() -// Model store copies so writes must be re-read instead of mutating caller snapshots. -vi.mock('../managed-server/lifecycle/orcad-managed-runtime-context', () => ({ - requireManagedOrcadTargetStore: () => ({ - getTarget: (id: string) => { - const entry = stored.get(id) - return entry ? { ...entry } : undefined - }, - updateTarget: (id: string, updates: Partial) => { - const entry = stored.get(id) - if (entry) { - stored.set(id, { ...entry, ...updates }) - } - return entry ?? null - } - }) -})) -vi.mock('../managed-server/lifecycle/orcad-managed-auto-update', () => ({ - autoUpdateManagedOrcadEnvironment: vi.fn() -})) - -const target = (id: string): SshTarget => ({ id, label: id, host: id, port: 22, username: 'me' }) - -describe('remembering a managed-server update failure for this launch', () => { - it('counts only an actual failure, and outlives the per-connect deps', () => { - stored.set('a', target('a')) - const deps = managedServerUpdateDeps('/tmp/user-data') - expect(deps.failedThisLaunch(target('a'))).toBe(false) - deps.recordUpdateFailure(target('a'), 'candidate rejected') - expect(managedServerUpdateDeps('/tmp/user-data').failedThisLaunch(target('a'))).toBe(true) - expect(deps.failedThisLaunch(target('b'))).toBe(false) - }) - - it('an overlapping check sees the failure the first one recorded on a copy it took earlier', async () => { - stored.set('c', target('c')) - // Both caller snapshots predate either check, as connect and tunnel restore can. - const first = { ...stored.get('c')! } - const second = { ...stored.get('c')! } - const deps = managedServerUpdateDeps('/tmp/user-data') - let tries = 0 - let lock = Promise.resolve() - const autoUpdate: typeof deps.autoUpdate = (_environmentId, options) => { - const run = lock.then(() => { - if (options.failedBefore()) { - return { outcome: 'skipped' as const, reason: 'failed-before' as const } - } - tries += 1 - return { outcome: 'failed' as const, reason: 'bad' } - }) - lock = run.then(() => undefined) - return run - } - const withLock = { ...deps, autoUpdate } - - const results = await Promise.all([ - checkManagedServerUpdate(first, 'env-c', withLock, () => {}), - checkManagedServerUpdate(second, 'env-c', withLock, () => {}) - ]) - - expect(tries).toBe(1) - expect(results[1].note).toEqual({ state: 'failed', detail: 'bad' }) - }) -}) diff --git a/src/main/ssh/legacy-relay/orcad-migration-bridged-panes.test.ts b/src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts similarity index 90% rename from src/main/ssh/legacy-relay/orcad-migration-bridged-panes.test.ts rename to src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts index 0cb697d6080..27e000e4856 100644 --- a/src/main/ssh/legacy-relay/orcad-migration-bridged-panes.test.ts +++ b/src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts @@ -6,8 +6,8 @@ import { manifest } from '../../persistence/migrating-orcad-catalog/persistence-orcad-migration-catalog-fixture' import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { preservesOrcadMigrationBridgedPanes } from '../orcad-migration-bridged-panes' -import { isBridgeableLease } from './legacy-relay-bridge-leases' +import { preservesOrcadMigrationBridgedPanes } from './orcad-migration-bridged-panes' +import { isBridgeableLease } from '../legacy-relay/bridge/legacy-relay-bridge-leases' const LEASE: SshRemotePtyLease = { targetId: 'ssh-prod', diff --git a/src/main/ssh/orcad-migration-bridged-panes.ts b/src/main/ssh/migration-source/orcad-migration-bridged-panes.ts similarity index 86% rename from src/main/ssh/orcad-migration-bridged-panes.ts rename to src/main/ssh/migration-source/orcad-migration-bridged-panes.ts index 260f75442c8..812a35bbf29 100644 --- a/src/main/ssh/orcad-migration-bridged-panes.ts +++ b/src/main/ssh/migration-source/orcad-migration-bridged-panes.ts @@ -1,7 +1,7 @@ -import type { OrcadMigrationCatalogPayload } from '../../shared/orcad-migration/orcad-migration-manifest' -import type { SshRemotePtyLease } from '../../shared/ssh-types' -import { collectLeafIds } from '../../shared/workspace-layout/terminal-pane-layout-tree' -import { normalizeWorkspaceSessionKeyToWorkspaceId } from '../../shared/workspace-scope' +import type { OrcadMigrationCatalogPayload } from '../../../shared/orcad-migration/orcad-migration-manifest' +import type { SshRemotePtyLease } from '../../../shared/ssh-types' +import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree' +import { normalizeWorkspaceSessionKeyToWorkspaceId } from '../../../shared/workspace-scope' export type OrcadMigrationPaneLeasePredicate = (lease: SshRemotePtyLease) => boolean diff --git a/src/main/ssh/orcad-migration-source-assertions.ts b/src/main/ssh/migration-source/orcad-migration-source-assertions.ts similarity index 87% rename from src/main/ssh/orcad-migration-source-assertions.ts rename to src/main/ssh/migration-source/orcad-migration-source-assertions.ts index 0c0638262a4..c722d0daaef 100644 --- a/src/main/ssh/orcad-migration-source-assertions.ts +++ b/src/main/ssh/migration-source/orcad-migration-source-assertions.ts @@ -2,16 +2,16 @@ import { createHash } from 'node:crypto' import { serializeOrcadMigrationValue, type OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import type { OrcadMigrationSourceCutover } from '../../shared/orcad-migration/orcad-migration-source-cutover' +} from '../../../shared/orcad-migration/orcad-migration-manifest' +import type { OrcadMigrationSourceCutover } from '../../../shared/orcad-migration/orcad-migration-source-cutover' import { exportOrcadMigrationManifest, type OrcadMigrationExportedBlob -} from './orcad-migration-manifest-export' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' import { resolveOrcadMigrationFence } from './orcad-migration-source-fence' import { confirmOrcadMigrationTerminalsUnderFence } from './orcad-migration-terminal-gate' -import { collectUntransferredDependentBlockers } from './targets/ssh-target-orcad-dependents' -import type { OrcadMigrationPreflightStore } from './targets/ssh-target-orcad-preflight' +import { collectUntransferredDependentBlockers } from '../targets/ssh-target-orcad-dependents' +import type { OrcadMigrationPreflightStore } from '../targets/ssh-target-orcad-preflight' /** Returns the re-read bytes of the blobs the journaled manifest names; unchanged source proves them. */ export function assertOrcadMigrationSourceUnchanged( diff --git a/src/main/ssh/orcad-migration-source-fence.test.ts b/src/main/ssh/migration-source/orcad-migration-source-fence.test.ts similarity index 88% rename from src/main/ssh/orcad-migration-source-fence.test.ts rename to src/main/ssh/migration-source/orcad-migration-source-fence.test.ts index 512b4dd992f..94b129a5892 100644 --- a/src/main/ssh/orcad-migration-source-fence.test.ts +++ b/src/main/ssh/migration-source/orcad-migration-source-fence.test.ts @@ -2,22 +2,22 @@ import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import type { SshTarget } from '../../shared/ssh-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' +import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' +import type { SshTarget } from '../../../shared/ssh-types' +import { closeTestStores, createSqliteTestStore } from '../../persistence/persistence-test-harness' +import { Store } from '../../persistence/loading-store/store' import { listOrcadMigrationSourceCutovers, orcadMigrationCutoverJournalDirectory -} from './orcad-migration-cutover-journal' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { fenceOrcadMigrationSource, resolveOrcadMigrationFence } from './orcad-migration-source-fence' import type { OrcadMigrationTerminalVerdict } from './orcad-migration-terminal-gate' -import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' -import './orcad-migration-manifest-export' -import '../../shared/orcad-migration/orcad-migration-manifest-validation' +import { SshTargetOrcadClaims } from '../targets/ssh-target-orcad-claims' +import '../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' +import '../../../shared/orcad-migration/orcad-migration-manifest-validation' const TARGET: SshTarget = { id: 'ssh-prod', diff --git a/src/main/ssh/orcad-migration-source-fence.ts b/src/main/ssh/migration-source/orcad-migration-source-fence.ts similarity index 91% rename from src/main/ssh/orcad-migration-source-fence.ts rename to src/main/ssh/migration-source/orcad-migration-source-fence.ts index e99e20cc493..c8c41da60e4 100644 --- a/src/main/ssh/orcad-migration-source-fence.ts +++ b/src/main/ssh/migration-source/orcad-migration-source-fence.ts @@ -1,32 +1,30 @@ /** Persist journal, fence, then profile flush before remote calls. Crashes may leave a non-authoritative stale journal; a fence without a journal requires destination evidence before release. */ import { randomUUID } from 'node:crypto' -import { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import type { OrcadMigrationBlocker } from '../../shared/orcad-migration/orcad-migration-preflight' +import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' +import type { OrcadMigrationBlocker } from '../../../shared/orcad-migration/orcad-migration-preflight' import { ORCAD_MIGRATION_SOURCE_CUTOVER_VERSION, type OrcadMigrationSourceCutover -} from '../../shared/orcad-migration/orcad-migration-source-cutover' -import type { SshTarget } from '../../shared/ssh-types' -import { - assertOrcadMigrationRequestFits, - createOrcadMigrationManifest -} from './orcad-migration-manifest-export' +} from '../../../shared/orcad-migration/orcad-migration-source-cutover' +import type { SshTarget } from '../../../shared/ssh-types' +import { assertOrcadMigrationRequestFits } from '../../managed-server/migration/catalog/orcad-migration-request-budget' +import { createOrcadMigrationManifest } from '../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' import { findOrcadMigrationSourceCutoverForTarget, removeOrcadMigrationSourceCutover, writeOrcadMigrationSourceCutover -} from './orcad-migration-cutover-journal' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' import { confirmOrcadMigrationTerminalsUnderFence, type OrcadMigrationTerminalVerdict } from './orcad-migration-terminal-gate' -import type { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' +import type { SshTargetOrcadClaims } from '../targets/ssh-target-orcad-claims' import { isBlockingOrcadMigrationBlocker, preflightOrcadMigrationExport, type OrcadMigrationPreflightStore -} from './targets/ssh-target-orcad-preflight' -import { orcadMigrationRefusalReason } from './orcad-migration-refusal-reason' +} from '../targets/ssh-target-orcad-preflight' +import { orcadMigrationRefusalReason } from '../../managed-server/migration/cutover/orcad-migration-refusal-reason' import { preservesOrcadMigrationBridgedPanes, type OrcadMigrationPaneLeasePredicate diff --git a/src/main/ssh/orcad-migration-ssh-relay-source.test.ts b/src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts similarity index 67% rename from src/main/ssh/orcad-migration-ssh-relay-source.test.ts rename to src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts index 16f4a7f3bcd..d0ef3f5e2a5 100644 --- a/src/main/ssh/orcad-migration-ssh-relay-source.test.ts +++ b/src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts @@ -2,13 +2,13 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' -import { listOrcadMigrationSourceCutovers } from './orcad-migration-cutover-journal' -import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' +import type { SshTarget } from '../../../shared/ssh-types' +import { closeTestStores, createSqliteTestStore } from '../../persistence/persistence-test-harness' +import { Store } from '../../persistence/loading-store/store' +import { listOrcadMigrationSourceCutovers } from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' + import { createSshRelayMigrationSource } from './orcad-migration-ssh-relay-source' -import { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' +import { SshTargetOrcadClaims } from '../targets/ssh-target-orcad-claims' const TARGET: SshTarget = { id: 'ssh-prod', @@ -52,23 +52,6 @@ function setup() { } describe('relay-era SSH migration source', () => { - it('is the SSH kind, keyed by its target id', () => { - expect(setup().source).toMatchObject({ kind: 'ssh-relay', journalKey: TARGET.id }) - }) - - it('exports exactly what the pre-abstraction export produced', () => { - const { store, source } = setup() - const options = { - migrationId: 'migration-1', - now: () => new Date('2026-10-01T00:00:00.000Z'), - destinationEnvironmentId: 'env-1' - } - expect(source.exportManifest(options)).toEqual( - createOrcadMigrationManifest(store, TARGET, options) - ) - expect(source.collectCatalog().repositories.map((repo) => repo.id)).toEqual(['repo-1']) - }) - it('never proves exit without a host-wide census', async () => { await expect(setup().source.assessTerminals()).resolves.toMatchObject({ verdict: 'unverifiable' diff --git a/src/main/ssh/orcad-migration-ssh-relay-source.ts b/src/main/ssh/migration-source/orcad-migration-ssh-relay-source.ts similarity index 74% rename from src/main/ssh/orcad-migration-ssh-relay-source.ts rename to src/main/ssh/migration-source/orcad-migration-ssh-relay-source.ts index aee34b164c2..5b2c596323e 100644 --- a/src/main/ssh/orcad-migration-ssh-relay-source.ts +++ b/src/main/ssh/migration-source/orcad-migration-ssh-relay-source.ts @@ -1,13 +1,13 @@ -import { ORCAD_MIGRATION_SSH_RELAY_SOURCE_KIND } from '../../shared/orcad-migration/orcad-migration-source-kind' -import type { SshTarget } from '../../shared/ssh-types' -import { collectOrcadMigrationSourceCatalog } from '../persistence/migrating-orcad-catalog/orcad-source-catalog' -import type { Store } from '../persistence/loading-store/store' -import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' -import { IDENTITY_ORCAD_MIGRATION_PATH_REWRITER } from './orcad-migration-path-rewrite' +import { ORCAD_MIGRATION_SSH_RELAY_SOURCE_KIND } from '../../../shared/orcad-migration/orcad-migration-source-kind' +import type { SshTarget } from '../../../shared/ssh-types' +import { collectOrcadMigrationSourceCatalog } from '../../persistence/migrating-orcad-catalog/orcad-source-catalog' +import type { Store } from '../../persistence/loading-store/store' +import { createOrcadMigrationManifest } from '../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' +import { IDENTITY_ORCAD_MIGRATION_PATH_REWRITER } from '../../persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' import type { OrcadMigrationSource, OrcadMigrationSourceCutoverPort -} from './orcad-migration-source' +} from '../../managed-server/migration/cutover/orcad-migration-source' import { assertOrcadMigrationSourceUnchanged } from './orcad-migration-source-assertions' import { fenceOrcadMigrationSource, @@ -19,8 +19,8 @@ import { retireProvenExitedLeases, type CensusHostRelayTerminals } from './orcad-migration-terminal-gate' -import type { SshTargetOrcadClaims } from './targets/ssh-target-orcad-claims' -import type { OrcadMigrationPreflightStore } from './targets/ssh-target-orcad-preflight' +import type { SshTargetOrcadClaims } from '../targets/ssh-target-orcad-claims' +import type { OrcadMigrationPreflightStore } from '../targets/ssh-target-orcad-preflight' import type { OrcadMigrationPaneLeasePredicate } from './orcad-migration-bridged-panes' type SshRelayCutoverDeps = { diff --git a/src/main/ssh/orcad-migration-terminal-gate.test.ts b/src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts similarity index 84% rename from src/main/ssh/orcad-migration-terminal-gate.test.ts rename to src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts index 1c2653b5ef8..28a9de838b7 100644 --- a/src/main/ssh/orcad-migration-terminal-gate.test.ts +++ b/src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts @@ -1,9 +1,8 @@ -import { describe, expect, it, vi } from 'vitest' -import type { SshRemotePtyLease } from '../../shared/ssh-types' +import { describe, expect, it } from 'vitest' +import type { SshRemotePtyLease } from '../../../shared/ssh-types' import { assessOrcadMigrationTerminals, - confirmOrcadMigrationTerminalsUnderFence, - retireProvenExitedLeases + confirmOrcadMigrationTerminalsUnderFence } from './orcad-migration-terminal-gate' type LeaseRow = Pick @@ -88,11 +87,4 @@ describe('a bridged conversion under its fence', () => { ptyIds: ['new'] }) }) - - it('retires nothing it bridged', () => { - const leases = store([{ ptyId: 'att', state: 'attached' }]) - const markSshRemotePtyLease = vi.fn() - retireProvenExitedLeases({ ...leases, markSshRemotePtyLease }, 'ssh-1', bridged) - expect(markSshRemotePtyLease).not.toHaveBeenCalled() - }) }) diff --git a/src/main/ssh/orcad-migration-terminal-gate.ts b/src/main/ssh/migration-source/orcad-migration-terminal-gate.ts similarity index 96% rename from src/main/ssh/orcad-migration-terminal-gate.ts rename to src/main/ssh/migration-source/orcad-migration-terminal-gate.ts index f42885779fd..807e96ca3f4 100644 --- a/src/main/ssh/orcad-migration-terminal-gate.ts +++ b/src/main/ssh/migration-source/orcad-migration-terminal-gate.ts @@ -1,7 +1,7 @@ /** Relay PTYs cannot move to orcad: prove host-wide exit or retain possible survivors in the legacy bridge. Lost contact and unaccounted leases never prove exit. */ -import { isLiveSshPtyLease, type SshRemotePtyLease } from '../../shared/ssh-types' -import type { Store } from '../persistence/loading-store/store' -import { PtyExitProof } from '../pty/process-retirement/pty-exit-proof' +import { isLiveSshPtyLease, type SshRemotePtyLease } from '../../../shared/ssh-types' +import type { Store } from '../../persistence/loading-store/store' +import { PtyExitProof } from '../../pty/process-retirement/pty-exit-proof' export type OrcadMigrationTerminalVerdict = | { verdict: 'exited'; provenPtyIds: string[] } diff --git a/src/main/ssh/orcad-migration-catalog-client.ts b/src/main/ssh/orcad-migration-catalog-client.ts deleted file mode 100644 index 846113879ec..00000000000 --- a/src/main/ssh/orcad-migration-catalog-client.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { hasModernAutomationLaunchSetup } from '../../shared/automations/launch/automation-launch-setup' -import { automationCanonicalLaunchSetup } from '../../shared/automations/launch/automation-canonical-launch-setup' -import { - AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY, - AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY -} from '../../shared/automations/automation-runtime-capabilities' -import { z } from 'zod' -import { pairedRuntimeConnectionFromOffer } from '../../shared/remote-runtime/pairing/paired-runtime-connection' -import { - parseOrcadMigrationCatalogAbortResult, - parseOrcadMigrationCatalogState -} from '../../shared/orcad-migration/orcad-migration-catalog-state' -import type { - OrcadMigrationCatalogAbortResult, - OrcadMigrationCatalogState, - OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import { - parseOrcadMigrationSnapshotChunkResult, - type OrcadMigrationSnapshotChunkRequest, - type OrcadMigrationSnapshotChunkResult -} from '../../shared/orcad-migration/orcad-migration-scrollback' -import { - findUnsupportedMigrationBlobKind, - orcadMigrationBlobKindUnsupportedBlocker, - parseOrcadMigrationBlobChunkResult, - type OrcadMigrationBlobChunkRequest, - type OrcadMigrationBlobChunkResult, - type OrcadMigrationBlobDescriptor -} from '../../shared/orcad-migration/orcad-migration-blob-transfer' -import { orcadMigrationManifestBlobs } from '../../shared/orcad-migration/orcad-migration-automation-run-history' -import { parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' -import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../shared/electron-remote-runtime-client-capabilities' -import { ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY } from '../../shared/orcad-runtime-capabilities' -import { sendRemoteRuntimeRequestWithStatusPreflight } from '../../shared/remote-runtime/remote-runtime-client' -import { assertOrcadMigrationRequestFits } from './orcad-migration-manifest-export' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import { hasExtraAgentArgs } from '../../shared/agent-launch/startup/automation-extra-agent-args' -import { requiredOrcadMigrationSourceCapability } from '../../shared/orcad-migration/orcad-migration-source-kind' -import type { OrcadServerRepository } from './orcad-migration-repository-link' - -type OrcadCatalogMigrationOperation = 'abort' | 'commit' | 'stage' | 'state' - -/** Missing capability/method is definite refusal; other failures require catalog re-read because a lost reply may hide staged state. */ -export const ORCAD_MIGRATION_DESTINATION_UNSUPPORTED = 'orcad_migration_destination_unsupported' -/** Refuse older destinations that would silently strip extra agent arguments. */ -export const ORCAD_MIGRATION_DESTINATION_EXTRA_AGENT_ARGS_UNSUPPORTED = - 'orcad_migration_destination_extra_agent_args_unsupported:Update Orca on this host to use extra arguments.' -/** Unsupported source kinds are refused before any staging request. */ -export const ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED = - 'orcad_migration_destination_source_kind_unsupported:Update Orca on this host to move this project to it.' - -export type CatalogRequestOptions = { - signal?: AbortSignal - timeoutMs?: number - expectedRuntimeId?: string -} - -const METHOD_BY_OPERATION: Record = { - abort: 'orcad.migration.abortCatalog', - commit: 'orcad.migration.commitCatalog', - stage: 'orcad.migration.stageCatalog', - state: 'orcad.migration.catalogState' -} - -export function stageRemoteOrcadMigrationCatalog( - pairingCode: string, - manifest: OrcadMigrationManifest, - options: CatalogRequestOptions = {} -): Promise { - return requestCatalogState(pairingCode, 'stage', manifest, options) -} - -/** Expected blobs make the destination refuse incomplete commits. */ -export async function commitRemoteOrcadMigrationCatalog( - pairingCode: string, - manifest: OrcadMigrationManifest, - options: CatalogRequestOptions & { - expectedBlobs?: readonly OrcadMigrationBlobDescriptor[] - } = {} -): Promise { - const result = await request(pairingCode, 'commit', manifest, options, options.expectedBlobs) - return parseOrcadMigrationCatalogState(result, manifest) -} - -export function readRemoteOrcadMigrationCatalogState( - pairingCode: string, - manifest: OrcadMigrationManifest, - options: CatalogRequestOptions = {} -): Promise { - return requestCatalogState(pairingCode, 'state', manifest, options) -} - -export async function abortRemoteOrcadMigrationCatalog( - pairingCode: string, - manifest: OrcadMigrationManifest, - options: CatalogRequestOptions = {} -): Promise { - const result = await request(pairingCode, 'abort', manifest, options) - const parsed = parseOrcadMigrationCatalogAbortResult(result, manifest) - // Older already-absent replies prove no durability, unlike real aborts. - if (parsed.state === 'absent' && !parsed.aborted && parsed.durableAbsent !== true) { - throw new Error('orcad_migration_abort_durability_unverifiable:destination_update_required') - } - return parsed -} - -export async function stageRemoteOrcadMigrationSnapshotChunk( - pairingCode: string, - request: OrcadMigrationSnapshotChunkRequest, - options: CatalogRequestOptions = {} -): Promise { - const pairing = parsePairingCode(pairingCode) - if (!pairing) { - throw new Error('orcad_migration_pairing_code_invalid') - } - const response = await sendSupportedMigrationRequest( - pairing, - 'orcad.migration.stageSnapshotChunk', - request, - options - ) - if (!response.ok) { - throw new Error(`orcad_migration_snapshot_failed:${response.error.message}`) - } - return parseOrcadMigrationSnapshotChunkResult(response.result, request) -} - -export async function stageRemoteOrcadMigrationBlobChunk( - pairingCode: string, - request: OrcadMigrationBlobChunkRequest, - options: CatalogRequestOptions = {} -): Promise { - const pairing = parsePairingCode(pairingCode) - if (!pairing) { - throw new Error('orcad_migration_pairing_code_invalid') - } - const response = await sendSupportedMigrationRequest( - pairing, - 'orcad.migration.stageBlobChunk', - request, - options, - false, - null, - // Recheck every request so a downgraded destination cannot stage an unsupported blob kind. - (capabilities) => { - const unsupported = findUnsupportedMigrationBlobKind([request.blob], capabilities) - if (unsupported) { - throw new Error(orcadMigrationBlobKindUnsupportedBlocker(unsupported)) - } - } - ) - if (!response.ok) { - throw new Error(`orcad_migration_blob_failed:${response.error.message}`) - } - return parseOrcadMigrationBlobChunkResult(response.result, request) -} - -export async function listServerRows( - pairingCode: string, - method: string, - rows: string, - options: CatalogRequestOptions -): Promise { - const pairing = parsePairingCode(pairingCode) - if (!pairing) { - throw new Error('orcad_migration_pairing_code_invalid') - } - const response = await sendSupportedMigrationRequest(pairing, method, undefined, options) - if (!response.ok) { - throw new Error(`orcad_migration_${rows}_failed:${response.error.message}`) - } - return response.result -} - -// repo.list returns full stored rows; omitted host fields identify server-local repos. -const ServerRepositoriesSchema = z.object({ - repos: z.array( - z.object({ - id: z.string().min(1), - path: z.string().min(1), - connectionId: z.string().nullish(), - executionHostId: z.string().nullish(), - projectGroupId: z.string().nullish() - }) - ) -}) - -export async function listRemoteOrcadRepositories( - pairingCode: string, - options: CatalogRequestOptions = {} -): Promise { - const result = await listServerRows(pairingCode, 'repo.list', 'repositories', options) - return ServerRepositoriesSchema.parse(result).repos.map( - ({ id, path, connectionId, executionHostId, projectGroupId }) => ({ - id, - path, - ...(connectionId != null ? { connectionId } : {}), - ...(executionHostId != null ? { executionHostId } : {}), - ...(projectGroupId != null ? { projectGroupId } : {}) - }) - ) -} - -async function requestCatalogState( - pairingCode: string, - operation: Exclude, - manifest: OrcadMigrationManifest, - options: CatalogRequestOptions -): Promise { - const result = await request(pairingCode, operation, manifest, options) - return parseOrcadMigrationCatalogState(result, manifest) -} - -async function request( - pairingCode: string, - operation: OrcadCatalogMigrationOperation, - manifest: OrcadMigrationManifest, - options: CatalogRequestOptions, - expectedBlobs: readonly OrcadMigrationBlobDescriptor[] = [] -): Promise { - const pairing = parsePairingCode(pairingCode) - if (!pairing) { - throw new Error('orcad_migration_pairing_code_invalid') - } - // Preserve exact { manifest } wire shape for blob-free and SSH moves. - const params = expectedBlobs.length > 0 ? { manifest, expectedBlobs } : { manifest } - // Validation-size limits can exceed sealed-frame capacity; reject before the host closes the socket. - assertOrcadMigrationRequestFits(params) - const imports = operation === 'stage' || operation === 'commit' - const carriesExtraAgentArgs = - imports && - (manifest.payload.dormantState?.automations ?? []).some((automation) => - hasExtraAgentArgs(automation.extraAgentArgs) - ) - // An older host would drop the blob a manifest names and import without its rows. - const requiredBlobs = imports - ? [...expectedBlobs, ...orcadMigrationManifestBlobs(manifest)] - : expectedBlobs - const response = await sendSupportedMigrationRequest( - pairing, - METHOD_BY_OPERATION[operation], - params, - options, - carriesExtraAgentArgs, - // Recheck source capabilities on every operation; older hosts may misparse non-SSH sources. - requiredOrcadMigrationSourceCapability(manifest.source), - // Hosts without blob capability would strip expectedBlobs and commit unchecked. - (capabilities) => { - if ( - imports && - (manifest.payload.dormantState?.automations ?? []).some((automation) => - hasModernAutomationLaunchSetup(automationCanonicalLaunchSetup(automation)) - ) && - !capabilities.includes(AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY) - ) { - throw new Error( - 'Update Orca on the destination host to keep automation agent launch settings.' - ) - } - const unsupported = findUnsupportedMigrationBlobKind(requiredBlobs, capabilities) - if (unsupported) { - throw new Error(orcadMigrationBlobKindUnsupportedBlocker(unsupported)) - } - } - ) - if (!response.ok) { - throw new Error(`orcad_migration_${operation}_failed:${response.error.message}`) - } - return response.result -} - -export async function sendSupportedMigrationRequest( - pairing: NonNullable>, - method: string, - params: unknown, - options: CatalogRequestOptions, - requiresExtraAgentArgs = false, - requiredSourceCapability: string | null = null, - assertCapabilities: (capabilities: readonly string[]) => void = () => {} -): Promise> { - const response = await sendRemoteRuntimeRequestWithStatusPreflight( - pairedRuntimeConnectionFromOffer(pairing), - method, - params, - options.timeoutMs ?? 15_000, - (status) => { - if (!status.ok) { - throw new Error(`orcad_migration_status_failed:${status.error.message}`) - } - if ( - options.expectedRuntimeId !== undefined && - status._meta?.runtimeId !== options.expectedRuntimeId - ) { - throw new Error('orcad_migration_destination_runtime_mismatch') - } - if (!status.result.capabilities?.includes(ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY)) { - throw new Error(ORCAD_MIGRATION_DESTINATION_UNSUPPORTED) - } - if ( - requiresExtraAgentArgs && - !status.result.capabilities?.includes(AUTOMATION_EXTRA_AGENT_ARGS_RUNTIME_CAPABILITY) - ) { - throw new Error(ORCAD_MIGRATION_DESTINATION_EXTRA_AGENT_ARGS_UNSUPPORTED) - } - if ( - requiredSourceCapability !== null && - !status.result.capabilities?.includes(requiredSourceCapability) - ) { - throw new Error(ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED) - } - assertCapabilities(status.result.capabilities ?? []) - }, - undefined, - ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, - options.signal - ) - if (!response.ok && response.error.code === 'method_not_found') { - throw new Error(ORCAD_MIGRATION_DESTINATION_UNSUPPORTED) - } - if ( - options.expectedRuntimeId !== undefined && - response._meta?.runtimeId !== options.expectedRuntimeId - ) { - throw new Error('orcad_migration_destination_runtime_mismatch') - } - return response -} diff --git a/src/main/ssh/orcad-migration-manifest-export.test.ts b/src/main/ssh/orcad-migration-manifest-export.test.ts deleted file mode 100644 index 3eb4dd17525..00000000000 --- a/src/main/ssh/orcad-migration-manifest-export.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../shared/project-group-types' -import type { Repo } from '../../shared/repo-types' -import type { SshTarget } from '../../shared/ssh-types' -import { computeOrcadMigrationManifestSha256 } from '../orcad/orcad-migration-manifest-digest' -import { emptyDormantPayload } from '../persistence/migrating-orcad-catalog/orcad-source-dormant-state' -import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' - -const TARGET: SshTarget = { - id: 'ssh-prod', - label: 'Production', - host: 'prod.example.com', - port: 22, - username: 'deploy', - generation: 7 -} - -function repo(id: string, connectionId: string, projectGroupId?: string): Repo { - return { - id, - path: `/srv/${id}`, - displayName: id, - badgeColor: '#737373', - addedAt: 1, - kind: 'git', - connectionId, - ...(projectGroupId ? { projectGroupId } : {}) - } -} - -function group( - id: string, - connectionId: string | null, - parentGroupId: string | null = null -): ProjectGroup { - return { - id, - name: id, - parentPath: `/srv/${id}`, - connectionId, - parentGroupId, - createdFrom: 'manual', - tabOrder: 1, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1 - } -} - -function folder(id: string, projectGroupId: string, connectionId?: string): FolderWorkspace { - return { - id, - projectGroupId, - name: id, - folderPath: `/srv/${id}`, - ...(connectionId ? { connectionId } : {}), - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 1, - lastActivityAt: 0, - createdAt: 1, - updatedAt: 1 - } -} - -describe('orcad migration manifest export', () => { - it('exports only the target catalog plus referenced group ancestry', () => { - const groups = [ - group('parent', null), - group('repo-group', 'ssh-prod', 'parent'), - group('folder-group', 'ssh-prod'), - group('other-group', 'ssh-other') - ] - const manifest = createOrcadMigrationManifest( - { - collectOrcadMigrationSourceDormantState: emptyDormantPayload, - getRepos: () => [ - repo('repo-prod', 'ssh-prod', 'repo-group'), - repo('repo-other', 'ssh-other') - ], - getProjectGroups: () => groups, - getFolderWorkspaces: () => [ - folder('folder-inherited', 'folder-group'), - folder('folder-explicit', 'folder-group', 'ssh-prod'), - folder('folder-other', 'other-group', 'ssh-other') - ] - }, - TARGET, - { migrationId: 'migration-1', now: () => new Date('2026-08-30T12:00:00.000Z') } - ) - - expect(manifest.payload.repositories.map((entry) => entry.id)).toEqual(['repo-prod']) - expect(manifest.payload.projectGroups.map((entry) => entry.id)).toEqual([ - 'parent', - 'repo-group', - 'folder-group' - ]) - expect(manifest.payload.folderWorkspaces.map((entry) => entry.id)).toEqual([ - 'folder-inherited', - 'folder-explicit' - ]) - expect(manifest.source).toEqual({ - sshTargetId: 'ssh-prod', - sshTargetGeneration: 7, - targetLabel: 'Production' - }) - const { manifestSha256, ...unsigned } = manifest - expect(manifestSha256).toBe(computeOrcadMigrationManifestSha256(unsigned)) - }) -}) diff --git a/src/main/ssh/orcad-migration-snapshot-resume.test.ts b/src/main/ssh/orcad-migration-snapshot-resume.test.ts deleted file mode 100644 index 0736977737f..00000000000 --- a/src/main/ssh/orcad-migration-snapshot-resume.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { getDefaultWorkspaceSession } from '../../shared/constants' -import { toSshExecutionHostId } from '../../shared/execution-host' -import type { - OrcadMigrationCatalogState, - OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' -import type { OrcadMigrationSnapshotChunkRequest } from '../../shared/orcad-migration/orcad-migration-scrollback' -import type { SshTarget } from '../../shared/ssh-types' -import { closeTestStores, createSqliteTestStore } from '../persistence/persistence-test-harness' -import { Store } from '../persistence/loading-store/store' -import { createOrcadMigrationManifest } from './orcad-migration-manifest-export' -import { transferOrcadMigrationSnapshots } from './orcad-migration-snapshot-coordinator' - -const TARGET: SshTarget = { - id: 'ssh-prod', - label: 'Production', - host: 'prod.example.com', - port: 22, - username: 'deploy', - generation: 1 -} -const WORKTREE_ID = 'repo-1::/srv/app' -const OUTPUT = 'dormant output\r\n' - -const directories: string[] = [] -afterEach(async () => { - await closeTestStores() - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -function openStore(dataFile: string): Store { - return createSqliteTestStore(Store, { dataFile }) -} - -/** Model relay ssh: partitions that retain dormant-tab scrollback inline. */ -function relayProfile(): { store: Store; dataFile: string } { - const directory = mkdtempSync(join(tmpdir(), 'orcad-snapshot-resume-')) - directories.push(directory) - const dataFile = join(directory, 'orca-data.json') - const store = openStore(dataFile) - store.addSshTarget(TARGET) - store.addRepo({ - id: 'repo-1', - path: '/srv/app', - displayName: 'App', - badgeColor: '#737373', - addedAt: 1, - kind: 'git', - connectionId: TARGET.id - }) - store.setWorkspaceSession( - { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: [ - { - id: 'tab-1', - ptyId: null, - worktreeId: WORKTREE_ID, - title: 'Shell', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { type: 'leaf', leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId: null, - buffersByLeafId: { 'leaf-1': OUTPUT } - } - } - }, - toSshExecutionHostId(TARGET.id) - ) - return { store, dataFile } -} - -function destination(manifest: OrcadMigrationManifest, failFirst: boolean) { - const [snapshot] = manifest.payload.dormantState?.terminalScrollbackSnapshots ?? [] - let received = 0 - let fail = failFirst - const state = (): Extract => ({ - state: 'staged', - migrationId: manifest.migrationId, - manifestSha256: manifest.manifestSha256, - stagedAt: '2026-10-05T00:00:00.000Z', - snapshotUploads: [{ ...snapshot!, receivedBytes: received }] - }) - return { - readState: async () => state(), - stageChunk: async (request: OrcadMigrationSnapshotChunkRequest) => { - if (fail) { - fail = false - throw new Error('transport lost') - } - received = request.offset + Buffer.from(request.bytesBase64, 'base64').length - return { - migrationId: request.migrationId, - manifestSha256: request.manifestSha256, - ref: request.ref, - acknowledgedOffset: received - } - }, - received: () => received - } -} - -async function transfer( - store: Store, - manifest: OrcadMigrationManifest, - remote: ReturnType -): Promise { - await transferOrcadMigrationSnapshots({ - source: store, - manifest, - state: await remote.readState(), - destination: remote - }) -} - -describe('resuming a scrollback upload the journal still holds', () => { - it('recovers after a restart, from the journal alone', async () => { - const { store, dataFile } = relayProfile() - const manifest = createOrcadMigrationManifest(store, TARGET) - store.syncOrcadMigrationScrollbackRetention([manifest]) - store.setWorkspaceSession(getDefaultWorkspaceSession(), toSshExecutionHostId(TARGET.id)) - await store.flushPendingOrThrowAsync() - await closeTestStores() - - const restarted = openStore(dataFile) - restarted.syncOrcadMigrationScrollbackRetention([manifest]) - const remote = destination(manifest, false) - await transfer(restarted, manifest, remote) - - expect(remote.received()).toBe(Buffer.byteLength(OUTPUT)) - }) -}) diff --git a/src/main/ssh/orcad-migration-terminal-gate-host-wide.test.ts b/src/main/ssh/orcad-migration-terminal-gate-host-wide.test.ts deleted file mode 100644 index 0f4d7a2f645..00000000000 --- a/src/main/ssh/orcad-migration-terminal-gate-host-wide.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -// Other desktops' live relays never prove exit. COMPAT(legacy-relay-bridge): convert with bridged verdict while leaving their relays untouched. -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 { relaySocketNameForInstanceId } from './legacy-relay/ssh-relay-instance-id' -import { windowsRelayPipePathsForSocketName } from './legacy-relay/ssh-relay-endpoints' -import { getRemoteHostPlatform, joinRemotePath } from './ssh-remote-platform' - -const { - execCommand, - probeRelayEndpointIncumbent, - countRelayEndpointPtys, - countRelayPtysOverBridge -} = vi.hoisted(() => ({ - execCommand: vi.fn(), - probeRelayEndpointIncumbent: vi.fn(), - countRelayEndpointPtys: vi.fn(), - countRelayPtysOverBridge: vi.fn() -})) - -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand -})) -vi.mock('./legacy-relay/ssh-relay-endpoint-incumbent', async (importOriginal) => ({ - ...(await importOriginal>()), - probeRelayEndpointIncumbent -})) -vi.mock('./legacy-relay/ssh-relay-endpoint-pty-count', () => ({ - countRelayEndpointPtys, - countRelayPtysOverBridge -})) -vi.mock('./legacy-relay/ssh-relay-endpoint-runtime', () => ({ - readRelayDaemonRuntimes: async () => new Map() -})) -vi.mock('./ssh-remote-commands', async (importOriginal) => ({ - ...(await importOriginal>()), - listRemoteInstallBaseDirsCommand: () => 'LIST' -})) -vi.mock('./legacy-relay/ssh-host-relay-windows-inventory', async (importOriginal) => ({ - ...(await importOriginal>()), - windowsRelayInventoryCommand: () => 'INVENTORY', - windowsPipeAccessCommand: () => 'ACCESS' -})) -vi.mock('./legacy-relay/ssh-relay-windows-launch-command', () => ({ - windowsRelayConnectCommand: (_h: unknown, _n: string, _d: string, pipe: string) => - `BRIDGE ${pipe}` -})) - -import { assessOrcadMigrationTerminals } from './orcad-migration-terminal-gate' -import { censusHostRelayEndpoints } from './legacy-relay/ssh-host-relay-endpoint-census' -import { censusWindowsHostRelays } from './legacy-relay/ssh-host-relay-windows-census' -import { hostTerminalProofFromCensus } from './legacy-relay/ssh-host-relay-terminals-on-connect' - -const conn: SshConnection = Object.create(null) -const noLeases = { getSshRemotePtyLeases: () => [] } - -describe('a desktop converting while another desktop runs a shell on the account', () => { - beforeEach(() => { - execCommand.mockReset() - probeRelayEndpointIncumbent.mockReset() - countRelayEndpointPtys.mockReset() - countRelayPtysOverBridge.mockReset() - }) - - it('never reads exited on a POSIX host where only desktop B’s socket runs a shell', async () => { - const host = getRemoteHostPlatform('linux-x64') - const dir = '/home/dev/.orca-remote/relay-0.1.0+aaaaaaaaaaaa' - const aSock = `${dir}/${relaySocketNameForInstanceId('desktop-a')}` - const bSock = `${dir}/${relaySocketNameForInstanceId('desktop-b')}` - execCommand.mockResolvedValue(`${aSock}\n${bSock}\n`) - probeRelayEndpointIncumbent.mockResolvedValue({ verdict: 'live', holders: [] }) - countRelayEndpointPtys.mockImplementation(async (_c: unknown, _n: string, endpoint: string) => - endpoint === bSock ? 1 : 0 - ) - const census = async () => - hostTerminalProofFromCensus( - await censusHostRelayEndpoints(conn, { - host, - remoteHome: '/home/dev', - fallbackNodePath: async () => '/usr/bin/node' - }) - ) - - await expect(assessOrcadMigrationTerminals(noLeases, 'desktop-a', census)).resolves.toEqual({ - verdict: 'bridged', - relayVerdict: 'live', - bridgedPtyIds: [], - hostTerminals: 1 - }) - - countRelayEndpointPtys.mockResolvedValue(0) - await expect(assessOrcadMigrationTerminals(noLeases, 'desktop-a', census)).resolves.toEqual({ - verdict: 'exited', - provenPtyIds: [] - }) - }) - - it('never reads exited on a Windows host where only desktop B’s pipe runs a shell', async () => { - const host = getRemoteHostPlatform('win32-x64') - const version = 'relay-0.1.0+aaaaaaaaaaaa' - const dir = joinRemotePath(host, 'C:\\Users\\dev', '.orca-remote', version) - const sockA = relaySocketNameForInstanceId('desktop-a') - const sockB = relaySocketNameForInstanceId('desktop-b') - const [aPipe] = windowsRelayPipePathsForSocketName(host, dir, sockA) - const [bPipe] = windowsRelayPipePathsForSocketName(host, dir, sockB) - const bare = (pipe: string): string => pipe.slice('\\\\.\\pipe\\'.length) - execCommand.mockImplementation(async (_c: unknown, command: string) => - command === 'LIST' - ? `${version}\r\n` - : JSON.stringify({ - pipes: [bare(aPipe), bare(bPipe)], - dirs: { - [version]: { - credentials: [`${sockA}.credential`, `${sockB}.credential`], - markers: {} - } - } - }) - ) - countRelayPtysOverBridge.mockImplementation(async (_c: unknown, command: string) => - command === `BRIDGE ${bPipe}` ? 1 : 0 - ) - const census = async () => - hostTerminalProofFromCensus( - await censusWindowsHostRelays(conn, { - host, - remoteHome: 'C:\\Users\\dev', - targetId: 'desktop-a', - nodePath: async () => 'C:\\node\\node.exe' - }) - ) - - await expect(assessOrcadMigrationTerminals(noLeases, 'desktop-a', census)).resolves.toEqual({ - verdict: 'bridged', - relayVerdict: 'live', - bridgedPtyIds: [], - hostTerminals: 1 - }) - - countRelayPtysOverBridge.mockResolvedValue(0) - await expect(assessOrcadMigrationTerminals(noLeases, 'desktop-a', census)).resolves.toEqual({ - verdict: 'exited', - provenPtyIds: [] - }) - }) -}) diff --git a/src/main/ssh/orcad-runtime-maintenance.ts b/src/main/ssh/orcad-runtime-maintenance.ts deleted file mode 100644 index f7e52644f76..00000000000 --- a/src/main/ssh/orcad-runtime-maintenance.ts +++ /dev/null @@ -1,319 +0,0 @@ -/** Census through the managed tunnel before lifecycle changes. Unknown counts never mean zero, so live/uncounted hosts defer update (D7). */ -import { getAppEnvironment } from '../../shared/app-environment' -import { assertRuntimeEnvironmentNotReconciling } from '../../shared/remote-runtime/host-catalog/runtime-environment-reconciliation-record' -import { - redactRuntimeEnvironment, - type KnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' -import type { - OrcadManagedDeployResult, - OrcadManagedPastLiveTerminals, - OrcadManagedRecoveryResult, - OrcadManagedRollbackResult -} from '../../shared/orcad-managed-runtime' -import { runTargetLifecycle } from '../ipc/ssh/ssh-target-lifecycle-queue' -import { recoverInterruptedOrcadActivation } from '../managed-server/activation/orcad-activation-recovery' -import { probeActiveOrcadReadiness } from './orcad-active-readiness' -import { materializeOrcadArtifact } from '../orcad/orcad-artifact-materializer' -import { CURRENT_ORCAD_DAEMON_PROTOCOL } from './orcad-daemon-protocol-crossing' -import { rebuildOrcadManagedTunnel } from '../managed-server/lifecycle/orcad-managed-tunnel' -import { wakeAlreadyActiveOrcad } from './orcad-already-active-wake' -import { - clearManagedOrcadUpdateDeferral, - recordManagedOrcadUpdateDeferral -} from '../managed-server/lifecycle/orcad-managed-update-deferrals' -import { - isForceableOrcadDeferral, - managedOrcadInstallDir, - managedOrcadSlot, - probeManagedOrcadReadiness, - requireManagedOrcadEnvironment, - resolveLinkedOrcadContext -} from '../managed-server/lifecycle/orcad-managed-runtime-context' -import type { OrcadRemoteContext } from '../managed-server/install/orcad-remote-context' -import { readRemoteOrcadBuildHash } from '../managed-server/install/orcad-remote-build-hash' -import { deployOrcad, type OrcadDeployOptions } from './orcad-remote-deploy' -import type { OrcadUpdateForce } from './orcad-update-plan' -import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from './orcad-installed-activation' -import { - pruneManagedOrcadVersions, - pruneSupersededOrcadCandidates -} from '../managed-server/lifecycle/orcad-managed-version-gc' -import { clearOrcadUpdateFailedThisLaunch } from '../managed-server/lifecycle/orcad-managed-update-failure-memory' -import { admitOrcadRecordForIntent } from '../managed-server/lifecycle/orcad-managed-update-decision' -import { rollbackOrcad } from '../managed-server/install/orcad-remote-rollback' -import { collectManagedTerminalCensus } from './orcad-terminal-census-client' -import { updateTerminalCounts } from './orcad-fenced-stop' -import { findIncompleteManagedOrcadMigration } from '../managed-server/lifecycle/orcad-managed-migration-status' -import { latestOrcadMigrationInto } from './orcad-migration-rollback-mark' -import { refreshMaintainedOrcadPairing } from './orcad-maintenance-pairing-refresh' - -type LifecycleArgs = { selector: string; signal?: AbortSignal } - -export function withManagedOrcadLifecycle( - userDataPath: string, - selector: string, - run: (managed: ReturnType) => Promise -): Promise { - const { environment, deployment } = requireManagedOrcadEnvironment(userDataPath, selector) - return runTargetLifecycle(deployment.sshTargetId, async () => { - // Re-read in the lifecycle queue because reconciliation/stop may have won first. - const current = requireManagedOrcadEnvironment(userDataPath, environment.id) - assertRuntimeEnvironmentNotReconciling(current.environment) - return run(current) - }) -} - -/** Rebuild forwarding when a launched slot binds a different port. */ -export async function followLaunchedServerPort( - userDataPath: string, - environmentId: string -): Promise { - try { - await rebuildOrcadManagedTunnel(userDataPath, environmentId) - } catch (error) { - // Server already launched; if tunnel rebuild fails, the next connect can forward its bound port. - console.warn('[ssh] Could not forward to the relaunched managed Orca server:', error) - } -} - -export function updateManagedOrcadEnvironment( - userDataPath: string, - args: LifecycleArgs & { force?: boolean; pastLiveTerminals?: OrcadManagedPastLiveTerminals } -): Promise { - const { pastLiveTerminals } = args - // Update anyway keeps Update's version admission even if a caller also passed force. - const intent = args.force && !pastLiveTerminals ? 'force' : 'update' - return withManagedOrcadLifecycle(userDataPath, args.selector, async (managed) => { - const admitIntent = admitOrcadRecordForIntent(intent, getAppEnvironment().getVersion()) - // Checked under the host fence: another desktop may have activated a build since the confirm. - const admitRecord: NonNullable = pastLiveTerminals - ? (record, candidateVersion) => - record.active !== pastLiveTerminals.incumbentVersion - ? "This host's server changed since the update was confirmed. Review it and update again." - : admitIntent(record, candidateVersion) - : admitIntent - const force: OrcadUpdateForce | undefined = pastLiveTerminals ? 'live-terminals' : args.force - const result = await runManagedOrcadUpdate( - userDataPath, - managed, - await resolveLinkedOrcadContext(managed.environment, managed.deployment, args.signal), - { signal: args.signal, force, admitRecord } - ) - // A completed manual update clears automatic failure suppression; deferred attempts do not. - if (result.outcome !== 'deferred') { - clearOrcadUpdateFailedThisLaunch({ kind: 'ssh', id: managed.deployment.sshTargetId }) - } - return result - }) -} - -export async function runManagedOrcadUpdate( - userDataPath: string, - { environment, deployment }: ReturnType, - context: OrcadRemoteContext, - args: { - force?: OrcadUpdateForce - signal?: AbortSignal - localOrcadDir?: string - admitRecord?: OrcadDeployOptions['admitRecord'] - } -): Promise { - const { countFirst, ...recount } = updateTerminalCounts((options) => - collectManagedTerminalCensus( - userDataPath, - environment, - context.activationRecord, - undefined, - options - ) - ) - const census = await countFirst() - const localOrcadDir = - args.localOrcadDir ?? - (await materializeOrcadArtifact(context.serverTarget, { signal: args.signal })) - const slot = managedOrcadSlot(context, deployment.remotePort, args.signal) - const result = await deployOrcad({ - ...slot, - localOrcadDir, - target: context.serverTarget, - census, - ...recount, - censusRecord: context.activationRecord, - force: args.force, - appVersion: getAppEnvironment().getVersion(), - ...(args.admitRecord ? { admitRecord: args.admitRecord } : {}) - }) - if (result.outcome === 'installed-not-activated') { - const deferral = { - outcome: 'deferred' as const, - candidateVersion: result.fullVersion, - code: result.code, - reason: result.reason, - // Force may override policy deferrals, including a newer host build. - forceable: - isForceableOrcadDeferral(result.code) || - result.code === ORCAD_ACTIVATION_POLICY_REFUSED_CODE - } - // Policy refusal is final for this host, not a transient update to retry. - if (result.code !== ORCAD_ACTIVATION_POLICY_REFUSED_CODE) { - recordManagedOrcadUpdateDeferral(environment.id, deferral, context.activationRecord) - } - await pruneSupersededOrcadCandidates(slot, context.serverTarget, result.fullVersion) - return deferral - } - clearManagedOrcadUpdateDeferral(environment.id) - const alreadyActive = result.outcome === 'already-active' - const managed = { environmentId: environment.id, hostLabel: context.target.label } - const started = alreadyActive && (await wakeAlreadyActiveOrcad(slot, managed)) - const readiness = await probeManagedOrcadReadiness( - context, - localOrcadDir, - result.fullVersion, - args.signal - ) - await pruneManagedOrcadVersions({ - slot, - serverTarget: context.serverTarget, - activeVersion: result.fullVersion, - readiness - }) - const updated = refreshMaintainedOrcadPairing(userDataPath, environment.id, readiness) - if (started || result.outcome !== 'already-active') { - await followLaunchedServerPort(userDataPath, environment.id) - } - return { - outcome: result.outcome === 'already-active' ? 'already-current' : 'updated', - environment: redactRuntimeEnvironment(updated), - activeVersion: result.fullVersion - } -} - -export function rollbackManagedOrcadEnvironment( - userDataPath: string, - args: LifecycleArgs -): Promise { - return withManagedOrcadLifecycle( - userDataPath, - args.selector, - async ({ environment, deployment }) => { - const context = await resolveLinkedOrcadContext(environment, deployment, args.signal) - const record = context.activationRecord - const target = record.previous - if (!target) { - return { - outcome: 'refused', - code: 'orcad_rollback_no_target', - reason: 'This server has no previous version to roll back to.' - } - } - const crossing = migrationRollbackRefusal(userDataPath, environment, record.activatedAt) - if (crossing) { - return crossing - } - const slot = managedOrcadSlot(context, deployment.remotePort, args.signal) - const targetDir = managedOrcadInstallDir(context, target) - const targetBuildHash = await readRemoteOrcadBuildHash(slot, targetDir) - const { countFirst, ...recount } = updateTerminalCounts((options) => - collectManagedTerminalCensus(userDataPath, environment, record, undefined, options) - ) - // Recount under lock before rollback stop; this initial census closes no admission. - const census = await countFirst() - // Require idle because this client cannot prove the older build's daemon protocol attaches to live terminals. - if (census.liveSessions !== 0) { - return { - outcome: 'refused', - code: - census.liveSessions === null - ? 'orcad_rollback_census_unavailable' - : 'orcad_rollback_terminals_running', - reason: - census.liveSessions === null - ? 'The server did not answer how many terminals it runs. Retry when it answers.' - : 'Close the terminals running on this server before rolling it back.' - } - } - const result = await rollbackOrcad({ - ...slot, - record, - census, - ...recount, - targetBuildHash, - targetDaemonProtocol: CURRENT_ORCAD_DAEMON_PROTOCOL - }) - if (result.outcome !== 'rolled-back') { - return result - } - const readiness = await probeActiveOrcadReadiness( - { ...slot, remoteInstallDir: targetDir }, - { buildHash: targetBuildHash, fullVersion: result.target } - ) - const updated = refreshMaintainedOrcadPairing(userDataPath, environment.id, readiness) - await followLaunchedServerPort(userDataPath, environment.id) - return { - outcome: 'rolled-back', - environment: redactRuntimeEnvironment(updated), - activeVersion: result.target, - discarded: result.discarded - } - } - ) -} - -export function recoverManagedOrcadEnvironment( - userDataPath: string, - args: LifecycleArgs & { acceptChangedState?: boolean } -): Promise { - return withManagedOrcadLifecycle( - userDataPath, - args.selector, - async ({ environment, deployment }) => { - const context = await resolveLinkedOrcadContext(environment, deployment, args.signal) - const result = await recoverInterruptedOrcadActivation({ - ...managedOrcadSlot(context, deployment.remotePort, args.signal), - acceptChangedState: args.acceptChangedState === true - }) - if (result.outcome !== 'recovered') { - return result - } - const updated = result.readiness - ? refreshMaintainedOrcadPairing(userDataPath, environment.id, result.readiness) - : environment - if (result.activeVersion) { - await followLaunchedServerPort(userDataPath, environment.id) - } - return { - outcome: 'recovered', - resolution: result.resolution, - activeVersion: result.activeVersion, - environment: redactRuntimeEnvironment(updated) - } - } - ) -} - -/** A post-activation migration is absent from the rollback snapshot; restoring it would discard imported state. */ -function migrationRollbackRefusal( - userDataPath: string, - environment: KnownRuntimeEnvironment, - activatedAt: string | null -): OrcadManagedRollbackResult | null { - if (findIncompleteManagedOrcadMigration(userDataPath, environment.id)) { - return { - outcome: 'refused', - code: 'orcad_rollback_migration_in_progress', - reason: 'A migration into this server is still running. Finish it before rolling back.' - } - } - const migratedAt = latestOrcadMigrationInto(userDataPath, environment) - if (migratedAt && (activatedAt === null || Date.parse(activatedAt) < Date.parse(migratedAt))) { - return { - outcome: 'refused', - code: 'orcad_rollback_crosses_migration', - reason: - "The previous version's state predates the projects migrated onto this server; " + - 'rolling back would lose them. Deploy forward instead.' - } - } - return null -} diff --git a/src/main/ssh/orcad-ssh-host-transport.ts b/src/main/ssh/orcad-ssh-host-transport.ts deleted file mode 100644 index 3a340fe2e54..00000000000 --- a/src/main/ssh/orcad-ssh-host-transport.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { OrcadHostTransport } from './orcad-host-transport' -import type { SshConnection } from './connection/ssh-connection' - -/** Return the connection object itself: tunnel ownership, dedupe and caches depend on its identity. */ -export function sshOrcadHostTransport(connection: SshConnection): OrcadHostTransport { - return connection -} diff --git a/src/main/ssh/orcad-update-plan.ts b/src/main/ssh/orcad-update-plan.ts deleted file mode 100644 index 7a03a71d681..00000000000 --- a/src/main/ssh/orcad-update-plan.ts +++ /dev/null @@ -1,260 +0,0 @@ -/** Daemon terminals survive orcad swaps and may retain the outgoing bundle, so keep its directory. Shared state migrates in place without schema versions; safe rollback therefore restores a pre-activation snapshot rather than comparing build versions. */ -import type { OrcadActivationRecord } from '../managed-server/activation/orcad-activation-record' -import type { OrcadTerminalCensus } from '../../shared/orcad-terminal-census' -import { - assessOrcadLiveDaemonCrossing, - describeDaemonProtocols, - type OrcadDaemonProtocolFacts -} from './orcad-daemon-protocol-crossing' - -type OrcadUpdateDecision = - | { action: 'noop'; reason: string } - | { - action: 'proceed' - preservesLiveDaemon: boolean - notes: string[] - } - | { action: 'defer'; code: OrcadUpdateDeferCode; reason: string } - -/** `live-terminals` passes only a counted live-terminal deferral, never an uncounted census. */ -export type OrcadUpdateForce = boolean | 'live-terminals' - -export type OrcadUpdateDeferCode = - | 'orcad_update_terminals_running' - | 'orcad_update_terminal_census_unavailable' - | 'orcad_update_strands_live_terminals' - | 'orcad_update_daemon_protocol_unverifiable' - | 'orcad_update_ends_in_process_terminals' - -/** Defer live-session mixed-build pairs unless the operator chooses force; force cannot authorize an unsupported daemon protocol. */ -export function planOrcadUpdate(input: { - record: OrcadActivationRecord - candidateVersion: string - census: OrcadTerminalCensus - candidateDaemonProtocol: OrcadDaemonProtocolFacts - /** Daemon generations the candidate found alive on the host; consulted only when the census cannot name them. */ - hostDaemonProtocols?: readonly number[] - force?: OrcadUpdateForce -}): OrcadUpdateDecision { - if (input.record.active === input.candidateVersion) { - return { - action: 'noop', - reason: `${input.candidateVersion} is already the active version; nothing to restart.` - } - } - const inProcess = input.census.inProcessSessions ?? 0 - // In-process terminals cannot survive restart; force cannot override this even if daemon census is empty. - if (inProcess > 0) { - return { - action: 'defer', - code: 'orcad_update_ends_in_process_terminals', - reason: - `${inProcess} terminal${inProcess === 1 ? ' runs' : 's run'} inside the orcad process ` + - 'itself because its terminal daemon is degraded. Any restart ends ' + - `${inProcess === 1 ? 'it' : 'them'}, and forcing the update cannot keep ` + - `${inProcess === 1 ? 'it' : 'them'} alive. Close ${inProcess === 1 ? 'it' : 'them'}, ` + - 'then update.' - } - } - const crossing = assessOrcadLiveDaemonCrossing( - input.census, - input.candidateDaemonProtocol, - input.hostDaemonProtocols - ) - // Force can accept mixed builds, never unreachable terminals. - if (crossing.state === 'strands-live-terminals') { - return { - action: 'defer', - code: 'orcad_update_strands_live_terminals', - reason: - `A terminal daemon on this host speaks ${describeDaemonProtocols(crossing.unattachable)}, ` + - `which orcad ${input.candidateVersion} cannot attach to. Restarting now would leave ` + - 'any terminals it runs unreachable. Update when no terminals are running.' - } - } - const { liveSessions } = input.census - if (input.force && crossing.state === 'unverifiable') { - return { - action: 'defer', - code: 'orcad_update_daemon_protocol_unverifiable', - reason: - 'The terminal daemon did not report its protocol, so this update cannot show that ' + - `orcad ${input.candidateVersion} will reach the terminals it is forced past. Retry ` + - 'when the daemon answers.' - } - } - if (liveSessions === null) { - if (input.force !== true) { - return { - action: 'defer', - code: 'orcad_update_terminal_census_unavailable', - reason: - 'The terminal daemon did not answer a session count, so this update cannot tell ' + - 'whether work is running on the host. Retry, or force the update knowing terminals ' + - 'may be mid-flight.' - } - } - return { - action: 'proceed', - // Unknown census must preserve possible live sessions; never assume the daemon replaceable. - preservesLiveDaemon: true, - notes: [ - 'Forced with an unverifiable session count. Planning as if terminals are live: the ' + - 'daemon will be preserved across the restart, and the outgoing version directory ' + - 'stays pinned against GC.' - ] - } - } - if (liveSessions > 0 && !input.force) { - return { - action: 'defer', - code: 'orcad_update_terminals_running', - reason: - `${liveSessions} terminal${liveSessions === 1 ? ' is' : 's are'} running on this host. ` + - 'The restart would not kill them — the daemon is preserved — but the host would run ' + - `orcad ${input.candidateVersion} against a daemon forked from ` + - `${input.record.active ?? 'the previous build'} until they all exit. Update when the ` + - 'host is idle, or force it.' - } - } - if (liveSessions > 0) { - return { - action: 'proceed', - preservesLiveDaemon: true, - notes: [ - `Forced with ${liveSessions} live terminal${liveSessions === 1 ? '' : 's'}. They survive ` + - 'the restart on the existing daemon; the outgoing version directory stays pinned ' + - 'against GC because that daemon was forked from it.' - ] - } - } - return { - action: 'proceed', - // At zero sessions daemon-init can safely replace the old daemon. - preservesLiveDaemon: false, - notes: [ - 'No terminals are running, so the daemon is replaced by one forked from the new bundle.' - ] - } -} - -type OrcadRollbackSafety = - | { safety: 'clean'; target: string; notes: string[] } - | { safety: 'lossy'; target: string; discards: string[] } - | { safety: 'unsafe'; code: OrcadRollbackUnsafeCode; reason: string } - -type OrcadRollbackUnsafeCode = - | 'orcad_rollback_no_target' - | 'orcad_rollback_snapshot_missing' - | 'orcad_rollback_orphans_live_terminals' - | 'orcad_rollback_census_unavailable' - | 'orcad_rollback_snapshot_unverifiable' - | 'orcad_rollback_strands_live_terminals' - | 'orcad_rollback_daemon_protocol_unverifiable' - -/** Restoring a pre-activation snapshot discards later state. Post-activation terminal creation makes rollback unsafe: the surviving daemon would own PTYs absent from restored rows. Settings/UI-only changes are merely lossy. */ -export function assessOrcadRollback(input: { - record: OrcadActivationRecord - /** Whether the snapshot is still on the host; `null` means the probe was unverifiable. */ - snapshotPresent: boolean | null - census: OrcadTerminalCensus - /** The rollback target's daemon protocol facts, from the client's copy of its bytes. */ - targetDaemonProtocol: OrcadDaemonProtocolFacts - /** Compare shared-store mtime to activation; unknown writes are treated as present rather than claiming unproven lossless rollback. */ - stateWritesSinceActivation: boolean | null -}): OrcadRollbackSafety { - const target = input.record.previous - if (!target) { - return { - safety: 'unsafe', - code: 'orcad_rollback_no_target', - reason: - 'This host has no previous orcad version recorded, so there is nothing to roll back ' + - 'to. Deploy a known-good build instead.' - } - } - if (input.record.snapshot && input.snapshotPresent === null) { - return { - safety: 'unsafe', - code: 'orcad_rollback_snapshot_unverifiable', - reason: - 'The host did not give a trustworthy answer about the pre-activation snapshot. Retry ' + - 'when the host is reachable; loss of contact is not evidence the snapshot is gone.' - } - } - if (!input.record.snapshot || !input.snapshotPresent) { - return { - safety: 'unsafe', - code: 'orcad_rollback_snapshot_missing', - reason: - `The pre-activation state snapshot for ${input.record.active ?? 'the active version'} ` + - 'is gone, and Orca state carries no schema version that could prove the older build ' + - 'can read what the newer one migrated. Switching the binary back would hand ' + - `${target} a store it may not understand. Deploy forward instead.` - } - } - const { startedSinceActivation } = input.census - if (startedSinceActivation === null) { - return { - safety: 'unsafe', - code: 'orcad_rollback_census_unavailable', - reason: - 'The daemon did not answer how many of its terminals started after this version was ' + - 'activated, so a snapshot restore might orphan running work. Retry when the host is ' + - 'reachable.' - } - } - if (startedSinceActivation > 0) { - return { - safety: 'unsafe', - code: 'orcad_rollback_orphans_live_terminals', - reason: - `${startedSinceActivation} terminal${startedSinceActivation === 1 ? '' : 's'} started ` + - 'after this version was activated. The daemon survives the rollback and would keep ' + - 'owning them, but the restored snapshot predates them, so nothing would be able to ' + - 'reattach. Close them (or let them exit) and roll back then.' - } - } - const crossing = assessOrcadLiveDaemonCrossing(input.census, input.targetDaemonProtocol) - if (crossing.state === 'unverifiable') { - return { - safety: 'unsafe', - code: 'orcad_rollback_daemon_protocol_unverifiable', - reason: - 'The terminal daemon did not report its protocol, so this rollback cannot show that ' + - `${target} would reach the terminals still running. Retry when the daemon answers.` - } - } - if (crossing.state === 'strands-live-terminals') { - return { - safety: 'unsafe', - code: 'orcad_rollback_strands_live_terminals', - reason: - `A terminal daemon on this host speaks ${describeDaemonProtocols(crossing.unattachable)}, ` + - `which ${target} does not list. Rolling back now would leave any terminals it runs ` + - 'unreachable. Roll back when no terminals are running, or deploy forward.' - } - } - if (input.stateWritesSinceActivation === false) { - return { - safety: 'clean', - target, - notes: [ - 'The pre-activation snapshot is intact, no terminals started since activation, and ' + - 'the store has not been written since. Restoring it changes nothing.' - ] - } - } - return { - safety: 'lossy', - target, - discards: [ - input.stateWritesSinceActivation === null - ? 'Any profile, settings and UI change written since activation — the store mtime ' + - 'could not be read, so assume there are some.' - : `Every profile, settings and UI change written since ${ - input.record.activatedAt ?? 'activation' - }, when ${input.record.active ?? 'the active version'} was activated.` - ] - } -} diff --git a/src/main/ssh/pinned-runtime-host-target.test.ts b/src/main/ssh/pinned-runtime-host-target.test.ts deleted file mode 100644 index 8757af18183..00000000000 --- a/src/main/ssh/pinned-runtime-host-target.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { NODE_RUNTIME_ASSETS, NODE_RUNTIME_COMPAT_ASSETS } from '../../shared/node-runtime-pin' -import { - isGlibcBelow, - nodeRuntimeStorePins, - pinnedRuntimeTargetForHost -} from './pinned-runtime-host-target' - -describe('pinned runtime host target', () => { - it('names the runtime a host can run by glibc alone', () => { - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 28 } }) - ).toBe('linux-x64-glibc') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 27 } }) - ).toBe('linux-x64-glibc217') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 17 } }) - ).toBe('linux-x64-glibc217') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 12 } }) - ).toBeNull() - expect( - pinnedRuntimeTargetForHost({ target: 'linux-arm64-glibc', glibc: { major: 2, minor: 17 } }) - ).toBeNull() - expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: null })).toBe( - 'linux-x64-glibc' - ) - expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-musl', glibc: null })).toBe( - 'linux-x64-musl' - ) - }) - - it('keeps the compat runtime pinned in the store beside the default one', () => { - const defaultSha = NODE_RUNTIME_ASSETS['linux-x64-glibc'].executableSha256 - const compatSha = NODE_RUNTIME_COMPAT_ASSETS['linux-x64-glibc217'].executableSha256 - expect(nodeRuntimeStorePins('linux-x64-glibc')).toEqual([defaultSha, compatSha]) - expect(nodeRuntimeStorePins('linux-x64-glibc217')).toEqual([defaultSha, compatSha]) - expect(nodeRuntimeStorePins('linux-arm64-glibc')).toEqual([ - NODE_RUNTIME_ASSETS['linux-arm64-glibc'].executableSha256 - ]) - }) - - it('compares glibc versions by major, then minor', () => { - expect(isGlibcBelow({ major: 2, minor: 27 }, { major: 2, minor: 28 })).toBe(true) - expect(isGlibcBelow({ major: 2, minor: 28 }, { major: 2, minor: 28 })).toBe(false) - expect(isGlibcBelow({ major: 1, minor: 99 }, { major: 2, minor: 0 })).toBe(true) - expect(isGlibcBelow({ major: 3, minor: 0 }, { major: 2, minor: 99 })).toBe(false) - }) -}) diff --git a/src/main/ssh/port-forwarding/ssh-port-forward.test.ts b/src/main/ssh/port-forwarding/ssh-port-forward.test.ts index 314097d90e5..901f1f1d4ca 100644 --- a/src/main/ssh/port-forwarding/ssh-port-forward.test.ts +++ b/src/main/ssh/port-forwarding/ssh-port-forward.test.ts @@ -8,7 +8,7 @@ const { startSystemSshPortForwardProcessMock } = vi.hoisted(() => ({ startSystemSshPortForwardProcessMock: vi.fn() })) -vi.mock('../system-transport/system-ssh-forward-process', async (importOriginal) => { +vi.mock('../system-transport/forwarding/system-ssh-forward-process', async (importOriginal) => { const actual = (await importOriginal()) as Record return { ...actual, diff --git a/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts b/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts new file mode 100644 index 00000000000..3800702be8d --- /dev/null +++ b/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts @@ -0,0 +1,61 @@ +import { createServer, type Server, type Socket } from 'node:net' +import { afterEach, describe, expect, it } from 'vitest' + +import type { ForwardChannelOpenFailure } from './ssh-port-forward-provider' +import { checkForwardChannel } from './ssh-tcp-forwarding-probe' + +import { lastChannelOpenFailure } from './system-ssh-port-forward-provider' + +const servers: Server[] = [] +afterEach(async () => { + await Promise.all( + servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))) + ) +}) + +/** Model ssh -L: socket behavior represents the remote channel-open result. */ +async function forwardAnswering( + onSocket: (socket: Socket, log: (line: string) => void) => void +): Promise[0]> { + let stderr = '' + const server = createServer((socket) => { + socket.on('error', () => {}) + onSocket(socket, (line) => { + stderr += `${line}\n` + }) + }) + servers.push(server) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + const localPort = typeof address === 'object' && address ? address.port : 0 + return { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check reads only localPort. + entry: { localPort } as never, + lastChannelOpenFailure: (): ForwardChannelOpenFailure | null => lastChannelOpenFailure(stderr) + } +} + +describe('forward channel check (system SSH)', () => { + it('reads OpenSSH’s administrative refusal as refused, though its listener accepted', async () => { + const forward = await forwardAnswering((socket, log) => { + log('channel 1: open failed: administratively prohibited: open failed') + socket.destroy() + }) + await expect(checkForwardChannel(forward)).resolves.toBe('refused') + }) + + it('reads a connect failure as allowed: sshd dialled, nothing listened yet', async () => { + const forward = await forwardAnswering((socket, log) => { + log('channel 1: open failed: connect failed: Connection refused') + socket.destroy() + }) + await expect(checkForwardChannel(forward)).resolves.toBe('allowed') + }) + + it('reads reply bytes through the channel as allowed', async () => { + const forward = await forwardAnswering((socket) => { + socket.once('data', () => socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')) + }) + await expect(checkForwardChannel(forward)).resolves.toBe('allowed') + }) +}) diff --git a/src/main/ssh/ssh-tcp-forwarding-probe.ts b/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.ts similarity index 97% rename from src/main/ssh/ssh-tcp-forwarding-probe.ts rename to src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.ts index 490a4c23399..613f0745d2f 100644 --- a/src/main/ssh/ssh-tcp-forwarding-probe.ts +++ b/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.ts @@ -1,8 +1,8 @@ /** Probe forwarding on each managed-tunnel start; sshd policy refusal selects the stdio bridge. */ import { connect, type Socket } from 'node:net' import type { ClientChannel } from 'ssh2' -import type { SshConnection } from './connection/ssh-connection' -import type { StartedPortForward } from './port-forwarding/ssh-port-forward-provider' +import type { SshConnection } from '../connection/ssh-connection' +import type { StartedPortForward } from './ssh-port-forward-provider' export type TcpForwardingVerdict = 'allowed' | 'refused' | 'unverifiable' /** `not-listening`: no dial ever connected, so the forward never got as far as its listener. */ diff --git a/src/main/ssh/port-forwarding/system-ssh-port-forward-provider.ts b/src/main/ssh/port-forwarding/system-ssh-port-forward-provider.ts index 03b02acc621..6e620b30217 100644 --- a/src/main/ssh/port-forwarding/system-ssh-port-forward-provider.ts +++ b/src/main/ssh/port-forwarding/system-ssh-port-forward-provider.ts @@ -3,7 +3,7 @@ import type { SystemSshBuildArgsOptions } from '../system-transport/system-ssh-a import { startSystemSshPortForwardProcess, systemSshForwardError -} from '../system-transport/system-ssh-forward-process' +} from '../system-transport/forwarding/system-ssh-forward-process' import type { ForwardChannelOpenFailure, PortForwardStartOptions, diff --git a/src/main/ssh/protocol/relay-handshake.ts b/src/main/ssh/protocol/relay-handshake.ts new file mode 100644 index 00000000000..26e00699832 --- /dev/null +++ b/src/main/ssh/protocol/relay-handshake.ts @@ -0,0 +1,5 @@ +export const RELAY_VERSION = '0.1.0' + +export const RELAY_SENTINEL = `ORCA-RELAY v${RELAY_VERSION} READY\n` + +export const RELAY_SENTINEL_TIMEOUT_MS = 10_000 diff --git a/src/main/ssh/protocol/remote-frame-protocol.test.ts b/src/main/ssh/protocol/remote-frame-protocol.test.ts new file mode 100644 index 00000000000..f6472700658 --- /dev/null +++ b/src/main/ssh/protocol/remote-frame-protocol.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { HEADER_LENGTH, FrameDecoder } from '../../../shared/relay-frame-decoder' +import type { DecodedFrame } from '../../../shared/relay-frame-decoder-contract' +import { + MessageType, + encodeFrame, + encodeJsonRpcFrame, + parseJsonRpcMessage +} from './remote-frame-protocol' + +describe('frame encoding', () => { + it('rejects messages larger than MAX_MESSAGE_SIZE', () => { + const bigPayload = { + jsonrpc: '2.0' as const, + id: 1, + method: 'x', + params: { data: 'a'.repeat(17 * 1024 * 1024) } + } + expect(() => encodeJsonRpcFrame(bigPayload, 1, 0)).toThrow('Message too large') + }) +}) + +describe('FrameDecoder', () => { + // Freeze clock for framing cases; relay-protocol-backpressure.test.ts separately covers time-sliced drain under CI load. + const frozenClock = { now: () => 0 } + + it('skips oversized frames and calls onError instead of throwing', () => { + const errors: Error[] = [] + const frames: DecodedFrame[] = [] + const decoder = new FrameDecoder( + (f) => frames.push(f), + (err) => errors.push(err), + frozenClock + ) + + const oversizedLength = 17 * 1024 * 1024 + const header = Buffer.alloc(HEADER_LENGTH) + header[0] = MessageType.Regular + header.writeUInt32BE(1, 1) + header.writeUInt32BE(0, 5) + header.writeUInt32BE(oversizedLength, 9) + + const fakePayload = Buffer.alloc(oversizedLength) + const fullFrame = Buffer.concat([header, fakePayload]) + + decoder.feed(fullFrame) + expect(frames).toHaveLength(0) + expect(errors).toHaveLength(1) + expect(errors[0].message).toContain('discarded') + }) + + it('skips an oversized frame fed in odd-sized chunks and resynchronizes', () => { + const errors: Error[] = [] + const frames: DecodedFrame[] = [] + const decoder = new FrameDecoder( + (f) => frames.push(f), + (err) => errors.push(err), + frozenClock + ) + + const oversizedLength = 17 * 1024 * 1024 + const header = Buffer.alloc(HEADER_LENGTH) + header[0] = MessageType.Regular + header.writeUInt32BE(1, 1) + header.writeUInt32BE(0, 5) + header.writeUInt32BE(oversizedLength, 9) + const oversized = Buffer.concat([header, Buffer.alloc(oversizedLength)]) + const valid = encodeFrame(MessageType.Regular, 2, 0, Buffer.from('after')) + const combined = Buffer.concat([oversized, valid]) + + const chunkSize = 1024 * 1024 - 7 + for (let i = 0; i < combined.length; i += chunkSize) { + decoder.feed(combined.subarray(i, i + chunkSize)) + } + + expect(errors).toHaveLength(1) + expect(frames).toHaveLength(1) + expect(frames[0].payload.toString()).toBe('after') + }) +}) + +describe('parseJsonRpcMessage', () => { + it('throws on invalid jsonrpc version', () => { + const payload = Buffer.from(JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'x' })) + expect(() => parseJsonRpcMessage(payload)).toThrow('Invalid JSON-RPC version') + }) +}) diff --git a/src/main/ssh/remote-exec/remote-frame-protocol.ts b/src/main/ssh/protocol/remote-frame-protocol.ts similarity index 66% rename from src/main/ssh/remote-exec/remote-frame-protocol.ts rename to src/main/ssh/protocol/remote-frame-protocol.ts index a01e68f1886..1a55c7323bd 100644 --- a/src/main/ssh/remote-exec/remote-frame-protocol.ts +++ b/src/main/ssh/protocol/remote-frame-protocol.ts @@ -1,8 +1,4 @@ import { HEADER_LENGTH, MAX_MESSAGE_SIZE } from '../../../shared/relay-frame-decoder' -export const RELAY_VERSION = '0.1.0' -export const RELAY_SENTINEL = `ORCA-RELAY v${RELAY_VERSION} READY\n` -export const RELAY_SENTINEL_TIMEOUT_MS = 10_000 -export const RELAY_REMOTE_DIR = '.orca-remote' export const MessageType = { Regular: 1, @@ -10,6 +6,7 @@ export const MessageType = { } as const export const KEEPALIVE_SEND_MS = 5_000 + export const TIMEOUT_MS = 20_000 export type JsonRpcRequest = { @@ -88,42 +85,3 @@ export function parseJsonRpcMessage(payload: Buffer): JsonRpcMessage { } return msg } - -export type RelayPlatform = - | 'linux-x64' - | 'linux-arm64' - | 'darwin-x64' - | 'darwin-arm64' - | 'win32-x64' - | 'win32-arm64' - -export function parseUnameToRelayPlatform(os: string, arch: string): RelayPlatform | null { - const normalizedOs = os.toLowerCase().trim() - const normalizedArch = arch.toLowerCase().trim() - - let relayOs: string | null = null - if (normalizedOs === 'linux') { - relayOs = 'linux' - } else if (normalizedOs === 'darwin') { - relayOs = 'darwin' - } else if ( - normalizedOs === 'windows' || - normalizedOs === 'win32' || - normalizedOs.startsWith('mingw') || - normalizedOs.startsWith('msys') - ) { - relayOs = 'win32' - } - - let relayArch: string | null = null - if (normalizedArch === 'x86_64' || normalizedArch === 'amd64' || normalizedArch === 'x64') { - relayArch = 'x64' - } else if (normalizedArch === 'aarch64' || normalizedArch === 'arm64') { - relayArch = 'arm64' - } - - if (!relayOs || !relayArch) { - return null - } - return `${relayOs}-${relayArch}` as RelayPlatform -} diff --git a/src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts b/src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts new file mode 100644 index 00000000000..2eb9e8cb61d --- /dev/null +++ b/src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts @@ -0,0 +1,115 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import type { MultiplexerTransport } from './ssh-multiplexer-transport-writer' +import { encodeFrame, MessageType } from './remote-frame-protocol' +import { HEADER_LENGTH } from '../../../shared/relay-frame-decoder' + +type MockTransport = MultiplexerTransport & { + data: (chunk: Buffer) => void + written: Buffer[] + pauseReads: ReturnType + resumeReads: ReturnType +} + +function createTransport(): MockTransport { + let onData: (chunk: Buffer) => void = () => {} + const written: Buffer[] = [] + const pauseReads = vi.fn() + const resumeReads = vi.fn() + return { + write: (data) => { + written.push(data) + }, + onData: (callback) => { + onData = callback + }, + onClose: () => {}, + pauseReads, + resumeReads, + data: (chunk) => onData(chunk), + written + } +} + +describe('SshChannelMultiplexer backpressure hardening', () => { + let transport: MockTransport + let mux: SshChannelMultiplexer + + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) + transport = createTransport() + mux = new SshChannelMultiplexer(transport) + }) + + afterEach(() => { + mux.dispose() + vi.restoreAllMocks() + vi.useRealTimers() + }) + + it('prioritizes source ACK and control while preserving FIFO and ordinary progress', async () => { + mux.dispose() + const written: Buffer[] = [] + let drain = (): void => {} + let deliver = (_data: Buffer): void => {} + transport = { + write: (data) => { + written.push(data) + return written.length !== 1 + }, + onDrain: (callback) => { + drain = callback + }, + onData: (callback) => { + deliver = callback + }, + onClose: vi.fn(), + pauseReads: vi.fn<() => void>(), + resumeReads: vi.fn<() => void>(), + data: vi.fn<(chunk: Buffer) => void>(), + written, + close: vi.fn() + } + mux = new SshChannelMultiplexer(transport) + mux.onRequest('client.control', () => ({ accepted: true })) + const controller = new AbortController() + + mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-1' }) + mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-2' }) + mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-3' }) + mux.notify('pty.ackData', { acknowledgements: [] }) + const request = mux.request('fs.scan', {}, { signal: controller.signal }) + controller.abort() + mux.notify('pty.exit', { id: 'pty-1', code: 0 }) + const remoteRequest = Buffer.from( + JSON.stringify({ jsonrpc: '2.0', id: 91, method: 'client.control' }) + ) + deliver(encodeFrame(MessageType.Regular, 1, 0, remoteRequest)) + await Promise.resolve() + await Promise.resolve() + + expect(written).toHaveLength(1) + drain() + const payloads = written.map((frame) => + JSON.parse(frame.subarray(HEADER_LENGTH, HEADER_LENGTH + frame.readUInt32BE(9)).toString()) + ) + expect( + payloads.map((payload) => + payload.method === 'pty.data' + ? `pty.data:${payload.params.data}` + : (payload.method ?? `response:${payload.id}`) + ) + ).toEqual([ + 'pty.data:ordinary-1', + 'pty.ackData', + 'fs.scan', + 'rpc.cancel', + 'pty.exit', + 'pty.data:ordinary-2', + 'response:91', + 'pty.data:ordinary-3' + ]) + await expect(request).rejects.toMatchObject({ name: 'AbortError' }) + }) +}) diff --git a/src/main/ssh/ssh-channel-multiplexer-saturation-wedge.test.ts b/src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts similarity index 90% rename from src/main/ssh/ssh-channel-multiplexer-saturation-wedge.test.ts rename to src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts index 7432d15ebd6..e3d03cb790e 100644 --- a/src/main/ssh/ssh-channel-multiplexer-saturation-wedge.test.ts +++ b/src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts @@ -1,10 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - encodeKeepAliveFrame, - KEEPALIVE_SEND_MS, - TIMEOUT_MS -} from './remote-exec/remote-frame-protocol' -import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer' +import { encodeKeepAliveFrame, KEEPALIVE_SEND_MS, TIMEOUT_MS } from './remote-frame-protocol' +import { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import type { MultiplexerTransport } from './ssh-multiplexer-transport-writer' type WedgedTransport = MultiplexerTransport & { writes: Buffer[]; feed: (chunk: Buffer) => void } diff --git a/src/main/ssh/ssh-channel-multiplexer-settlement.test.ts b/src/main/ssh/protocol/ssh-channel-multiplexer-settlement.test.ts similarity index 95% rename from src/main/ssh/ssh-channel-multiplexer-settlement.test.ts rename to src/main/ssh/protocol/ssh-channel-multiplexer-settlement.test.ts index 7f471f67c3c..30fc5e218ac 100644 --- a/src/main/ssh/ssh-channel-multiplexer-settlement.test.ts +++ b/src/main/ssh/protocol/ssh-channel-multiplexer-settlement.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer' +import { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import type { MultiplexerTransport } from './ssh-multiplexer-transport-writer' function transportHarness(): { transport: MultiplexerTransport diff --git a/src/main/ssh/ssh-channel-multiplexer.test.ts b/src/main/ssh/protocol/ssh-channel-multiplexer.test.ts similarity index 75% rename from src/main/ssh/ssh-channel-multiplexer.test.ts rename to src/main/ssh/protocol/ssh-channel-multiplexer.test.ts index c9e81a619b0..bb9b712e330 100644 --- a/src/main/ssh/ssh-channel-multiplexer.test.ts +++ b/src/main/ssh/protocol/ssh-channel-multiplexer.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' -import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer' -import { encodeFrame, MessageType, encodeKeepAliveFrame } from './remote-exec/remote-frame-protocol' -import { HEADER_LENGTH } from '../../shared/relay-frame-decoder' +import { SshChannelMultiplexer } from './ssh-channel-multiplexer' +import type { MultiplexerTransport } from './ssh-multiplexer-transport-writer' +import { encodeFrame, MessageType, encodeKeepAliveFrame } from './remote-frame-protocol' +import { HEADER_LENGTH } from '../../../shared/relay-frame-decoder' function createMockTransport(): MultiplexerTransport & { dataCallbacks: ((data: Buffer) => void)[] @@ -66,18 +67,6 @@ function makeNotificationFrame( return encodeFrame(MessageType.Regular, seq, 0, payload) } -type MuxInternals = { - notificationHandlers: unknown[] - methodNotificationHandlers: Map> - disposeHandlers: unknown[] - lastReceivedAt: number - unackedTimestamps: Map -} - -function getMuxInternals(instance: SshChannelMultiplexer): MuxInternals { - return instance as unknown as MuxInternals -} - describe('SshChannelMultiplexer', () => { let transport: ReturnType let mux: SshChannelMultiplexer @@ -258,90 +247,9 @@ describe('SshChannelMultiplexer', () => { expect(() => vi.advanceTimersByTime(5_000)).not.toThrow() expect(mux.isDisposed()).toBe(true) }) - - it('survives local saturation while the peer keeps talking, and rebases both clocks on drain', () => { - mux.dispose() - let drain = (): void => {} - let feed: (chunk: Buffer) => void = () => {} - const written: Buffer[] = [] - const saturatedTransport: MultiplexerTransport = { - write: (data) => { - written.push(data) - return false - }, - supportsWriteSettlement: true, - onDrain: (callback) => { - drain = callback - }, - onData: (callback) => { - feed = callback - }, - onClose: vi.fn() - } - mux = new SshChannelMultiplexer(saturatedTransport) - - vi.advanceTimersByTime(5_000) - expect(written).toHaveLength(1) - // Only inbound peer traffic proves liveness; skipping health checks on saturation wedged half-open links forever. - for (let tick = 0; tick < 5; tick++) { - feed(encodeKeepAliveFrame(0, 0)) - vi.advanceTimersByTime(5_000) - } - expect(mux.isDisposed()).toBe(false) - expect(written).toHaveLength(1) - - drain() - const resumedAt = Date.now() - const internals = getMuxInternals(mux) - expect(internals.lastReceivedAt).toBe(resumedAt) - expect(new Set(internals.unackedTimestamps.values())).toEqual(new Set([resumedAt])) - - vi.advanceTimersByTime(20_000) - expect(mux.isDisposed()).toBe(false) - vi.advanceTimersByTime(5_000) - expect(mux.isDisposed()).toBe(true) - }) }) describe('wake guard (timer pause across system sleep, #7773)', () => { - it('sends one fresh probe per link and rebaselines liveness after a wake gap', () => { - const secondTransport = createMockTransport() - const secondMux = new SshChannelMultiplexer(secondTransport) - - try { - // Reach steady state with pending unacked keepalives (<5s old at pause). - vi.advanceTimersByTime(5_000) - expect(mux.isDisposed()).toBe(false) - expect(secondMux.isDisposed()).toBe(false) - - const internals = getMuxInternals(mux) - const secondInternals = getMuxInternals(secondMux) - const previousReceivedAt = internals.lastReceivedAt - const writesBefore = transport.written.length - const secondWritesBefore = secondTransport.written.length - - // Simulate sleep/App Nap: wall clock jumps far ahead with no ticks. - vi.setSystemTime(Date.now() + 60 * 60 * 1000) - vi.advanceTimersByTime(5_000) - const resumedAt = Date.now() - - expect(mux.isDisposed()).toBe(false) - expect(secondMux.isDisposed()).toBe(false) - expect(transport.written).toHaveLength(writesBefore + 1) - expect(secondTransport.written).toHaveLength(secondWritesBefore + 1) - expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive) - expect(secondTransport.written.at(-1)![0]).toBe(MessageType.KeepAlive) - - expect(internals.lastReceivedAt).toBe(resumedAt) - expect(internals.lastReceivedAt).toBeGreaterThan(previousReceivedAt) - expect(new Set(internals.unackedTimestamps.values())).toEqual(new Set([resumedAt])) - expect(secondInternals.lastReceivedAt).toBe(resumedAt) - expect(new Set(secondInternals.unackedTimestamps.values())).toEqual(new Set([resumedAt])) - } finally { - secondMux.dispose() - } - }) - it('keeps the link alive after wake when frames resume', () => { vi.advanceTimersByTime(5_000) vi.setSystemTime(Date.now() + 60 * 60 * 1000) diff --git a/src/main/ssh/ssh-channel-multiplexer.ts b/src/main/ssh/protocol/ssh-channel-multiplexer.ts similarity index 99% rename from src/main/ssh/ssh-channel-multiplexer.ts rename to src/main/ssh/protocol/ssh-channel-multiplexer.ts index 31353441691..1ba2940a966 100644 --- a/src/main/ssh/ssh-channel-multiplexer.ts +++ b/src/main/ssh/protocol/ssh-channel-multiplexer.ts @@ -1,6 +1,7 @@ /* eslint-disable max-lines -- Why: the SSH relay protocol state machine keeps request, notification, keepalive, and cancellation semantics paired. */ -import { FrameDecoder, type DecodedFrame } from '../../shared/relay-frame-decoder' +import { FrameDecoder } from '../../../shared/relay-frame-decoder' +import type { DecodedFrame } from '../../../shared/relay-frame-decoder-contract' import { MessageType, encodeJsonRpcFrame, @@ -12,7 +13,7 @@ import { type JsonRpcRequest, type JsonRpcResponse, type JsonRpcNotification -} from './remote-exec/remote-frame-protocol' +} from './remote-frame-protocol' import { SshMultiplexerTransportWriter, type MultiplexerTransport, @@ -20,8 +21,6 @@ import { type MultiplexerWriterLane } from './ssh-multiplexer-transport-writer' -export type { MultiplexerTransport, MultiplexerWriteSettlement } - type PendingRequest = { resolve: (result: unknown) => void reject: (error: Error) => void diff --git a/src/main/ssh/ssh-multiplexer-transport-writer.test.ts b/src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts similarity index 93% rename from src/main/ssh/ssh-multiplexer-transport-writer.test.ts rename to src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts index 02a05dc5064..0ad90a5755f 100644 --- a/src/main/ssh/ssh-multiplexer-transport-writer.test.ts +++ b/src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts @@ -1,7 +1,6 @@ import { EventEmitter } from 'node:events' import { describe, expect, it, vi } from 'vitest' import { - MULTIPLEXER_CONTROL_RESERVE_BYTES, MULTIPLEXER_ORDINARY_QUEUE_MAX_BYTES, SshMultiplexerTransportWriter, type MultiplexerTransport, @@ -138,22 +137,6 @@ describe('SshMultiplexerTransportWriter', () => { writer.dispose() }) - it('keeps a full ordinary lane from consuming the control reserve', () => { - const harness = transportHarness([false, true, true]) - const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn()) - - expect(writer.enqueue(Buffer.alloc(1), 'ordinary')).toBe(true) - expect(writer.enqueue(Buffer.alloc(MULTIPLEXER_ORDINARY_QUEUE_MAX_BYTES - 1), 'ordinary')).toBe( - true - ) - expect(writer.enqueue(Buffer.alloc(MULTIPLEXER_CONTROL_RESERVE_BYTES), 'control')).toBe(true) - - expect(harness.writes).toHaveLength(1) - harness.drain() - expect(harness.writes).toHaveLength(3) - writer.dispose() - }) - it('fails all retained writes once when a callback reports an error', () => { const harness = transportHarness([false]) const failed = vi.fn() diff --git a/src/main/ssh/ssh-multiplexer-transport-writer.ts b/src/main/ssh/protocol/ssh-multiplexer-transport-writer.ts similarity index 98% rename from src/main/ssh/ssh-multiplexer-transport-writer.ts rename to src/main/ssh/protocol/ssh-multiplexer-transport-writer.ts index f1b384c8fbe..7c19de3ee5e 100644 --- a/src/main/ssh/ssh-multiplexer-transport-writer.ts +++ b/src/main/ssh/protocol/ssh-multiplexer-transport-writer.ts @@ -1,9 +1,9 @@ -import { HEADER_LENGTH, MAX_MESSAGE_SIZE } from '../../shared/relay-frame-decoder' +import { HEADER_LENGTH, MAX_MESSAGE_SIZE } from '../../../shared/relay-frame-decoder' import { SshMultiplexerWriterLaneScheduler } from './ssh-multiplexer-writer-lane-scheduler' import type { WriteAmbiguityReason, WriteRefusalReason -} from '../../shared/terminal/pty/lifecycle/pty-write-settlement' +} from '../../../shared/terminal/pty/lifecycle/pty-write-settlement' export type MultiplexerTransportWriteResult = { ok: true } | { ok: false; error: Error } diff --git a/src/main/ssh/ssh-multiplexer-writer-lane-scheduler.ts b/src/main/ssh/protocol/ssh-multiplexer-writer-lane-scheduler.ts similarity index 100% rename from src/main/ssh/ssh-multiplexer-writer-lane-scheduler.ts rename to src/main/ssh/protocol/ssh-multiplexer-writer-lane-scheduler.ts diff --git a/src/main/ssh/ssh-multiplexer-writer-retention.test.ts b/src/main/ssh/protocol/ssh-multiplexer-writer-retention.test.ts similarity index 64% rename from src/main/ssh/ssh-multiplexer-writer-retention.test.ts rename to src/main/ssh/protocol/ssh-multiplexer-writer-retention.test.ts index 9c74fd8c734..5b6d4c77825 100644 --- a/src/main/ssh/ssh-multiplexer-writer-retention.test.ts +++ b/src/main/ssh/protocol/ssh-multiplexer-writer-retention.test.ts @@ -84,53 +84,6 @@ function harness() { } describe('SSH writer completed entry lifetime', () => { - for (const lane of ['ordinary', 'control'] as const) { - it.each(['drain', 'dispose'] as const)( - `releases completed ${lane} entries during a rolling backlog, then %s`, - async (release) => { - const state = harness() - try { - state.enqueue(0, lane) - state.enqueue(1, lane) - state.enqueue(2, lane) - state.complete() - for (let index = 0; index < 32; index += 1) { - state.drain() - state.complete() - state.enqueue(index + 3, lane) - } - await collect() - expect(state.buffers.slice(0, 33).filter((ref) => ref.deref())).toHaveLength(0) - expect(state.receipts.slice(0, 33).filter((ref) => ref.deref())).toHaveLength(0) - expect(state.buffers.slice(33).filter((ref) => ref.deref())).toHaveLength(2) - expect(state.receipts.slice(33).filter((ref) => ref.deref())).toHaveLength(2) - expect(state.writes).toEqual(Array.from({ length: 33 }, (_, index) => index)) - expect(state.settlements).toEqual( - state.writes.map((index) => ({ index, outcome: 'accepted' })) - ) - - if (release === 'drain') { - state.drain() - state.complete() - state.drain() - state.complete() - } else { - state.writer.dispose() - } - await collect() - expect(state.buffers.filter((ref) => ref.deref())).toHaveLength(0) - expect(state.receipts.filter((ref) => ref.deref())).toHaveLength(0) - expect(state.settlements).toHaveLength(35) - expect(state.settlements.slice(33).map((result) => result.outcome)).toEqual( - release === 'drain' ? ['accepted', 'accepted'] : ['refused', 'refused'] - ) - } finally { - state.writer.dispose() - } - } - ) - } - it('preserves in-flight callback ownership and one settlement across disposal', async () => { const state = harness() try { diff --git a/src/main/ssh/remote-exec/remote-exec-command.ts b/src/main/ssh/remote-exec/remote-exec-command.ts index b2d1724cbc2..f01f5df86f1 100644 --- a/src/main/ssh/remote-exec/remote-exec-command.ts +++ b/src/main/ssh/remote-exec/remote-exec-command.ts @@ -7,7 +7,7 @@ import { createSshOperationAbortError, type SshExecOptions } from '../connection import { REMOTE_COMMAND_DECODER_UNAVAILABLE, REMOTE_COMMAND_DECODER_UNAVAILABLE_EXIT -} from '../ssh-posix-command-wrapper' +} from './ssh-posix-command-wrapper' import { redactRelayInstallMarkerError, redactRelayInstallMarkerTokens diff --git a/src/main/ssh/remote-exec/remote-frame-protocol.test.ts b/src/main/ssh/remote-exec/remote-frame-protocol.test.ts deleted file mode 100644 index feca327e717..00000000000 --- a/src/main/ssh/remote-exec/remote-frame-protocol.test.ts +++ /dev/null @@ -1,215 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { HEADER_LENGTH, FrameDecoder, type DecodedFrame } from '../../../shared/relay-frame-decoder' -import { - MessageType, - encodeFrame, - encodeJsonRpcFrame, - encodeKeepAliveFrame, - parseJsonRpcMessage, - type JsonRpcRequest -} from './remote-frame-protocol' - -describe('frame encoding', () => { - it('encodes a frame with 13-byte header', () => { - const payload = Buffer.from('hello') - const frame = encodeFrame(MessageType.Regular, 1, 0, payload) - - expect(frame.length).toBe(HEADER_LENGTH + payload.length) - expect(frame[0]).toBe(MessageType.Regular) - expect(frame.readUInt32BE(1)).toBe(1) - expect(frame.readUInt32BE(5)).toBe(0) - expect(frame.readUInt32BE(9)).toBe(5) - expect(frame.subarray(HEADER_LENGTH).toString()).toBe('hello') - }) - - it('encodes keepalive frame with empty payload', () => { - const frame = encodeKeepAliveFrame(42, 10) - - expect(frame.length).toBe(HEADER_LENGTH) - expect(frame[0]).toBe(MessageType.KeepAlive) - expect(frame.readUInt32BE(1)).toBe(42) - expect(frame.readUInt32BE(5)).toBe(10) - expect(frame.readUInt32BE(9)).toBe(0) - }) - - it('encodes JSON-RPC frame', () => { - const msg: JsonRpcRequest = { - jsonrpc: '2.0', - id: 1, - method: 'pty.spawn', - params: { cols: 80, rows: 24 } - } - const frame = encodeJsonRpcFrame(msg, 5, 3) - - expect(frame[0]).toBe(MessageType.Regular) - expect(frame.readUInt32BE(1)).toBe(5) - expect(frame.readUInt32BE(5)).toBe(3) - - const payloadLen = frame.readUInt32BE(9) - const payload = frame.subarray(HEADER_LENGTH, HEADER_LENGTH + payloadLen) - const decoded = JSON.parse(payload.toString('utf-8')) - expect(decoded.method).toBe('pty.spawn') - expect(decoded.params.cols).toBe(80) - }) - - it('rejects messages larger than MAX_MESSAGE_SIZE', () => { - const bigPayload = { - jsonrpc: '2.0' as const, - id: 1, - method: 'x', - params: { data: 'a'.repeat(17 * 1024 * 1024) } - } - expect(() => encodeJsonRpcFrame(bigPayload, 1, 0)).toThrow('Message too large') - }) -}) - -describe('FrameDecoder', () => { - // Freeze clock for framing cases; relay-protocol-backpressure.test.ts separately covers time-sliced drain under CI load. - const frozenClock = { now: () => 0 } - - it('decodes a complete frame', () => { - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder((f) => frames.push(f), undefined, frozenClock) - - const payload = Buffer.from('test') - const encoded = encodeFrame(MessageType.Regular, 1, 0, payload) - decoder.feed(encoded) - - expect(frames).toHaveLength(1) - expect(frames[0].type).toBe(MessageType.Regular) - expect(frames[0].id).toBe(1) - expect(frames[0].ack).toBe(0) - expect(frames[0].payload.toString()).toBe('test') - }) - - it('handles partial frames across multiple feeds', () => { - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder((f) => frames.push(f), undefined, frozenClock) - - const payload = Buffer.from('hello world') - const encoded = encodeFrame(MessageType.Regular, 2, 1, payload) - - decoder.feed(encoded.subarray(0, 10)) - expect(frames).toHaveLength(0) - - decoder.feed(encoded.subarray(10)) - expect(frames).toHaveLength(1) - expect(frames[0].payload.toString()).toBe('hello world') - }) - - it('decodes multiple frames from a single chunk', () => { - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder((f) => frames.push(f), undefined, frozenClock) - - const frame1 = encodeFrame(MessageType.Regular, 1, 0, Buffer.from('a')) - const frame2 = encodeFrame(MessageType.Regular, 2, 1, Buffer.from('b')) - const combined = Buffer.concat([frame1, frame2]) - - decoder.feed(combined) - expect(frames).toHaveLength(2) - expect(frames[0].payload.toString()).toBe('a') - expect(frames[1].payload.toString()).toBe('b') - }) - - it('decodes keepalive frames', () => { - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder((f) => frames.push(f), undefined, frozenClock) - - decoder.feed(encodeKeepAliveFrame(5, 3)) - expect(frames).toHaveLength(1) - expect(frames[0].type).toBe(MessageType.KeepAlive) - expect(frames[0].payload.length).toBe(0) - }) - - it('skips oversized frames and calls onError instead of throwing', () => { - const errors: Error[] = [] - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder( - (f) => frames.push(f), - (err) => errors.push(err), - frozenClock - ) - - const oversizedLength = 17 * 1024 * 1024 - const header = Buffer.alloc(HEADER_LENGTH) - header[0] = MessageType.Regular - header.writeUInt32BE(1, 1) - header.writeUInt32BE(0, 5) - header.writeUInt32BE(oversizedLength, 9) - - const fakePayload = Buffer.alloc(oversizedLength) - const fullFrame = Buffer.concat([header, fakePayload]) - - decoder.feed(fullFrame) - expect(frames).toHaveLength(0) - expect(errors).toHaveLength(1) - expect(errors[0].message).toContain('discarded') - }) - - it('reset clears internal buffer', () => { - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder((f) => frames.push(f), undefined, frozenClock) - - const encoded = encodeFrame(MessageType.Regular, 1, 0, Buffer.from('test')) - decoder.feed(encoded.subarray(0, 5)) - decoder.reset() - - decoder.feed(encodeFrame(MessageType.Regular, 2, 0, Buffer.from('new'))) - expect(frames).toHaveLength(1) - expect(frames[0].id).toBe(2) - }) - - it('decodes frames fed one byte at a time (worst-case boundary straddling)', () => { - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder((f) => frames.push(f), undefined, frozenClock) - - const frame1 = encodeFrame(MessageType.Regular, 1, 0, Buffer.from('first payload')) - const frame2 = encodeFrame(MessageType.Regular, 2, 1, Buffer.from('second')) - const combined = Buffer.concat([frame1, frame2]) - - for (let i = 0; i < combined.length; i += 1) { - decoder.feed(combined.subarray(i, i + 1)) - } - - expect(frames).toHaveLength(2) - expect(frames[0].payload.toString()).toBe('first payload') - expect(frames[1].id).toBe(2) - expect(frames[1].payload.toString()).toBe('second') - }) - - it('skips an oversized frame fed in odd-sized chunks and resynchronizes', () => { - const errors: Error[] = [] - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder( - (f) => frames.push(f), - (err) => errors.push(err), - frozenClock - ) - - const oversizedLength = 17 * 1024 * 1024 - const header = Buffer.alloc(HEADER_LENGTH) - header[0] = MessageType.Regular - header.writeUInt32BE(1, 1) - header.writeUInt32BE(0, 5) - header.writeUInt32BE(oversizedLength, 9) - const oversized = Buffer.concat([header, Buffer.alloc(oversizedLength)]) - const valid = encodeFrame(MessageType.Regular, 2, 0, Buffer.from('after')) - const combined = Buffer.concat([oversized, valid]) - - const chunkSize = 1024 * 1024 - 7 - for (let i = 0; i < combined.length; i += chunkSize) { - decoder.feed(combined.subarray(i, i + chunkSize)) - } - - expect(errors).toHaveLength(1) - expect(frames).toHaveLength(1) - expect(frames[0].payload.toString()).toBe('after') - }) -}) - -describe('parseJsonRpcMessage', () => { - it('throws on invalid jsonrpc version', () => { - const payload = Buffer.from(JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'x' })) - expect(() => parseJsonRpcMessage(payload)).toThrow('Invalid JSON-RPC version') - }) -}) diff --git a/src/main/ssh/remote-exec/remote-host-exec.ts b/src/main/ssh/remote-exec/remote-host-exec.ts index 8caef686654..1aedbc8d126 100644 --- a/src/main/ssh/remote-exec/remote-host-exec.ts +++ b/src/main/ssh/remote-exec/remote-host-exec.ts @@ -1,6 +1,6 @@ import type { RemoteInstallTransport } from '../../managed-server/install/remote-install-transport' import { execCommand } from './remote-exec-command' -import type { RemoteHostPlatform } from '../ssh-remote-platform' +import type { RemoteHostPlatform } from '../remote-host/ssh-remote-platform' export function execHostCommand( conn: RemoteInstallTransport, diff --git a/src/main/ssh/ssh-exec-command-decoder-fallback.test.ts b/src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts similarity index 77% rename from src/main/ssh/ssh-exec-command-decoder-fallback.test.ts rename to src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts index 8cdde22cbc8..618e8f92eaf 100644 --- a/src/main/ssh/ssh-exec-command-decoder-fallback.test.ts +++ b/src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts @@ -3,13 +3,13 @@ import { PassThrough } from 'node:stream' import { describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' import { wrapRemoteCommandForPosixShell } from './ssh-posix-command-wrapper' -import type { SshExecOptions } from './connection/ssh-exec-options' -import { execCommand } from './remote-exec/remote-exec-command' +import type { SshExecOptions } from '../connection/ssh-exec-options' +import { execCommand } from './remote-exec-command' import { captureOrcadStateSnapshotCommand, parseOrcadSnapshotCapture -} from '../managed-server/host-state/orcad-state-snapshot' -import { getRemoteHostPlatform } from './ssh-remote-platform' +} from '../../managed-server/host-state/orcad-state-snapshot' +import { getRemoteHostPlatform } from '../remote-host/ssh-remote-platform' import { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -69,23 +69,6 @@ describe.skipIf(process.platform === 'win32')( ]) }) - it('remembers the host across a reconnect that replaces the connection object', async () => { - const target = { id: 'decoderless-target' } - const first = { ...host({ path: '' }), getTarget: () => target } - await expect(execCommand(first, LONG)).resolves.toBe('ran') - const reconnected = { ...host({ path: '' }), getTarget: () => target } - await expect(execCommand(reconnected, LONG)).resolves.toBe('ran') - expect(reconnected.exec.mock.calls.map(([, options]) => options?.compressCommand)).toEqual([ - false - ]) - }) - - it('keeps compressing for a host that has the decoders', async () => { - const conn = host() - await expect(execCommand(conn, LONG)).resolves.toBe('ran') - expect(conn.exec).toHaveBeenCalledTimes(1) - }) - it('captures a snapshot whole through a gateway that cuts exec requests at 6 KiB and merges stderr', async () => { const base = mkdtempSync(join(tmpdir(), 'orcad-gateway-capture-')) try { diff --git a/src/main/ssh/ssh-exec-rc-stdout-noise.test.ts b/src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts similarity index 94% rename from src/main/ssh/ssh-exec-rc-stdout-noise.test.ts rename to src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts index 07df77f9495..8311f5c6ee0 100644 --- a/src/main/ssh/ssh-exec-rc-stdout-noise.test.ts +++ b/src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts @@ -7,16 +7,16 @@ import { PassThrough } from 'node:stream' import { describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' import { wrapRemoteCommandForPosixShell } from './ssh-posix-command-wrapper' -import type { SshExecOptions } from './connection/ssh-exec-options' -import { execCommand, isSshCommandExitError } from './remote-exec/remote-exec-command' +import type { SshExecOptions } from '../connection/ssh-exec-options' +import { execCommand, isSshCommandExitError } from './remote-exec-command' import { readRemoteHomeCommand } from './ssh-remote-commands' -import type { SshConnection } from './connection/ssh-connection' -import { tryResolveViaLoginShell } from './ssh-remote-node-resolution' +import type { SshConnection } from '../connection/ssh-connection' +import { tryResolveViaLoginShell } from '../remote-host/node-toolchain/ssh-remote-node-resolution' import { normalizeRemoteHome, validateRemoteHome, type RemoteHostPlatform -} from './ssh-remote-platform' +} from '../remote-host/ssh-remote-platform' const LINUX_HOST: RemoteHostPlatform = { os: 'linux', diff --git a/src/main/ssh/ssh-login-shell-command.ts b/src/main/ssh/remote-exec/ssh-login-shell-command.ts similarity index 83% rename from src/main/ssh/ssh-login-shell-command.ts rename to src/main/ssh/remote-exec/ssh-login-shell-command.ts index 86e3ffd03fe..b0dd022ff5c 100644 --- a/src/main/ssh/ssh-login-shell-command.ts +++ b/src/main/ssh/remote-exec/ssh-login-shell-command.ts @@ -1,5 +1,5 @@ -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { buildAnyShellStdoutFence } from '../../shared/posix-stdout-fence' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { buildAnyShellStdoutFence } from '../../../shared/posix-stdout-fence' const COMMAND_ONLY_SHELLS = new Set(['sh', 'dash', 'csh', 'tcsh']) diff --git a/src/main/ssh/ssh-posix-command-wrapper.test.ts b/src/main/ssh/remote-exec/ssh-posix-command-wrapper.test.ts similarity index 96% rename from src/main/ssh/ssh-posix-command-wrapper.test.ts rename to src/main/ssh/remote-exec/ssh-posix-command-wrapper.test.ts index fe0bf79c72a..a26cae75979 100644 --- a/src/main/ssh/ssh-posix-command-wrapper.test.ts +++ b/src/main/ssh/remote-exec/ssh-posix-command-wrapper.test.ts @@ -1,11 +1,11 @@ -import { encodePosixPrintfRecords } from '../../shared/posix-printf-encoding' +import { encodePosixPrintfRecords } from '../../../shared/posix-printf-encoding' import { spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' import { describe, expect, it } from 'vitest' import { chmodSync, existsSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { REMOTE_COMMAND_DECODER_UNAVAILABLE, REMOTE_COMMAND_DECODER_UNAVAILABLE_EXIT, diff --git a/src/main/ssh/ssh-posix-command-wrapper.ts b/src/main/ssh/remote-exec/ssh-posix-command-wrapper.ts similarity index 92% rename from src/main/ssh/ssh-posix-command-wrapper.ts rename to src/main/ssh/remote-exec/ssh-posix-command-wrapper.ts index 17b0555540b..ca360d75d7d 100644 --- a/src/main/ssh/ssh-posix-command-wrapper.ts +++ b/src/main/ssh/remote-exec/ssh-posix-command-wrapper.ts @@ -1,6 +1,6 @@ -import { encodePosixPrintfRecords } from '../../shared/posix-printf-encoding' +import { encodePosixPrintfRecords } from '../../../shared/posix-printf-encoding' import { gzipSync } from 'node:zlib' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' const REMOTE_COMMAND_COMPRESSION_THRESHOLD_BYTES = 8_000 diff --git a/src/main/ssh/ssh-remote-commands.test.ts b/src/main/ssh/remote-exec/ssh-remote-commands.test.ts similarity index 86% rename from src/main/ssh/ssh-remote-commands.test.ts rename to src/main/ssh/remote-exec/ssh-remote-commands.test.ts index 70b383eaede..07a766bc132 100644 --- a/src/main/ssh/ssh-remote-commands.test.ts +++ b/src/main/ssh/remote-exec/ssh-remote-commands.test.ts @@ -11,29 +11,20 @@ import { utimesSync } from 'node:fs' import { tmpdir } from 'node:os' -import { basename, dirname, join } from 'node:path' +import { dirname, join } from 'node:path' import { describe, expect, it } from 'vitest' import { decodeRemotePowerShellScript } from './ssh-remote-powershell' import { tryCreateInstallLockCommand, tryStealInstallLockCommand -} from '../managed-server/install/remote-install-lock-commands' -import { - listRemoteInstallBaseDirsCommand, - MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES, - probeRemoteInstallCompleteCommand -} from './ssh-remote-commands' +} from '../../managed-server/install/remote-install-lock-commands' +import { listRemoteInstallBaseDirsCommand } from '../../managed-server/install/remote-install-gc-listing-command' +import { probeRemoteInstallCompleteCommand } from '../../managed-server/install/remote-install-completeness-command' import { ORCAD_INSTALL_MODEL, RELAY_INSTALL_MODEL -} from '../managed-server/install/remote-install-model' -import { getRemoteHostPlatform } from './ssh-remote-platform' -import { - createRelayGcListingFixture, - readUncappedRelayGcPaths, - runCappedRelayGcShellCommand, - SSH_EXEC_OUTPUT_CAP_CHARS -} from '../managed-server/install/remote-install-gc-listing.test-fixture' +} from '../../managed-server/install/remote-install-model' +import { getRemoteHostPlatform } from '../remote-host/ssh-remote-platform' const posix = getRemoteHostPlatform('linux-x64') const nativePosix = getRemoteHostPlatform( @@ -170,51 +161,6 @@ describe('ssh remote command builders', () => { } }) - it.runIf(process.platform !== 'win32')( - 'bounds real POSIX GC output with more than the exec-cap stage population', - async () => { - const fixture = createRelayGcListingFixture() - try { - const paths = await readUncappedRelayGcPaths(fixture.findCommand) - expect(paths.join('\n').length).toBeGreaterThan(SSH_EXEC_OUTPUT_CAP_CHARS) - const cappedRaw = await runCappedRelayGcShellCommand( - `${fixture.findCommand} | LC_ALL=C sort` - ) - expect(cappedRaw.length).toBe(SSH_EXEC_OUTPUT_CAP_CHARS) - for (const name of fixture.validNames) { - expect(cappedRaw).not.toContain(join(fixture.root, name)) - } - - const output = await runCappedRelayGcShellCommand( - listRelayBaseDirsCommand(posix, fixture.root) - ) - const entries = output.trim().split('\n') - - expect([...entries].sort()).toEqual(['relay-0.1.0+aaa', 'relay-0.1.0+bbb']) - expect(Buffer.byteLength(output)).toBeLessThan(1_024) - expect(entries.length).toBeLessThanOrEqual(MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES) - - fixture.fillValidEntryBoundary() - const validNames = new Set(fixture.validNames) - const unboundedEntries = (await readUncappedRelayGcPaths(fixture.findCommand)) - .map((path) => basename(path)) - .filter((name) => validNames.has(name)) - expect(unboundedEntries).toHaveLength(65) - const boundedOutput = await runCappedRelayGcShellCommand( - listRelayBaseDirsCommand(posix, fixture.root) - ) - const boundedEntries = boundedOutput.trim().split('\n') - expect(boundedEntries).toEqual(unboundedEntries.slice(0, 64)) - expect(boundedEntries).toHaveLength(64) - expect(new Set(boundedEntries).size).toBe(64) - expect(Buffer.byteLength(boundedOutput)).toBeLessThan(1_024) - } finally { - fixture.dispose() - } - }, - 30_000 - ) - it.runIf(process.platform !== 'win32')( 'fails closed when real POSIX GC enumeration fails', async () => { diff --git a/src/main/ssh/ssh-remote-commands.ts b/src/main/ssh/remote-exec/ssh-remote-commands.ts similarity index 52% rename from src/main/ssh/ssh-remote-commands.ts rename to src/main/ssh/remote-exec/ssh-remote-commands.ts index 37e15c9a259..19a5ea51d67 100644 --- a/src/main/ssh/ssh-remote-commands.ts +++ b/src/main/ssh/remote-exec/ssh-remote-commands.ts @@ -1,17 +1,9 @@ -import { - remoteInstallListingRegexSource, - type RemoteInstallModel -} from '../managed-server/install/remote-install-model' +import type { RemoteHostPlatform } from '../remote-host/ssh-remote-platform' +import { isWindowsRemoteHost, remoteDirname } from '../remote-host/ssh-remote-platform' -import { - type RemoteHostPlatform, - isWindowsRemoteHost, - joinRemotePath, - remoteDirname -} from './ssh-remote-platform' import { powerShellCommand } from './ssh-remote-powershell' -import { quotePowerShellLiteral as powerShellLiteral } from '../../shared/powershell-native-argument' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' export function readRemoteHomeCommand(host: RemoteHostPlatform): string { if (!isWindowsRemoteHost(host)) { @@ -79,63 +71,6 @@ export function writeRemoteEmptyFileCommand(host: RemoteHostPlatform, remotePath ) } -/** Require the directory and every declared regular-file artifact; incomplete installs must report missing. */ -export function probeRemoteInstallCompleteCommand( - host: RemoteHostPlatform, - remoteInstallDir: string, - requiredFilenames: readonly string[] -): string { - if (!isWindowsRemoteHost(host)) { - // Use relative artifacts inside a subshell to fit gateway exec budgets without leaking cd (#30491). - const fileTests = requiredFilenames - .map((filename) => `&& test -f ${quotePosixShell(filename)} `) - .join('') - return `(cd ${quotePosixShell(remoteInstallDir)} 2>/dev/null ${fileTests}) && echo OK || echo MISSING` - } - const required = requiredFilenames.map((filename) => - joinRemotePath(host, remoteInstallDir, filename) - ) - return powerShellCommand( - [ - `$dir = ${powerShellLiteral(remoteInstallDir)}`, - `$required = @(${required.map((path) => powerShellLiteral(path)).join(', ')})`, - '$ok = Test-Path -LiteralPath $dir -PathType Container', - 'foreach ($f in $required) { if (-not (Test-Path -LiteralPath $f -PathType Leaf)) { $ok = $false } }', - "if ($ok) { 'OK' } else { 'MISSING' }" - ].join('; ') - ) -} - -export const MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES = 64 - -/** Scope both listing glob and validation regex by install model so orcad GC never even receives legacy relay directory names. */ -export function listRemoteInstallBaseDirsCommand( - host: RemoteHostPlatform, - baseDir: string, - model: RemoteInstallModel -): string { - const namePattern = remoteInstallListingRegexSource(model) - if (!isWindowsRemoteHost(host)) { - const statusPrefix = '__ORCA_RELAY_GC_FIND_STATUS__' - return [ - `base=${quotePosixShell(baseDir)}; [ -d "$base" ] || exit 0;`, - `{ find "$base" -mindepth 1 -maxdepth 1 -type d -name '${model.dirPrefix}-*' -print; status=$?; printf '\n${statusPrefix}%s\n' "$status"; } |`, - String.raw`awk 'BEGIN { count=0; status=-1 } /^${statusPrefix}[0-9]+$/ { status=substr($0, ${statusPrefix.length + 1}); next } { name=$0; sub(/^.*\//, "", name); if (name ~ /${namePattern}/ && count < ${MAX_REMOTE_INSTALL_GC_LISTING_ENTRIES}) { entries[count++]=name } } END { if (status != 0) exit 1; for (i=0; i vi.fn()) -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../../remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand: execCommandMock })) @@ -298,16 +298,6 @@ describe('resolveRemoteNodePath', () => { await expect(resolveRemoteNodePath(conn)).resolves.toBe('/usr/local/bin/node') }) - it('deduplicates repeated candidate paths before version-checking', async () => { - // Deduplicate stale shim paths before checking Node/npm again. - execCommandMock - .mockResolvedValueOnce('/usr/local/bin/node\n/usr/local/bin/node\n') - .mockResolvedValueOnce('v20.0.0\n') - - await expect(resolveRemoteNodePath(conn)).resolves.toBe('/usr/local/bin/node') - expect(execCommandMock).toHaveBeenCalledTimes(2) - }) - it('falls back to the login shell when path probes find nothing', async () => { execCommandMock .mockResolvedValueOnce('\n') @@ -403,26 +393,6 @@ describe('resolveRemoteNodePath', () => { ) }) - it('throws when both strategies find no usable node', async () => { - execCommandMock - .mockResolvedValueOnce('\n') - .mockResolvedValueOnce('/bin/bash') - .mockResolvedValueOnce('\n') - .mockResolvedValueOnce('apt-get\n') - - await expect(resolveRemoteNodePath(conn)).rejects.toThrow(/sudo apt-get install -y nodejs npm/) - }) - - it('throws when the path-probe exec fails and the login shell finds nothing', async () => { - execCommandMock - .mockRejectedValueOnce(new Error('SSH exec channel failed')) - .mockResolvedValueOnce('/bin/zsh') - .mockResolvedValueOnce('\n') - .mockRejectedValueOnce(new Error('package manager probe failed')) - - await expect(resolveRemoteNodePath(conn)).rejects.toThrow(/Debian\/Ubuntu:/) - }) - it('keeps the default path-probe fallback for SSH session-limit-shaped errors', async () => { const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 4 @@ -529,28 +499,6 @@ describe('resolveRemoteNodePath', () => { ).rejects.toMatchObject({ name: 'AbortError' }) }) - it('throws when every candidate across both strategies is below the minimum', async () => { - execCommandMock - .mockResolvedValueOnce('/old/node\n') - .mockResolvedValueOnce('v8.17.0\n') - .mockResolvedValueOnce('/bin/bash') - .mockImplementationOnce(loginShellAnswer('/old/node2\n')) - .mockResolvedValueOnce('v6.17.0\n') - .mockResolvedValueOnce('dnf\n') - - await expect(resolveRemoteNodePath(conn)).rejects.toThrow(/sudo dnf install -y nodejs npm/) - }) - - it('rejects a Windows node.exe below the minimum version', async () => { - execCommandMock - .mockResolvedValueOnce('C:\\Program Files\\nodejs\\node.exe\n') - .mockResolvedValueOnce('v16.20.2\n') - - await expect(resolveRemoteNodePath(conn, getRemoteHostPlatform('win32-x64'))).rejects.toThrow( - /winget install OpenJS\.NodeJS\.LTS/ - ) - }) - it('does not stop Windows node discovery after the first existing candidate', async () => { execCommandMock .mockResolvedValueOnce('C:\\old\\node.exe\nC:\\Program Files\\nodejs\\node.exe\n') @@ -606,23 +554,6 @@ describe('resolveRemoteNodePath', () => { await expect(resolveRemoteNodePath(conn, undefined, { strict: true })).rejects.toBe(lost) }) - it('probes a Node the login shell names again only once', async () => { - execCommandMock - .mockResolvedValueOnce('/usr/local/bin/node\n') - .mockResolvedValueOnce('__node__\nv20.0.0\n') - .mockResolvedValueOnce('/bin/bash') - .mockImplementationOnce(loginShellAnswer('/usr/local/bin/node\n')) - .mockResolvedValueOnce('') - - await expect(resolveRemoteNodePath(conn, undefined, { strict: true })).rejects.toBeInstanceOf( - RemoteNodeNotFoundError - ) - const npmProbes = execCommandMock.mock.calls.filter(([, command]) => - String(command).includes('npm --version') - ) - expect(npmProbes).toHaveLength(1) - }) - it('proves a POSIX host has no Node when every probe answered', async () => { execCommandMock .mockResolvedValueOnce('') diff --git a/src/main/ssh/ssh-remote-node-resolution.ts b/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.ts similarity index 94% rename from src/main/ssh/ssh-remote-node-resolution.ts rename to src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.ts index 8ca4cd69845..8968bdb306a 100644 --- a/src/main/ssh/ssh-remote-node-resolution.ts +++ b/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.ts @@ -1,20 +1,20 @@ -import type { SshConnection } from './connection/ssh-connection' -import { createSshOperationAbortError } from './connection/ssh-exec-options' -import type { RemoteHostPlatform } from './ssh-remote-platform' -import { isWindowsRemoteHost, normalizeWindowsRemotePath } from './ssh-remote-platform' -import { powerShellCommand } from './ssh-remote-powershell' +import type { SshConnection } from '../../connection/ssh-connection' +import { createSshOperationAbortError } from '../../connection/ssh-exec-options' +import type { RemoteHostPlatform } from '../ssh-remote-platform' +import { isWindowsRemoteHost, normalizeWindowsRemotePath } from '../ssh-remote-platform' +import { powerShellCommand } from '../../remote-exec/ssh-remote-powershell' import { buildPosixNodeInstallGuidance, type RemoteNodeResolutionOptions } from './ssh-remote-node-install-guidance' -import { execCommand, isSshCommandExitError } from './remote-exec/remote-exec-command' +import { execCommand, isSshCommandExitError } from '../../remote-exec/remote-exec-command' import { buildPosixNodeToolchainProbe, buildWindowsNodeToolchainProbe, nodeToolchainVersionsMeetRequirements } from './ssh-remote-node-toolchain-probe' -import { isSshSessionLimitError } from './ssh-session-limit-error' -import { buildSshLoginShellCommand } from './ssh-login-shell-command' +import { isSshSessionLimitError } from '../../connection/ssh-session-limit-error' +import { buildSshLoginShellCommand } from '../../remote-exec/ssh-login-shell-command' import { REMOTE_NODE_PATH_PROBE_SCRIPT } from './ssh-remote-node-probe-script' // Login fallback covers custom profiles but can hang on interactive setup; keep its deadline short. diff --git a/src/main/ssh/ssh-remote-node-toolchain-probe.ts b/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-toolchain-probe.ts similarity index 95% rename from src/main/ssh/ssh-remote-node-toolchain-probe.ts rename to src/main/ssh/remote-host/node-toolchain/ssh-remote-node-toolchain-probe.ts index 9230f6ca537..9151aaa7717 100644 --- a/src/main/ssh/ssh-remote-node-toolchain-probe.ts +++ b/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-toolchain-probe.ts @@ -1,6 +1,6 @@ import { posix as posixPath } from 'node:path' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { quotePowerShellLiteral as powerShellLiteral } from '../../shared/powershell-native-argument' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../../shared/powershell-native-argument' const MIN_HOST_NODE_MAJOR = 18 const NODE_VERSION_MARKER = '__ORCA_NODE_VERSION__' diff --git a/src/main/ssh/ssh-host-platform-memo.ts b/src/main/ssh/remote-host/ssh-host-platform-memo.ts similarity index 88% rename from src/main/ssh/ssh-host-platform-memo.ts rename to src/main/ssh/remote-host/ssh-host-platform-memo.ts index 27762c811d4..9c6d7c1519a 100644 --- a/src/main/ssh/ssh-host-platform-memo.ts +++ b/src/main/ssh/remote-host/ssh-host-platform-memo.ts @@ -1,5 +1,5 @@ /** Memoize session host facts for connect telemetry without extra probes; keys are local target ids. */ -import type { NodeRuntimeTarget } from '../../shared/node-runtime-pin' +import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import type { RemoteHostPlatform } from './ssh-remote-platform' export type SshHostPlatformFacts = { @@ -41,7 +41,3 @@ export function rememberSshHostPlatform( export function knownSshHostPlatform(targetId: string): SshHostPlatformFacts | null { return known.get(targetId) ?? null } - -export function resetSshHostPlatformMemoForTests(): void { - known.clear() -} diff --git a/src/main/ssh/ssh-host-proxy-environment.test.ts b/src/main/ssh/remote-host/ssh-host-proxy-environment.test.ts similarity index 89% rename from src/main/ssh/ssh-host-proxy-environment.test.ts rename to src/main/ssh/remote-host/ssh-host-proxy-environment.test.ts index 605f8d53c4e..477638c1185 100644 --- a/src/main/ssh/ssh-host-proxy-environment.test.ts +++ b/src/main/ssh/remote-host/ssh-host-proxy-environment.test.ts @@ -1,10 +1,10 @@ import { execFileSync } from 'node:child_process' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { execCommand } from './remote-exec/remote-exec-command' -import type * as ExecCommandModule from './remote-exec/remote-exec-command' +import { execCommand } from '../remote-exec/remote-exec-command' +import type * as ExecCommandModule from '../remote-exec/remote-exec-command' import { readSshHostProxyEnvironment } from './ssh-host-proxy-environment' -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand: vi.fn() })) diff --git a/src/main/ssh/ssh-host-proxy-environment.ts b/src/main/ssh/remote-host/ssh-host-proxy-environment.ts similarity index 93% rename from src/main/ssh/ssh-host-proxy-environment.ts rename to src/main/ssh/remote-host/ssh-host-proxy-environment.ts index 41579872fa6..f9cb4baaee6 100644 --- a/src/main/ssh/ssh-host-proxy-environment.ts +++ b/src/main/ssh/remote-host/ssh-host-proxy-environment.ts @@ -1,12 +1,12 @@ -import { PROXY_ENVIRONMENT_KEYS } from '../../shared/network-proxy' +import { PROXY_ENVIRONMENT_KEYS } from '../../../shared/network-proxy' import { execCommand, isSshCommandExitError, isSshExecTimeout, isUnconfirmedSshCommandTermination -} from './remote-exec/remote-exec-command' -import { powerShellCommand } from './ssh-remote-powershell' -import { isSshSessionLimitError } from './ssh-session-limit-error' +} from '../remote-exec/remote-exec-command' +import { powerShellCommand } from '../remote-exec/ssh-remote-powershell' +import { isSshSessionLimitError } from '../connection/ssh-session-limit-error' type ProxyEnvironmentTransport = Parameters[0] diff --git a/src/main/ssh/ssh-remote-platform-detection.test.ts b/src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts similarity index 96% rename from src/main/ssh/ssh-remote-platform-detection.test.ts rename to src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts index 782c0af7d61..7c33ac7aac5 100644 --- a/src/main/ssh/ssh-remote-platform-detection.test.ts +++ b/src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts @@ -1,11 +1,11 @@ -import type * as ExecCommandModule from './remote-exec/remote-exec-command' +import type * as ExecCommandModule from '../remote-exec/remote-exec-command' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { SshConnection } from './connection/ssh-connection' -import { SSH_EXEC_TIMEOUT_CODE } from './remote-exec/remote-exec-command' +import type { SshConnection } from '../connection/ssh-connection' +import { SSH_EXEC_TIMEOUT_CODE } from '../remote-exec/remote-exec-command' const execCommandMock = vi.hoisted(() => vi.fn()) -vi.mock('./remote-exec/remote-exec-command', async (importOriginal) => ({ +vi.mock('../remote-exec/remote-exec-command', async (importOriginal) => ({ ...(await importOriginal()), execCommand: execCommandMock })) diff --git a/src/main/ssh/ssh-remote-platform-detection.ts b/src/main/ssh/remote-host/ssh-remote-platform-detection.ts similarity index 93% rename from src/main/ssh/ssh-remote-platform-detection.ts rename to src/main/ssh/remote-host/ssh-remote-platform-detection.ts index 1270588c35c..732b5f32931 100644 --- a/src/main/ssh/ssh-remote-platform-detection.ts +++ b/src/main/ssh/remote-host/ssh-remote-platform-detection.ts @@ -1,17 +1,22 @@ -import type { RemoteInstallTransport } from '../managed-server/install/remote-install-transport' +import type { RemoteInstallTransport } from '../../managed-server/install/remote-install-transport' import { getProcessOutputFields, iterateProcessOutputLines -} from '../../shared/process-output-field-scanner' -import { parseUnameToRelayPlatform, type RelayPlatform } from './remote-exec/remote-frame-protocol' +} from '../../../shared/process-output-field-scanner' +import { + parseUnameToRelayPlatform, + type RelayPlatform, + getRemoteHostPlatform, + type RemoteHostPlatform +} from './ssh-remote-platform' import { execCommand, isSshExecTimeout, isUnconfirmedSshCommandTermination -} from './remote-exec/remote-exec-command' -import { isSshSessionLimitError } from './ssh-session-limit-error' -import { getRemoteHostPlatform, type RemoteHostPlatform } from './ssh-remote-platform' -import { powerShellCommand } from './ssh-remote-powershell' +} from '../remote-exec/remote-exec-command' +import { isSshSessionLimitError } from '../connection/ssh-session-limit-error' + +import { powerShellCommand } from '../remote-exec/ssh-remote-powershell' const PLATFORM_PROBE_MARKER = '__ORCA_REMOTE_PLATFORM__' /** The probe's marker-backed line starts with this. */ diff --git a/src/main/ssh/ssh-remote-platform.test.ts b/src/main/ssh/remote-host/ssh-remote-platform.test.ts similarity index 100% rename from src/main/ssh/ssh-remote-platform.test.ts rename to src/main/ssh/remote-host/ssh-remote-platform.test.ts diff --git a/src/main/ssh/ssh-remote-platform.ts b/src/main/ssh/remote-host/ssh-remote-platform.ts similarity index 83% rename from src/main/ssh/ssh-remote-platform.ts rename to src/main/ssh/remote-host/ssh-remote-platform.ts index 55a644eab6c..ae136261fb7 100644 --- a/src/main/ssh/ssh-remote-platform.ts +++ b/src/main/ssh/remote-host/ssh-remote-platform.ts @@ -1,8 +1,48 @@ -import type { RelayPlatform } from './remote-exec/remote-frame-protocol' +export type RelayPlatform = + | 'linux-x64' + | 'linux-arm64' + | 'darwin-x64' + | 'darwin-arm64' + | 'win32-x64' + | 'win32-arm64' + +export function parseUnameToRelayPlatform(os: string, arch: string): RelayPlatform | null { + const normalizedOs = os.toLowerCase().trim() + const normalizedArch = arch.toLowerCase().trim() + + let relayOs: string | null = null + if (normalizedOs === 'linux') { + relayOs = 'linux' + } else if (normalizedOs === 'darwin') { + relayOs = 'darwin' + } else if ( + normalizedOs === 'windows' || + normalizedOs === 'win32' || + normalizedOs.startsWith('mingw') || + normalizedOs.startsWith('msys') + ) { + relayOs = 'win32' + } + + let relayArch: string | null = null + if (normalizedArch === 'x86_64' || normalizedArch === 'amd64' || normalizedArch === 'x64') { + relayArch = 'x64' + } else if (normalizedArch === 'aarch64' || normalizedArch === 'arm64') { + relayArch = 'arm64' + } + + if (!relayOs || !relayArch) { + return null + } + return `${relayOs}-${relayArch}` as RelayPlatform +} export type RemotePathFlavor = 'posix' | 'windows' + type RemoteCommandDialect = 'posix' | 'powershell' + type RemoteOperatingSystem = 'linux' | 'darwin' | 'win32' + type RemoteArchitecture = 'x64' | 'arm64' export type RemoteHostPlatform = { diff --git a/src/main/ssh/runtime-ssh-access-verification.ts b/src/main/ssh/runtime-access/runtime-ssh-access-verification.ts similarity index 60% rename from src/main/ssh/runtime-ssh-access-verification.ts rename to src/main/ssh/runtime-access/runtime-ssh-access-verification.ts index bcdb81080ed..a1eb5d74103 100644 --- a/src/main/ssh/runtime-ssh-access-verification.ts +++ b/src/main/ssh/runtime-access/runtime-ssh-access-verification.ts @@ -1,7 +1,7 @@ -import type { KnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' -import { verifyRuntimeEnvironmentIdentity } from '../runtime/hosts/identity/runtime-environment-identity-verification' -import type { PairedRuntimeConnection } from '../../shared/remote-runtime/pairing/paired-runtime-connection' -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import { verifyRuntimeEnvironmentIdentity } from '../../runtime/hosts/identity/runtime-environment-identity-verification' +import type { PairedRuntimeConnection } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' export async function verifyRuntimeEnvironmentSshTunnel( environment: KnownRuntimeEnvironment, diff --git a/src/main/ssh/runtime-ssh-access.test.ts b/src/main/ssh/runtime-access/runtime-ssh-access.test.ts similarity index 74% rename from src/main/ssh/runtime-ssh-access.test.ts rename to src/main/ssh/runtime-access/runtime-ssh-access.test.ts index a5c748c335c..2490827e8ed 100644 --- a/src/main/ssh/runtime-ssh-access.test.ts +++ b/src/main/ssh/runtime-access/runtime-ssh-access.test.ts @@ -1,16 +1,15 @@ -import { pairedRuntimeConnectionFromOffer } from '../../shared/remote-runtime/pairing/paired-runtime-connection' +import { pairedRuntimeConnectionFromOffer } from '../../../shared/remote-runtime/pairing/paired-runtime-connection' 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 { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' +import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' import { addEnvironmentFromPairingCode, resolveEnvironment -} from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { readPersistedEnvironmentStore } from '../../shared/remote-runtime/host-store/runtime-environment-store-file' -import { writeRuntimeEnvironmentSidecarEntry } from '../../shared/remote-runtime/host-store/runtime-environment-sidecar' -import type { SshTarget } from '../../shared/ssh-types' +} from '../../../shared/remote-runtime/host-store/runtime-environment-store' + +import type { SshTarget } from '../../../shared/ssh-types' const mocks = vi.hoisted(() => ({ infrastructure: vi.fn(), @@ -23,10 +22,10 @@ const mocks = vi.hoisted(() => ({ flush: vi.fn(), preflight: vi.fn() })) -vi.mock('../managed-server/lifecycle/orcad-managed-runtime-context', () => ({ +vi.mock('../../managed-server/lifecycle/orcad-managed-runtime-context', () => ({ requireManagedOrcadInfrastructure: mocks.infrastructure })) -vi.mock('../managed-server/lifecycle/orcad-managed-tunnel', () => ({ +vi.mock('../../managed-server/lifecycle/orcad-managed-tunnel', () => ({ startOrcadManagedTunnel: mocks.start, closeOrcadManagedTunnel: mocks.close, ensureOrcadManagedTunnel: mocks.ensure @@ -135,38 +134,6 @@ describe('independent runtime SSH access coordinator', () => { }) afterEach(() => rmSync(userDataPath, { recursive: true, force: true })) - it.each(['link', 'unlink'])( - 'refuses %s before side effects during host reconciliation', - async (operation) => { - const environments = readPersistedEnvironmentStore(userDataPath).environments - const persisted = environments.find((entry) => entry.id === environmentId) - if (!persisted) { - throw new Error('missing environment') - } - writeRuntimeEnvironmentSidecarEntry(userDataPath, environments, persisted, { - reconciliation: { - version: 1, - stage: 'prepared', - requestId: 'reconciliation', - canonicalEnvironmentId: environmentId, - runtimeId: 'host-runtime', - preparedAt: 1, - registrations: [ - { environmentId, authorityDigest: 'a'.repeat(64) }, - { environmentId: 'peer', authorityDigest: 'b'.repeat(64) } - ] - } - }) - await expect( - operation === 'link' ? linkRuntimeSshAccess(userDataPath, request()) : unlink() - ).rejects.toThrow('reconciliation') - expect(mocks.connect).not.toHaveBeenCalled() - expect(mocks.start).not.toHaveBeenCalled() - expect(mocks.close).not.toHaveBeenCalled() - expect(mocks.flush).not.toHaveBeenCalled() - } - ) - it('cancels a pending connect and starts no tunnel when the link is aborted', async () => { const controller = new AbortController() mocks.connect.mockImplementationOnce( @@ -238,38 +205,6 @@ describe('independent runtime SSH access coordinator', () => { expect(target.orcadFence).toBeUndefined() }) - it('retries verification failure with the same durable intent', async () => { - mocks.verify.mockRejectedValueOnce(new Error('unverifiable')) - await expect(linkRuntimeSshAccess(userDataPath, request())).rejects.toThrow() - await linkRuntimeSshAccess(userDataPath, request()) - expect(current().sshAccess).toBeDefined() - }) - - it.each(['host', 'generation', 'owner'] as const)( - 'fences %s reassignment during authenticated proof', - async (field) => { - mocks.verify.mockImplementationOnce(async () => { - target = { - ...target, - ...(field === 'host' - ? { host: 'elsewhere' } - : field === 'generation' - ? { generation: 4 } - : { orcadFence: { environmentId: 'other' } }) - } - return { - verifiedRuntimeId: 'runtime', - verifiedConnection: pairedRuntimeConnectionFromOffer(pairing) - } - }) - await expect(linkRuntimeSshAccess(userDataPath, request())).rejects.toThrow('changed') - expect(current().sshAccess).toBeUndefined() - expect(mocks.close).toHaveBeenCalled() - await expect(unlink('request')).rejects.toThrow('changed') - expect(events).not.toContain('release') - } - ) - it.each([1, 2])('never connects when durable flush %s fails', async (flushNumber) => { if (flushNumber === 2) { mocks.flush.mockResolvedValueOnce(undefined) diff --git a/src/main/ssh/runtime-ssh-access.ts b/src/main/ssh/runtime-access/runtime-ssh-access.ts similarity index 89% rename from src/main/ssh/runtime-ssh-access.ts rename to src/main/ssh/runtime-access/runtime-ssh-access.ts index b2086838d62..ffb4191e02d 100644 --- a/src/main/ssh/runtime-ssh-access.ts +++ b/src/main/ssh/runtime-access/runtime-ssh-access.ts @@ -3,31 +3,31 @@ import { RuntimeSshAccessUnlinkRequestSchema, type RuntimeSshAccessLinkRequest, type RuntimeSshAccessUnlinkRequest -} from '../../shared/runtime-ssh-access' -import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { assertRuntimeEnvironmentNotReconciling } from '../../shared/remote-runtime/host-catalog/runtime-environment-reconciliation-record' -import { redactRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' +} from '../../../shared/runtime-ssh-access' +import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { assertRuntimeEnvironmentNotReconciling } from '../../../shared/remote-runtime/host-catalog/runtime-environment-reconciliation-record' +import { redactRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { cancelRuntimeEnvironmentSshAccessLink, completeRuntimeEnvironmentSshAccessUnlink, linkVerifiedRuntimeEnvironmentSshAccess, prepareRuntimeEnvironmentSshAccessLink, prepareRuntimeEnvironmentSshAccessUnlink -} from '../../shared/remote-runtime/host-store/runtime-environment-ssh-access-store' -import { getManagedOrcadFenceEnvironmentId } from '../../shared/managed-orcad-ssh-owner' -import type { SshTarget } from '../../shared/ssh-types' -import { runTargetLifecycle } from '../ipc/ssh/ssh-target-lifecycle-queue' -import { requireManagedOrcadInfrastructure } from '../managed-server/lifecycle/orcad-managed-runtime-context' +} from '../../../shared/remote-runtime/host-store/runtime-environment-ssh-access-store' +import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' +import type { SshTarget } from '../../../shared/ssh-types' +import { runTargetLifecycle } from '../../ipc/ssh/ssh-target-lifecycle-queue' +import { requireManagedOrcadInfrastructure } from '../../managed-server/lifecycle/orcad-managed-runtime-context' import { closeOrcadManagedTunnel, ensureOrcadManagedTunnel, startOrcadManagedTunnel -} from '../managed-server/lifecycle/orcad-managed-tunnel' +} from '../../managed-server/lifecycle/orcad-managed-tunnel' import { verifyRuntimeEnvironmentSshTunnel } from './runtime-ssh-access-verification' import { fingerprintRuntimeSshTarget } from './runtime-ssh-target-fingerprint' -import { orcadTargetBlockerMessage } from './targets/ssh-target-orcad-claims' -import { dependentStateSummary } from './targets/ssh-target-orcad-dependents' -import type { OrcadMigrationBlocker } from '../../shared/orcad-migration/orcad-migration-preflight' +import { orcadTargetBlockerMessage } from '../targets/ssh-target-orcad-claims' +import { dependentStateSummary } from '../targets/ssh-target-orcad-dependents' +import type { OrcadMigrationBlocker } from '../../../shared/orcad-migration/orcad-migration-preflight' type TargetClaims = ReturnType['claims'] diff --git a/src/main/ssh/runtime-ssh-target-fingerprint.ts b/src/main/ssh/runtime-access/runtime-ssh-target-fingerprint.ts similarity index 92% rename from src/main/ssh/runtime-ssh-target-fingerprint.ts rename to src/main/ssh/runtime-access/runtime-ssh-target-fingerprint.ts index ef19b1bdaa4..8a422274569 100644 --- a/src/main/ssh/runtime-ssh-target-fingerprint.ts +++ b/src/main/ssh/runtime-access/runtime-ssh-target-fingerprint.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' export function fingerprintRuntimeSshTarget(target: SshTarget): string { return createHash('sha256') diff --git a/src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts b/src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts deleted file mode 100644 index e893fa079d9..00000000000 --- a/src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer' -import { encodeFrame, encodeKeepAliveFrame, MessageType } from './remote-exec/remote-frame-protocol' -import { HEADER_LENGTH } from '../../shared/relay-frame-decoder' - -type MockTransport = MultiplexerTransport & { - data: (chunk: Buffer) => void - written: Buffer[] - pauseReads: ReturnType - resumeReads: ReturnType -} - -type MuxInternals = { - nextOutgoingSeq: number - highestAckedBySelf: number - lastReceivedAt: number - decoderReadPaused: boolean - unackedTimestamps: Map -} - -function createTransport(): MockTransport { - let onData: (chunk: Buffer) => void = () => {} - const written: Buffer[] = [] - const pauseReads = vi.fn() - const resumeReads = vi.fn() - return { - write: (data) => { - written.push(data) - }, - onData: (callback) => { - onData = callback - }, - onClose: () => {}, - pauseReads, - resumeReads, - data: (chunk) => onData(chunk), - written - } -} - -function internals(mux: SshChannelMultiplexer): MuxInternals { - return mux as unknown as MuxInternals -} - -describe('SshChannelMultiplexer backpressure hardening', () => { - let transport: MockTransport - let mux: SshChannelMultiplexer - - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(0) - transport = createTransport() - mux = new SshChannelMultiplexer(transport) - }) - - afterEach(() => { - mux.dispose() - vi.restoreAllMocks() - vi.useRealTimers() - }) - - it('clamps ack=0xffffffff and deletes only retained sequence keys', () => { - mux.notify('one') - mux.notify('two') - const state = internals(mux) - const deleteSpy = vi.spyOn(state.unackedTimestamps, 'delete') - - transport.data(encodeKeepAliveFrame(1, 0xffffffff)) - - expect(deleteSpy).toHaveBeenCalledTimes(2) - expect(state.unackedTimestamps.size).toBe(0) - expect(state.highestAckedBySelf).toBe(state.nextOutgoingSeq - 1) - }) - - it('caps timestamps while preserving a reserved liveness entry', () => { - for (let i = 0; i < 5000; i += 1) { - mux.notify('bounded') - } - const state = internals(mux) - - expect(state.unackedTimestamps.size).toBe(4095) - expect(state.unackedTimestamps.has(1)).toBe(true) - void mux.probeLiveness(60_000) - expect(state.unackedTimestamps.size).toBe(4096) - void mux.probeLiveness(60_000) - expect(state.unackedTimestamps.size).toBe(4096) - }) - - it('suppresses timeout while self-paused and rebases both clocks on resume', () => { - mux.dispose() - const continuations: (() => void)[] = [] - vi.spyOn(globalThis, 'setImmediate').mockImplementation( - (callback: (...args: never[]) => void) => { - continuations.push(callback) - return {} as NodeJS.Immediate - } - ) - transport = createTransport() - mux = new SshChannelMultiplexer(transport) - mux.notify('tracked') - - const incoming = Buffer.concat( - Array.from({ length: 65 }, (_, index) => encodeKeepAliveFrame(index + 1, 0)) - ) - transport.data(incoming) - const state = internals(mux) - - expect(state.decoderReadPaused).toBe(true) - expect(transport.pauseReads).toHaveBeenCalledTimes(1) - expect(continuations).toHaveLength(1) - - vi.advanceTimersByTime(25_000) - expect(mux.isDisposed()).toBe(false) - - continuations.shift()!() - const resumedAt = Date.now() - expect(state.decoderReadPaused).toBe(false) - expect(transport.resumeReads).toHaveBeenCalledTimes(1) - expect(state.lastReceivedAt).toBe(resumedAt) - expect(new Set(state.unackedTimestamps.values())).toEqual(new Set([resumedAt])) - }) - - it('keeps frame dispatch ordered across a decoder continuation', () => { - const seen: number[] = [] - mux.onNotification((_method, params) => seen.push(params.index as number)) - const frames = Array.from({ length: 65 }, (_, index) => { - const payload = Buffer.from( - JSON.stringify({ jsonrpc: '2.0', method: 'ordered', params: { index } }) - ) - return encodeFrame(MessageType.Regular, index + 1, 0, payload) - }) - - transport.data(Buffer.concat(frames)) - expect(seen).toEqual(Array.from({ length: 64 }, (_, index) => index)) - vi.runAllTicks() - vi.advanceTimersByTime(0) - expect(seen).toEqual(Array.from({ length: 65 }, (_, index) => index)) - }) - - it('prioritizes source ACK and control while preserving FIFO and ordinary progress', async () => { - mux.dispose() - const written: Buffer[] = [] - let drain = (): void => {} - let deliver = (_data: Buffer): void => {} - transport = { - write: (data) => { - written.push(data) - return written.length !== 1 - }, - onDrain: (callback) => { - drain = callback - }, - onData: (callback) => { - deliver = callback - }, - onClose: vi.fn(), - pauseReads: vi.fn<() => void>(), - resumeReads: vi.fn<() => void>(), - data: vi.fn<(chunk: Buffer) => void>(), - written, - close: vi.fn() - } - mux = new SshChannelMultiplexer(transport) - mux.onRequest('client.control', () => ({ accepted: true })) - const controller = new AbortController() - - mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-1' }) - mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-2' }) - mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-3' }) - mux.notify('pty.ackData', { acknowledgements: [] }) - const request = mux.request('fs.scan', {}, { signal: controller.signal }) - controller.abort() - mux.notify('pty.exit', { id: 'pty-1', code: 0 }) - const remoteRequest = Buffer.from( - JSON.stringify({ jsonrpc: '2.0', id: 91, method: 'client.control' }) - ) - deliver(encodeFrame(MessageType.Regular, 1, 0, remoteRequest)) - await Promise.resolve() - await Promise.resolve() - - expect(written).toHaveLength(1) - drain() - const payloads = written.map((frame) => - JSON.parse(frame.subarray(HEADER_LENGTH, HEADER_LENGTH + frame.readUInt32BE(9)).toString()) - ) - expect( - payloads.map((payload) => - payload.method === 'pty.data' - ? `pty.data:${payload.params.data}` - : (payload.method ?? `response:${payload.id}`) - ) - ).toEqual([ - 'pty.data:ordinary-1', - 'pty.ackData', - 'fs.scan', - 'rpc.cancel', - 'pty.exit', - 'pty.data:ordinary-2', - 'response:91', - 'pty.data:ordinary-3' - ]) - await expect(request).rejects.toMatchObject({ name: 'AbortError' }) - }) -}) diff --git a/src/main/ssh/ssh-credential-decline.test.ts b/src/main/ssh/ssh-credential-decline.test.ts deleted file mode 100644 index eea869ee2e9..00000000000 --- a/src/main/ssh/ssh-credential-decline.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { - clearSshCredentialDeclinedForEnvironment, - isSshCredentialDeclined, - recordSshCredentialDeclined, - resetSshCredentialDeclinesForTests -} from './ssh-credential-decline' - -const link = { - requestId: 'request-1', - sshTargetId: 'ssh-1', - sshTargetGeneration: 1, - localPort: 41000, - remotePort: 6768 -} - -describe('clearSshCredentialDeclinedForEnvironment', () => { - beforeEach(() => { - resetSshCredentialDeclinesForTests() - recordSshCredentialDeclined('ssh-1') - }) - - it('lifts the decline for the SSH host a managed server is reached through', () => { - clearSshCredentialDeclinedForEnvironment({ orcadDeployment: link }) - expect(isSshCredentialDeclined('ssh-1')).toBe(false) - }) - - it('lifts the decline for a server with independent SSH access', () => { - clearSshCredentialDeclinedForEnvironment({ - sshAccess: { ...link, endpointId: 'ssh', previousPreferredEndpointId: 'direct' } - }) - expect(isSshCredentialDeclined('ssh-1')).toBe(false) - }) - - it('leaves other hosts alone for a server not reached over SSH', () => { - clearSshCredentialDeclinedForEnvironment({}) - expect(isSshCredentialDeclined('ssh-1')).toBe(true) - }) -}) diff --git a/src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts b/src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts deleted file mode 100644 index 2112001b2f2..00000000000 --- a/src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { Server, utils, type Connection } from 'ssh2' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { SshConnection } from './connection/ssh-connection' -import { INITIAL_RETRY_DELAY_MS } from './connection/ssh-connection-timing' -import { - createCallbacks, - createResolvedConfig, - createTarget -} from './connection/ssh-connection-test-fixtures' -import { initSshHostKeyStoreFile } from './ssh-host-key-store' -import { resolveWithSshG } from './config/ssh-g-config-resolution' -import type * as SshGConfigResolution from './config/ssh-g-config-resolution' - -vi.mock('./config/ssh-g-config-resolution', async (importOriginal) => ({ - ...(await importOriginal()), - resolveWithSshG: vi.fn() -})) - -const PASSWORD = 'fixture-password' -// Longer than the connection's 2s retry delay, so a retry would start while the prompt is open. -const USER_ANSWER_DELAY_MS = 3_000 - -/** Keep the original prompt open across LoginGraceTime expiry; socket loss must not replace a pending user answer. */ -describe('a password prompt the server gives up on', () => { - let profile: string - let server: Server - let conn: SshConnection | undefined - const sockets = new Set() - - beforeEach(() => { - profile = mkdtempSync(join(tmpdir(), 'orca-login-grace-wire-')) - initSshHostKeyStoreFile(join(profile, 'host-keys.json')) - vi.stubEnv('SSH_AUTH_SOCK', '') - vi.mocked(resolveWithSshG).mockResolvedValue( - createResolvedConfig({ - hostname: '127.0.0.1', - identitiesOnly: true, - identityAgent: 'none', - proxyUseFdpass: false, - strictHostKeyChecking: 'no' - }) - ) - }) - - afterEach(async () => { - await conn?.disconnect() - conn = undefined - for (const socket of sockets) { - socket.end() - } - sockets.clear() - if (server) { - await new Promise((resolve) => server.close(() => resolve())) - } - vi.unstubAllEnvs() - rmSync(profile, { recursive: true, force: true }) - }) - - /** Prompt on every login; abandon the first server-side. */ - async function startHost(): Promise { - let logins = 0 - server = new Server( - { hostKeys: [utils.generateKeyPairSync('ecdsa', { bits: 256 }).private] }, - (socket) => { - sockets.add(socket) - socket.on('error', () => {}) - socket.on('close', () => sockets.delete(socket)) - const login = ++logins - socket.on('authentication', (context) => { - if (context.method !== 'keyboard-interactive') { - context.reject(['keyboard-interactive']) - return - } - context.prompt([{ prompt: 'Password: ', echo: false }], (answers) => { - if (answers[0] === PASSWORD) { - context.accept() - } else { - context.reject(['keyboard-interactive']) - } - }) - if (login === 1) { - setTimeout(() => socket.end(), 100) - } - }) - socket.on('ready', () => socket.on('session', (accept) => accept())) - } - ) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('Fixture did not bind') - } - return address.port - } - - /** Behaves like the real dialog: an abort closes it, otherwise the user answers late. */ - function slowUser(answer: string | null) { - return vi.fn( - ( - _targetId: string, - _kind: string, - _detail: string, - _echo?: boolean, - signal?: AbortSignal - ): Promise => - new Promise((resolve) => { - const timer = setTimeout(() => resolve(answer), USER_ANSWER_DELAY_MS) - signal?.addEventListener('abort', () => { - clearTimeout(timer) - resolve(null) - }) - }) - ) - } - - it('keeps the open prompt and signs in with what the user typed', async () => { - const port = await startHost() - const onCredentialRequest = slowUser(PASSWORD) - conn = new SshConnection( - createTarget({ host: '127.0.0.1', port }), - createCallbacks({ onCredentialRequest }) - ) - - const connecting = conn.connect() - void connecting.catch(() => {}) - await vi.waitFor(() => expect(onCredentialRequest).toHaveBeenCalled()) - const answered = onCredentialRequest.mock.results[0].value - expect(await answered).toBe(PASSWORD) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'], shouldClearNativeTimers: true }) - try { - await vi.advanceTimersByTimeAsync(0) - // Answered but not yet used by the retry: a background dial must not replace it. - await vi.waitFor(() => expect(conn?.isAwaitingCredential()).toBe(true), { timeout: 1_000 }) - await vi.advanceTimersByTimeAsync(INITIAL_RETRY_DELAY_MS) - await connecting - - expect(conn.getState().status).toBe('connected') - expect(onCredentialRequest).toHaveBeenCalledTimes(1) - expect(conn.isAwaitingCredential()).toBe(false) - } finally { - vi.clearAllTimers() - vi.useRealTimers() - } - }, 15_000) -}) diff --git a/src/main/ssh/ssh-host-platform-memo.test.ts b/src/main/ssh/ssh-host-platform-memo.test.ts deleted file mode 100644 index 4249cb1144d..00000000000 --- a/src/main/ssh/ssh-host-platform-memo.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import { - knownSshHostPlatform, - rememberSshHostPlatform, - resetSshHostPlatformMemoForTests -} from './ssh-host-platform-memo' -import { getRemoteHostPlatform } from './ssh-remote-platform' - -describe('ssh host platform memo', () => { - beforeEach(() => { - resetSshHostPlatformMemoForTests() - }) - - it('records the libc flavor, and keeps a probed one when a later report has none', () => { - expect(knownSshHostPlatform('ssh-1')).toBeNull() - rememberSshHostPlatform('ssh-1', getRemoteHostPlatform('linux-arm64'), 'linux-arm64-musl') - expect(knownSshHostPlatform('ssh-1')).toEqual({ os: 'linux', arch: 'arm64', libc: 'musl' }) - rememberSshHostPlatform('ssh-1', getRemoteHostPlatform('linux-arm64'), null) - expect(knownSshHostPlatform('ssh-1')?.libc).toBe('musl') - - rememberSshHostPlatform('ssh-2', getRemoteHostPlatform('win32-x64'), 'win32-x64') - expect(knownSshHostPlatform('ssh-2')).toEqual({ os: 'win32', arch: 'x64', libc: 'none' }) - }) -}) diff --git a/src/main/ssh/ssh-keyboard-interactive-wire.test.ts b/src/main/ssh/ssh-keyboard-interactive-wire.test.ts deleted file mode 100644 index 0fff6b62327..00000000000 --- a/src/main/ssh/ssh-keyboard-interactive-wire.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { Server, utils, type Connection } from 'ssh2' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { SshConnection } from './connection/ssh-connection' -import { - createCallbacks, - createResolvedConfig, - createTarget -} from './connection/ssh-connection-test-fixtures' -import { initSshHostKeyStoreFile } from './ssh-host-key-store' -import { resolveWithSshG } from './config/ssh-g-config-resolution' -import type * as SshGConfigResolution from './config/ssh-g-config-resolution' - -vi.mock('./config/ssh-g-config-resolution', async (importOriginal) => ({ - ...(await importOriginal()), - resolveWithSshG: vi.fn() -})) - -describe('keyboard-interactive over a real SSH socket', () => { - let profile: string - let server: Server - let conn: SshConnection | undefined - const sockets = new Set() - - beforeEach(() => { - profile = mkdtempSync(join(tmpdir(), 'orca-keyboard-wire-')) - initSshHostKeyStoreFile(join(profile, 'host-keys.json')) - vi.stubEnv('SSH_AUTH_SOCK', '') - vi.mocked(resolveWithSshG).mockResolvedValue( - createResolvedConfig({ - hostname: '127.0.0.1', - identitiesOnly: true, - identityAgent: 'none', - proxyUseFdpass: false, - strictHostKeyChecking: 'no' - }) - ) - }) - - afterEach(async () => { - await conn?.disconnect() - for (const socket of sockets) { - socket.end() - } - sockets.clear() - if (server) { - await new Promise((resolve) => server.close(() => resolve())) - } - vi.unstubAllEnvs() - rmSync(profile, { recursive: true, force: true }) - }) - - it.each([false, true])( - 'completes password then MFA with empty push response=%s', - async (empty) => { - const received: string[][] = [] - const methods: string[] = [] - server = new Server( - { hostKeys: [utils.generateKeyPairSync('ecdsa', { bits: 256 }).private] }, - (socket) => { - sockets.add(socket) - socket.on('error', () => {}) - socket.on('close', () => sockets.delete(socket)) - let passwordAccepted = false - socket.on('authentication', (context) => { - methods.push(context.method) - if (context.method === 'password' && context.password === 'fixture-password') { - passwordAccepted = true - context.reject(['keyboard-interactive'], true) - } else if (context.method === 'keyboard-interactive' && passwordAccepted) { - context.prompt( - [ - { - prompt: empty ? 'Press Enter for push:' : 'Passcode or option (1-2):', - echo: true - } - ], - 'MFA', - 'Choose verification:', - (answers) => { - received.push(answers) - if (answers[0] === (empty ? '' : '1')) { - context.accept() - } else { - context.reject(['keyboard-interactive']) - } - } - ) - } else { - context.reject(['password']) - } - }) - } - ) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('Fixture did not bind') - } - const onCredentialRequest = vi.fn(async (_id: string, kind: string) => - kind === 'password' ? 'fixture-password' : empty ? '' : '1' - ) - conn = new SshConnection( - createTarget({ host: '127.0.0.1', port: address.port }), - createCallbacks({ onCredentialRequest }) - ) - await conn.connect() - expect(conn.getState().status).toBe('connected') - expect(received).toEqual([[empty ? '' : '1']]) - expect(methods).toContain('password') - expect(onCredentialRequest).toHaveBeenLastCalledWith( - 'target-1', - 'keyboard-interactive', - `MFA\nChoose verification:\n${empty ? 'Press Enter for push:' : 'Passcode or option (1-2):'}`, - true, - expect.any(AbortSignal) - ) - } - ) -}) diff --git a/src/main/ssh/ssh-quit-abort-upload.test.ts b/src/main/ssh/ssh-quit-abort-upload.test.ts deleted file mode 100644 index ba4b2233de6..00000000000 --- a/src/main/ssh/ssh-quit-abort-upload.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { EventEmitter } from 'node:events' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { Writable } from 'node:stream' -import { describe, expect, it, vi } from 'vitest' -import type { SFTPWrapper } from 'ssh2' -import type { SshTarget } from '../../shared/ssh-types' -import { uploadSshDirectory } from './connection/ssh-connection-file-transfers' - -const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } - -function flushingSftp(): SFTPWrapper { - const sftp = Object.assign(new EventEmitter(), { - mkdir: (_path: string, cb: (err?: Error | null) => void) => cb(null), - createWriteStream: () => - new Writable({ - write(_chunk, _encoding, callback) { - callback() - }, - final() {} - }), - end: () => sftp.emit('close') - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the upload calls only these members. - return sftp as unknown as SFTPWrapper -} - -describe('quitting during an orcad bundle upload', () => { - it("aborts through the connection's teardown signal with no uncaught exception", async () => { - const localDir = await mkdtemp(join(tmpdir(), 'orca-quit-upload-')) - // The disconnect aborts this controller, exactly as SshConnection.disconnect does. - const teardown = new AbortController() - const uncaught = vi.fn() - process.prependListener('uncaughtException', uncaught) - try { - await writeFile(join(localDir, 'orcad.js'), Buffer.alloc(64 * 1024, 7)) - const upload = uploadSshDirectory( - { - target, - usesSystemSshTransport: () => false, - systemOperationSignal: () => teardown.signal, - systemSshBuildArgsOptions: () => ({}), - sftp: async () => flushingSftp() - }, - localDir, - '/home/u/.orca-remote/orcad-candidate' - ) - const settled = upload.then( - () => 'resolved', - (error: unknown) => (error instanceof Error ? error.name : 'rejected') - ) - await new Promise((resolve) => setTimeout(resolve, 50)) - - teardown.abort() - await expect(settled).resolves.toBe('AbortError') - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(uncaught).not.toHaveBeenCalled() - } finally { - process.off('uncaughtException', uncaught) - await rm(localDir, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/ssh/ssh-tcp-forwarding-probe.test.ts b/src/main/ssh/ssh-tcp-forwarding-probe.test.ts deleted file mode 100644 index 0b2a7d2086b..00000000000 --- a/src/main/ssh/ssh-tcp-forwarding-probe.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { createServer, type Server, type Socket } from 'node:net' -import { afterEach, describe, expect, it } from 'vitest' - -import type { ForwardChannelOpenFailure } from './port-forwarding/ssh-port-forward-provider' -import { checkForwardChannel } from './ssh-tcp-forwarding-probe' - -import { lastChannelOpenFailure } from './port-forwarding/system-ssh-port-forward-provider' - -const servers: Server[] = [] -afterEach(async () => { - await Promise.all( - servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))) - ) -}) - -/** Model ssh -L: socket behavior represents the remote channel-open result. */ -async function forwardAnswering( - onSocket: (socket: Socket, log: (line: string) => void) => void -): Promise[0]> { - let stderr = '' - const server = createServer((socket) => { - socket.on('error', () => {}) - onSocket(socket, (line) => { - stderr += `${line}\n` - }) - }) - servers.push(server) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - const localPort = typeof address === 'object' && address ? address.port : 0 - return { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the check reads only localPort. - entry: { localPort } as never, - lastChannelOpenFailure: (): ForwardChannelOpenFailure | null => lastChannelOpenFailure(stderr) - } -} - -describe('forward channel check (system SSH)', () => { - it('reads OpenSSH’s administrative refusal as refused, though its listener accepted', async () => { - const forward = await forwardAnswering((socket, log) => { - log('channel 1: open failed: administratively prohibited: open failed') - socket.destroy() - }) - await expect(checkForwardChannel(forward)).resolves.toBe('refused') - }) - - it('reads a connect failure as allowed: sshd dialled, nothing listened yet', async () => { - const forward = await forwardAnswering((socket, log) => { - log('channel 1: open failed: connect failed: Connection refused') - socket.destroy() - }) - await expect(checkForwardChannel(forward)).resolves.toBe('allowed') - }) - - it('reads reply bytes through the channel as allowed', async () => { - const forward = await forwardAnswering((socket) => { - socket.once('data', () => socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')) - }) - await expect(checkForwardChannel(forward)).resolves.toBe('allowed') - }) - - it('is unverifiable for an unexplained drop, a silent open channel, or no channel log', async () => { - const dropped = await forwardAnswering((socket) => socket.destroy()) - await expect(checkForwardChannel(dropped)).resolves.toBe('unverifiable') - const silent = await forwardAnswering((socket) => socket.resume()) - await expect(checkForwardChannel(silent, { channelTimeoutMs: 50 })).resolves.toBe( - 'unverifiable' - ) - await expect(checkForwardChannel({ entry: dropped.entry })).resolves.toBe('unverifiable') - }) - - // Why: a forward still waiting on its own login (a key touch, a prompt) never binds its listener. - it('reports a listener that never came up as not listening', async () => { - const closed = await forwardAnswering(() => {}) - await new Promise((resolve) => servers.pop()?.close(resolve)) - await expect(checkForwardChannel(closed, { listenTimeoutMs: 300 })).resolves.toBe( - 'not-listening' - ) - }) - - // Why: ssh -L binds only after its own login, which a ProxyCommand such as Coder's can stretch well past the channel wait. - it('waits out a slow login and reads the answer once the listener comes up', async () => { - const forward = await forwardAnswering((socket) => { - socket.once('data', () => socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')) - }) - const server = servers.pop() - await new Promise((resolve) => server?.close(resolve)) - const verdict = checkForwardChannel(forward, { channelTimeoutMs: 50, listenTimeoutMs: 5_000 }) - // ast-grep-ignore: test-no-real-time-wait -- a real socket must fail to dial before the listener comes up. - await new Promise((resolve) => setTimeout(resolve, 300)) - server?.listen(forward.entry.localPort, '127.0.0.1') - if (server) { - servers.push(server) - } - await expect(verdict).resolves.toBe('allowed') - }) - - it('stops waiting for the listener once the forward exits', async () => { - const closed = await forwardAnswering(() => {}) - await new Promise((resolve) => servers.pop()?.close(resolve)) - const exited = new AbortController() - const verdict = checkForwardChannel(closed, { signal: exited.signal }) - setTimeout(() => exited.abort(), 100) - await expect(verdict).resolves.toBe('not-listening') - }) -}) diff --git a/src/main/ssh/ssh2-module-load.test.ts b/src/main/ssh/ssh2-module-load.test.ts deleted file mode 100644 index cdb4046076c..00000000000 --- a/src/main/ssh/ssh2-module-load.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { createRequire } from 'node:module' -import { describe, expect, it, vi } from 'vitest' - -const nodeRequire = createRequire(import.meta.url) - -function isSsh2Loaded(): boolean { - return Object.keys(nodeRequire.cache).some((path) => /[\\/]node_modules[\\/]ssh2[\\/]/.test(path)) -} - -describe('ssh2 deferred load', () => { - it('stays unloaded until an agent is first built, which then extends the real BaseAgent', async () => { - // The manager reaches connect, auth, channels and file transfers; the rest sit beside it. - await import('./connection/ssh-connection-manager') - await import('./port-forwarding/ssh2-port-forward-provider') - await import('./sftp-upload') - await import('./sftp-file-upload') - await import('../providers/ssh-filesystem-provider-sftp') - const { observeAgentSigning } = await import('./ssh-agent-sign-observer') - expect(isSsh2Loaded()).toBe(false) - - const agent = observeAgentSigning('/tmp/orca-test-agent.sock', vi.fn()) - - expect(agent).toBeInstanceOf(nodeRequire('ssh2').BaseAgent) - }) -}) diff --git a/src/main/ssh/system-transport/system-ssh-file-binary-transfer.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-file-binary-transfer.ts similarity index 94% rename from src/main/ssh/system-transport/system-ssh-file-binary-transfer.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-file-binary-transfer.ts index 8a44be18072..577b65fa303 100644 --- a/src/main/ssh/system-transport/system-ssh-file-binary-transfer.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-file-binary-transfer.ts @@ -4,21 +4,21 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type { Writable } from 'node:stream' import { pipeline } from 'node:stream/promises' -import type { SshTarget } from '../../../shared/ssh-types' -import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import type { SshTarget } from '../../../../shared/ssh-types' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import { getSystemSshBuildArgsFromOperationOptions, type SystemSshBuildArgsOptions -} from './system-ssh-args' -import { spawnSystemSshCommand } from './system-ssh-command' -import { isWindowsRemoteHost, type RemoteHostPlatform } from '../ssh-remote-platform' -import { powerShellCommand } from '../ssh-remote-powershell' -import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' +} from '../system-ssh-args' +import { spawnSystemSshCommand } from '../system-ssh-command' +import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' +import { powerShellCommand } from '../../remote-exec/ssh-remote-powershell' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../../shared/powershell-native-argument' import { awaitWithSystemSshAbort, throwIfAborted, waitForChannelClose -} from './system-ssh-operation-lifecycle' +} from '../system-ssh-operation-lifecycle' import { writeWindowsRemoteFile, type WindowsWriteSource diff --git a/src/main/ssh/system-transport/system-ssh-file-transfer.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-file-transfer.ts similarity index 93% rename from src/main/ssh/system-transport/system-ssh-file-transfer.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-file-transfer.ts index 96909bd15a6..2649329255c 100644 --- a/src/main/ssh/system-transport/system-ssh-file-transfer.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-file-transfer.ts @@ -1,24 +1,24 @@ -import { DirectoryTransferBudget } from '../ssh-directory-transfer-budget' +import { DirectoryTransferBudget } from '../../file-transfer/ssh-directory-transfer-budget' import { spawn } from 'node:child_process' import { lstat, opendir } from 'node:fs/promises' import { join as pathJoin } from 'node:path' import { pipeline } from 'node:stream/promises' -import type { SshTarget } from '../../../shared/ssh-types' -import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { wrapRemoteCommandForPosixShell } from '../ssh-posix-command-wrapper' -import { findSystemSsh } from './system-ssh-binary' +import type { SshTarget } from '../../../../shared/ssh-types' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { wrapRemoteCommandForPosixShell } from '../../remote-exec/ssh-posix-command-wrapper' +import { findSystemSsh } from '../system-ssh-binary' import { buildSshArgs, getSystemSshBuildArgsFromOperationOptions, type SystemSshBuildArgsOptions -} from './system-ssh-args' -import { spawnSystemSshCommand } from './system-ssh-command' +} from '../system-ssh-args' +import { spawnSystemSshCommand } from '../system-ssh-command' import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../ssh-remote-platform' -import { powerShellCommand } from '../ssh-remote-powershell' +} from '../../remote-host/ssh-remote-platform' +import { powerShellCommand } from '../../remote-exec/ssh-remote-powershell' import { awaitWithSystemSshAbort, killProcess, @@ -26,7 +26,7 @@ import { waitForChannelClose, waitForProcess, type ProcessResult -} from './system-ssh-operation-lifecycle' +} from '../system-ssh-operation-lifecycle' import { uploadFileViaSystemSsh, writeBufferViaSystemSsh } from './system-ssh-file-binary-transfer' import { WINDOWS_STDIN_WRITE_CHUNK_BYTES, diff --git a/src/main/ssh/system-transport/system-ssh-sftp-args.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts similarity index 57% rename from src/main/ssh/system-transport/system-ssh-sftp-args.test.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts index 59421d3b790..0585a3f5820 100644 --- a/src/main/ssh/system-transport/system-ssh-sftp-args.test.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts @@ -1,10 +1,6 @@ /** SSH flags can silently change meaning in SFTP; unknown translations must decline to another transport. */ import { describe, expect, it } from 'vitest' -import { - SftpArgTranslationError, - translateSshArgsToSftpArgs, - withSftpKeepalive -} from './system-ssh-sftp-args' +import { SftpArgTranslationError, translateSshArgsToSftpArgs } from './system-ssh-sftp-args' describe('translateSshArgsToSftpArgs', () => { it('translates the whole unclaimed-alias shape buildSshArgs emits', () => { @@ -46,34 +42,6 @@ describe('translateSshArgsToSftpArgs', () => { ) }) - it('passes through the flags both clients spell the same way', () => { - const args = translateSshArgsToSftpArgs([ - '-F', - '/tmp/config', - '-o', - 'BatchMode=yes', - '-i', - '/tmp/key', - '-J', - 'jump.example', - '--', - 'dev@win.example' - ]) - - expect(args).toEqual([ - '-F', - '/tmp/config', - '-o', - 'BatchMode=yes', - '-i', - '/tmp/key', - '-J', - 'jump.example', - '--', - 'dev@win.example' - ]) - }) - it('takes everything after -- as the destination without reinterpreting it', () => { // A host literally named `-p` is not a flag once `--` has been seen. expect(translateSshArgsToSftpArgs(['--', '-p'])).toEqual(['--', '-p']) @@ -88,24 +56,3 @@ describe('translateSshArgsToSftpArgs', () => { expect(() => translateSshArgsToSftpArgs(['-o'])).toThrow(SftpArgTranslationError) }) }) - -describe('withSftpKeepalive', () => { - it('asks OpenSSH to notice a dead peer, since the transfer itself has no wall-clock bound', () => { - expect(withSftpKeepalive(['--', 'host'])).toEqual([ - '-o', - 'ServerAliveInterval=15', - '-o', - 'ServerAliveCountMax=3', - '--', - 'host' - ]) - }) - - it('leaves a caller-stated keepalive policy alone', () => { - const args = withSftpKeepalive(['-o', 'ServerAliveInterval=60', '--', 'host']) - - expect(args.filter((arg) => arg.startsWith('ServerAliveInterval'))).toEqual([ - 'ServerAliveInterval=60' - ]) - }) -}) diff --git a/src/main/ssh/system-transport/system-ssh-sftp-args.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.ts similarity index 100% rename from src/main/ssh/system-transport/system-ssh-sftp-args.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.ts diff --git a/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts similarity index 100% rename from src/main/ssh/system-transport/system-ssh-sftp-path.test.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts diff --git a/src/main/ssh/system-transport/system-ssh-sftp-path.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.ts similarity index 93% rename from src/main/ssh/system-transport/system-ssh-sftp-path.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.ts index a23fd0bc903..71fcf4fbc9b 100644 --- a/src/main/ssh/system-transport/system-ssh-sftp-path.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.ts @@ -1,4 +1,4 @@ -import { normalizeWindowsRemotePath } from '../ssh-remote-platform' +import { normalizeWindowsRemotePath } from '../../remote-host/ssh-remote-platform' /** Unsupported paths decline this operation to another transport. */ export class UnsupportedSftpPathError extends Error { diff --git a/src/main/ssh/system-transport/system-ssh-sftp-transfer.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-transfer.ts similarity index 95% rename from src/main/ssh/system-transport/system-ssh-sftp-transfer.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-sftp-transfer.ts index 5729c2ddc20..0c78e55d55e 100644 --- a/src/main/ssh/system-transport/system-ssh-sftp-transfer.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-transfer.ts @@ -1,8 +1,8 @@ import { accessSync, constants, existsSync, statSync } from 'node:fs' import { posix, win32 } from 'node:path' -import type { SshTarget } from '../../../shared/ssh-types' -import { buildSshArgs, type SystemSshBuildArgsOptions } from './system-ssh-args' -import { findSystemSsh } from './system-ssh-binary' +import type { SshTarget } from '../../../../shared/ssh-types' +import { buildSshArgs, type SystemSshBuildArgsOptions } from '../system-ssh-args' +import { findSystemSsh } from '../system-ssh-binary' import { SftpArgTranslationError, translateSshArgsToSftpArgs, @@ -13,7 +13,7 @@ import { toSftpRemotePath, UnsupportedSftpPathError } from './system-ssh-sftp-path' -import { SystemSshCommandExitError, throwIfAborted } from './system-ssh-operation-lifecycle' +import { SystemSshCommandExitError, throwIfAborted } from '../system-ssh-operation-lifecycle' import { runProcess } from '@orca/process-host' /** Subsystem refusal permits transport fallback. */ diff --git a/src/main/ssh/system-transport/system-ssh-upload-plan-budget.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-upload-plan-budget.test.ts similarity index 53% rename from src/main/ssh/system-transport/system-ssh-upload-plan-budget.test.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-upload-plan-budget.test.ts index 4e95b78fab6..93254020aeb 100644 --- a/src/main/ssh/system-transport/system-ssh-upload-plan-budget.test.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-upload-plan-budget.test.ts @@ -7,34 +7,7 @@ vi.mock('node:fs/promises', async (load) => ({ lstat: stats })) import { collectLocalUploadPlan } from './system-ssh-file-transfer' -import { getRemoteHostPlatform } from '../ssh-remote-platform' - -it('stops the upload producer at its retained-plan ceiling before any transfer starts', async () => { - let visited = 0 - let closed = false - stats.mockResolvedValue({ - isSymbolicLink: () => false, - isFile: () => true, - isDirectory: () => false - }) - directory.mockImplementation(async () => - (async function* () { - try { - for (let index = 0; index < 1_000_000; index++) { - visited++ - yield { name: `file-${index}.txt` } - } - } finally { - closed = true - } - })() - ) - await expect( - collectLocalUploadPlan('/local', 'C:/remote', getRemoteHostPlatform('win32-x64'), undefined) - ).rejects.toThrow('transfer plan is too large') - expect(visited).toBeLessThanOrEqual(100_000) - expect(closed).toBe(true) -}) +import { getRemoteHostPlatform } from '../../remote-host/ssh-remote-platform' it('closes an in-progress upload directory when canceled', async () => { const controller = new AbortController() diff --git a/src/main/ssh/system-transport/system-ssh-windows-file-write.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-file-write.ts similarity index 95% rename from src/main/ssh/system-transport/system-ssh-windows-file-write.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-windows-file-write.ts index 7e4fcd1971e..7e7340954e2 100644 --- a/src/main/ssh/system-transport/system-ssh-windows-file-write.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-file-write.ts @@ -1,7 +1,7 @@ import { randomBytes } from 'node:crypto' -import { powerShellCommand } from '../ssh-remote-powershell' -import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' -import { normalizeWindowsRemotePath } from '../ssh-remote-platform' +import { powerShellCommand } from '../../remote-exec/ssh-remote-powershell' +import { quotePowerShellLiteral as powerShellLiteral } from '../../../../shared/powershell-native-argument' +import { normalizeWindowsRemotePath } from '../../remote-host/ssh-remote-platform' /** Unique staging names avoid locks from prior writers: contact loss never proves their death (docs/reference/ssh-execution-boundary.md). */ export const WINDOWS_STAGED_WRITE_SUFFIX = '.orca-partial' diff --git a/src/main/ssh/system-transport/system-ssh-windows-upload.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts similarity index 56% rename from src/main/ssh/system-transport/system-ssh-windows-upload.test.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts index e13b2f7ab85..5a98be2b7ec 100644 --- a/src/main/ssh/system-transport/system-ssh-windows-upload.test.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts @@ -6,15 +6,13 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { PassThrough, Writable } from 'node:stream' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as SystemSshOperationLifecycle from './system-ssh-operation-lifecycle' -const { spawnSystemSshCommandMock, waitForChannelCloseSpy, runProcessMock } = vi.hoisted(() => ({ +const { spawnSystemSshCommandMock, runProcessMock } = vi.hoisted(() => ({ spawnSystemSshCommandMock: vi.fn(), - waitForChannelCloseSpy: vi.fn(), runProcessMock: vi.fn() })) -vi.mock('./system-ssh-command', () => ({ +vi.mock('../system-ssh-command', () => ({ spawnSystemSshCommand: spawnSystemSshCommandMock })) @@ -22,18 +20,11 @@ vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -// Delegates to the real implementation; the spy only records whether each wait was given a bound. -vi.mock('./system-ssh-operation-lifecycle', async (importActual) => { - const actual = (await importActual()) as typeof SystemSshOperationLifecycle - waitForChannelCloseSpy.mockImplementation(actual.waitForChannelClose) - return { ...actual, waitForChannelClose: waitForChannelCloseSpy } -}) - import { uploadFileViaSystemSsh, writeBufferViaSystemSsh } from './system-ssh-file-binary-transfer' import { WINDOWS_STAGED_WRITE_SUFFIX } from './system-ssh-windows-file-write' -import { waitForChannelClose } from './system-ssh-operation-lifecycle' + import * as windowsFileWrite from './system-ssh-windows-file-write' -import { getRemoteHostPlatform } from '../ssh-remote-platform' +import { getRemoteHostPlatform } from '../../remote-host/ssh-remote-platform' import { clearWindowsRemoteWriteCapabilitiesForTests, getWindowsRemoteWriteCapabilities @@ -44,7 +35,7 @@ import { WINDOWS_STDIN_WRITE_TIMEOUT_MS, writeWindowsRemoteFile } from './system-ssh-windows-write-strategy' -import type { SshTarget } from '../../../shared/ssh-types' +import type { SshTarget } from '../../../../shared/ssh-types' type FakeChannel = EventEmitter & { stdin: Writable @@ -99,8 +90,7 @@ const fileWrites = (): RecordedCommand[] => commands.filter((command) => command.script.includes('OpenStandardInput')) const writtenPath = (command: RecordedCommand): string => /\$path = '((?:[^']|'')*)'/.exec(command.script)?.[1]?.replace(/''/g, "'") ?? '' -const fileMode = (command: RecordedCommand): string | undefined => - /FileMode\]::(\w+)/.exec(command.script)?.[1] + const putLines = (): string[] => sftpBatches.flatMap((batch) => batch.script.split('\n').filter((line) => line.startsWith('put '))) const putDestination = (line: string): string => /put "(?:[^"]*)" "([^"]*)"/.exec(line)?.[1] ?? '' @@ -133,30 +123,6 @@ function refuseSftp(): void { }) } -function refusePwsh(): void { - spawnSystemSshCommandMock.mockImplementation((_target: SshTarget, command: string) => { - const spawnIndex = spawnSystemSshCommandMock.mock.calls.length - 1 - const executable = command.split(' ')[0] ?? '' - return createFakeChannel((channel) => { - commands.push({ - script: decodePowerShellCommand(command), - executable, - stdin: channel.written - }) - setImmediate(() => { - if (executable === 'pwsh.exe') { - channel.stderr.write( - "'pwsh.exe' is not recognized as an internal or external command,\noperable program or batch file." - ) - channel.emit('close', 9009, null) - return - } - channel.emit('close', spawnIndex === failAtSpawn ? 1 : 0, null) - }) - }) - }) -} - beforeEach(() => { commands.length = 0 sftpBatches.length = 0 @@ -164,7 +130,6 @@ beforeEach(() => { failedWriteExit = 1 failedWriteStderr = '' clearWindowsRemoteWriteCapabilitiesForTests() - waitForChannelCloseSpy.mockClear() localDir = mkdtempSync(join(tmpdir(), 'orca-win-upload-')) process.env.ORCA_SYSTEM_SFTP_PATH = '/usr/bin/sftp' runProcessMock.mockReset() @@ -249,23 +214,6 @@ describe('Windows upload over sftp', () => { expect(fileWrites()).toHaveLength(0) }) - it('does not let one unaddressable path become a verdict about the host', async () => { - writeFileSync(join(localDir, 'relay.js'), 'x') - - // UNC path refusal applies to this write; it says nothing about the host's SFTP support. - await uploadFileViaSystemSsh( - target, - join(localDir, 'relay.js'), - '//fileserver/share/relay.js', - { hostPlatform } - ) - - expect(fileWrites().length).toBeGreaterThan(0) - expect(sftpBatches).toHaveLength(0) - // Never cache path refusal: a host-wide verdict would degrade later ordinary destinations too. - expect(getWindowsRemoteWriteCapabilities(target).shouldTry('sftp-subsystem')).toBe(true) - }) - it('keeps using sftp for the next file after one path it could not spell', async () => { writeFileSync(join(localDir, 'relay.js'), 'x') @@ -279,18 +227,6 @@ describe('Windows upload over sftp', () => { expect(putLines()).toHaveLength(1) expect(putDestination(putLines()[0]!)).toContain('/C:/Users/dev/.orca-remote/b.js') }) - - it('does not let a local filename sftp cannot quote become a verdict either', async () => { - // POSIX clients allow a newline in a filename, and sftp's batch lexer would read it as the end - // of one command and the start of another. - const awkward = join(localDir, 'two\nlines.js') - writeFileSync(awkward, 'x') - - await uploadFileViaSystemSsh(target, awkward, `${remoteRoot}/relay.js`, { hostPlatform }) - - expect(fileWrites().length).toBeGreaterThan(0) - expect(getWindowsRemoteWriteCapabilities(target).shouldTry('sftp-subsystem')).toBe(true) - }) }) describe('Windows upload on a host with no sftp subsystem', () => { @@ -309,29 +245,6 @@ describe('Windows upload on a host with no sftp subsystem', () => { expect(Buffer.concat(fileWrites().map((write) => write.stdin)).equals(contents)).toBe(true) }) - it('bounds every write when only Windows PowerShell 5.1 is available', async () => { - refusePwsh() - const contents = Buffer.alloc(WINDOWS_STDIN_WRITE_CHUNK_BYTES * 3 + 11, 0x64) - writeFileSync(join(localDir, 'big.node'), contents) - - await uploadFileViaSystemSsh(target, join(localDir, 'big.node'), `${remoteRoot}/big.node`, { - hostPlatform - }) - - const writes = fileWrites().filter((write) => write.executable === 'powershell.exe') - expect(writes).toHaveLength(4) - expect(Math.max(...writes.map((write) => write.stdin.length))).toBe( - WINDOWS_STDIN_WRITE_CHUNK_BYTES - ) - expect(Buffer.concat(writes.map((write) => write.stdin)).equals(contents)).toBe(true) - expect(writes.map(fileMode)).toEqual(['Create', 'Append', 'Append', 'Append']) - // A wedged 5.1 read never closes; require bounded waits and a nonempty call list so every() cannot pass vacuously. - expect(waitForChannelCloseSpy.mock.calls.length).toBeGreaterThan(0) - expect( - waitForChannelCloseSpy.mock.calls.every((call) => call[2] === WINDOWS_STDIN_WRITE_TIMEOUT_MS) - ).toBe(true) - }) - it('leaves no truncated file under the real name when a chunk fails mid-file', async () => { writeFileSync(join(localDir, 'relay.js'), Buffer.alloc(WINDOWS_STDIN_WRITE_CHUNK_BYTES * 3)) failAtSpawn = 0 @@ -390,122 +303,6 @@ describe('Windows upload on a host with no sftp subsystem', () => { expect(commands.some((command) => command.script.includes('::Move('))).toBe(false) }) - const capturedPowerShellMissingPwsh = - "pwsh.exe : The term 'pwsh.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. \r\nCheck the spelling of the name, or if a path was included, verify that the path is correct and try again.\r\nAt line:1 char:1\r\n+ pwsh.exe -NoProfile -NonInteractive -Command exit\r\n+ ~~~~~~~~\r\n + CategoryInfo : ObjectNotFound: (pwsh.exe:String) [], CommandNotFoundException\r\n + FullyQualifiedErrorId : CommandNotFoundException" - - // Source-derived resource/layout controls; these are not captured localized Windows errors. - const sourceDerivedLocalizedMissingPwsh = [ - 'pwsh.exe : La commande est introuvable.', - 'Vérifiez le nom de la commande.', - 'À la ligne:1 caractère:1', - '+ pwsh.exe -NoProfile -NonInteractive -EncodedCommand JABwAGEAdABoAA== ...', - '+ ~~~~~~~~', - ' + CategoryInfo : CommandNotFoundException — cible pwsh.exe, type String', - ' + FullyQualifiedErrorId : CommandNotFoundException' - ].join('\r\n') - const sourceDerivedWrappedMissingPwsh = [ - 'pwsh.exe : The term', - "'pwsh.exe' is not recognized.", - 'At line:1 char:1', - '+ pwsh.exe -NoProfile ', - '-NonInteractive -EncodedCommand ', - 'JABwAGEAdABoAA== ...', - '+ ~~~~~~~~', - ' + CategoryInfo : ObjectNotFound: ', - '(pwsh.exe:String) [], CommandNotFoundExcept', - 'ion', - ' + FullyQualifiedErrorId : CommandNotFoundExcept', - 'ion' - ].join('\r\n') - - it.each([ - "'missing-tool.exe' is not recognized as an internal or external command", - `Access to the path 'relay.js' is denied.\n${capturedPowerShellMissingPwsh}`, - `${capturedPowerShellMissingPwsh}\nAccess to the path 'relay.js' is denied.`, - capturedPowerShellMissingPwsh.replaceAll('pwsh.exe', 'missing-tool.exe'), - capturedPowerShellMissingPwsh.replace(/.*CategoryInfo.*\r?\n/, ''), - capturedPowerShellMissingPwsh.replace('At line:', 'pwsh.exe : Another failure.\r\nAt line:'), - capturedPowerShellMissingPwsh.replace('At line:', 'another.exe : Another failure.\r\nAt line:'), - sourceDerivedLocalizedMissingPwsh.replace('cible pwsh.exe', 'cible relay-pwsh.exe.js'), - sourceDerivedLocalizedMissingPwsh.replace('cible pwsh.exe', 'cible C:\\bin\\pwsh.exe'), - sourceDerivedLocalizedMissingPwsh.replace('cible pwsh.exe', 'cible pwsh.exe-backup'), - sourceDerivedLocalizedMissingPwsh.replace('type String', 'type FileInfo'), - sourceDerivedWrappedMissingPwsh.replace('+ pwsh.exe', '+ missing-tool.exe'), - `${sourceDerivedWrappedMissingPwsh}\n${capturedPowerShellMissingPwsh}`, - `${sourceDerivedLocalizedMissingPwsh}\nAccess to the path 'relay.js' is denied.`, - `Access to the path 'relay.js' is denied.\n${sourceDerivedLocalizedMissingPwsh}`, - 'CommandNotFoundException: missing-tool.exe', - "Access to the path 'relay.js' is denied.\nCommandNotFoundException: pwsh.exe", - "Access to the path 'relay.js' is denied.\n'pwsh.exe' is not recognized as an internal or external command" - ])( - 'does not mark PowerShell 7 absent when its script reports another missing command: %s', - async (stderr) => { - writeFileSync(join(localDir, 'relay.js'), 'x') - failAtSpawn = 0 - failedWriteStderr = stderr - - await expect( - uploadFileViaSystemSsh(target, join(localDir, 'relay.js'), `${remoteRoot}/relay.js`, { - hostPlatform - }) - ).rejects.toThrow('failed (exit 1)') - - expect(fileWrites().map((write) => write.executable)).toEqual(['pwsh.exe']) - expect(getWindowsRemoteWriteCapabilities(target).shouldTry('pwsh')).toBe(true) - expect(commands.some((command) => command.script.includes('::Move('))).toBe(false) - } - ) - - it.each([ - [9009, ''], - [1, "'pwsh.exe' is not recognized as an internal or external command"], - [1, 'CommandNotFoundException: pwsh.exe'], - [ - 1, - "'pwsh.exe' is not recognized as an internal or external command,\r\noperable program or batch file." - ], - [1, capturedPowerShellMissingPwsh] - ])('falls back on an actual missing PowerShell 7 signal: %s %s', async (exit, stderr) => { - writeFileSync(join(localDir, 'relay.js'), Buffer.alloc(WINDOWS_STDIN_WRITE_CHUNK_BYTES * 3)) - failAtSpawn = 0 - failedWriteExit = exit - failedWriteStderr = stderr - - await uploadFileViaSystemSsh(target, join(localDir, 'relay.js'), `${remoteRoot}/relay.js`, { - hostPlatform - }) - - expect(fileWrites().map((write) => write.executable)).toEqual([ - 'pwsh.exe', - 'powershell.exe', - 'powershell.exe', - 'powershell.exe' - ]) - expect(getWindowsRemoteWriteCapabilities(target).shouldTry('pwsh')).toBe(false) - expect(commands.some((command) => command.script.includes('::Move('))).toBe(true) - }) - - it.each([ - sourceDerivedLocalizedMissingPwsh, - sourceDerivedWrappedMissingPwsh, - sourceDerivedLocalizedMissingPwsh.replace(' -NonInteractive', '\r\n -NonInteractive') - ])( - 'falls back on a source-derived localized or wrapped missing-pwsh record: %s', - async (stderr) => { - writeFileSync(join(localDir, 'relay.js'), 'x') - failAtSpawn = 0 - failedWriteStderr = stderr - - await uploadFileViaSystemSsh(target, join(localDir, 'relay.js'), `${remoteRoot}/relay.js`, { - hostPlatform - }) - - expect(fileWrites().map((write) => write.executable)).toEqual(['pwsh.exe', 'powershell.exe']) - expect(getWindowsRemoteWriteCapabilities(target).shouldTry('pwsh')).toBe(false) - expect(commands.some((command) => command.script.includes('::Move('))).toBe(true) - } - ) - it.each([ 'relay-CommandNotFoundException.js', 'is not recognized as an internal or external command.js' @@ -578,37 +375,3 @@ describe('last-resort Windows PowerShell failure reporting', () => { expect(explainWindowsPowerShellStdinFailure(denied)).toBe(denied) }) }) - -describe('waitForChannelClose bounding', () => { - it('fails a remote that accepts stdin and never closes, instead of waiting forever', async () => { - vi.useFakeTimers() - try { - const channel = createFakeChannel(() => {}) - const settled = vi.fn() - const promise = waitForChannelClose(channel as never, 'windows relay upload', 1_000) - promise.then(settled, settled) - - await vi.advanceTimersByTimeAsync(999) - expect(settled).not.toHaveBeenCalled() - - await vi.advanceTimersByTimeAsync(2) - await expect(promise).rejects.toThrow(/timed out after 1000ms with no response/) - } finally { - vi.useRealTimers() - } - }) - - it('leaves an unbounded wait unbounded when no timeout is asked for', async () => { - vi.useFakeTimers() - try { - const channel = createFakeChannel(() => {}) - const settled = vi.fn() - void waitForChannelClose(channel as never, 'posix write').then(settled, settled) - - await vi.advanceTimersByTimeAsync(60 * 60 * 1000) - expect(settled).not.toHaveBeenCalled() - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/ssh/system-transport/system-ssh-windows-write-capabilities.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-write-capabilities.ts similarity index 93% rename from src/main/ssh/system-transport/system-ssh-windows-write-capabilities.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-windows-write-capabilities.ts index e7f0a18302f..080e7df8041 100644 --- a/src/main/ssh/system-transport/system-ssh-windows-write-capabilities.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-write-capabilities.ts @@ -1,5 +1,5 @@ -import type { SshTarget } from '../../../shared/ssh-types' -import { CapabilityProbeCache } from '../../../shared/capability-probe-cache' +import type { SshTarget } from '../../../../shared/ssh-types' +import { CapabilityProbeCache } from '../../../../shared/capability-probe-cache' /** Cache SFTP/PowerShell 7 absence per execution host to avoid per-file probes. */ type WindowsRemoteWriteCapability = 'sftp-subsystem' | 'pwsh' diff --git a/src/main/ssh/system-transport/system-ssh-windows-write-strategy.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-write-strategy.ts similarity index 97% rename from src/main/ssh/system-transport/system-ssh-windows-write-strategy.ts rename to src/main/ssh/system-transport/file-transfer/system-ssh-windows-write-strategy.ts index e6d3261154c..b0b10916844 100644 --- a/src/main/ssh/system-transport/system-ssh-windows-write-strategy.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-write-strategy.ts @@ -1,12 +1,12 @@ -import type { SshTarget } from '../../../shared/ssh-types' -import { getSystemSshBuildArgsFromOperationOptions } from './system-ssh-args' -import { spawnSystemSshCommand } from './system-ssh-command' +import type { SshTarget } from '../../../../shared/ssh-types' +import { getSystemSshBuildArgsFromOperationOptions } from '../system-ssh-args' +import { spawnSystemSshCommand } from '../system-ssh-command' import { awaitWithSystemSshAbort, SystemSshCommandExitError, throwIfAborted, waitForChannelClose -} from './system-ssh-operation-lifecycle' +} from '../system-ssh-operation-lifecycle' import { isSftpPathUnsupportedError, isSftpRefusalBeforeStaging, diff --git a/src/main/ssh/system-transport/system-ssh-dynamic-forward-process.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts similarity index 76% rename from src/main/ssh/system-transport/system-ssh-dynamic-forward-process.test.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts index 2a4eacabcc3..0515b063e68 100644 --- a/src/main/ssh/system-transport/system-ssh-dynamic-forward-process.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts @@ -10,7 +10,7 @@ const { spawnMock, connectMock, createServerMock, waitForStopMock } = vi.hoisted vi.mock('node:child_process', () => ({ spawn: spawnMock })) vi.mock('node:net', () => ({ connect: connectMock, createServer: createServerMock })) -vi.mock('./system-ssh-binary', () => ({ findSystemSsh: () => '/usr/bin/ssh' })) +vi.mock('../system-ssh-binary', () => ({ findSystemSsh: () => '/usr/bin/ssh' })) vi.mock('./system-ssh-forward-process', () => ({ waitForSystemSshForwardStop: waitForStopMock })) @@ -77,34 +77,6 @@ describe('system SSH dynamic forward process', () => { afterEach(() => vi.useRealTimers()) - it('starts one non-interactive dynamic forward before the destination', async () => { - const forward = await startSystemSshDynamicForwardProcess(target) - const args = spawnMock.mock.calls[0]![1] as string[] - - expect(args).toEqual( - expect.arrayContaining([ - '-o', - 'BatchMode=yes', - '-S', - 'none', - '-p', - '2222', - '-i', - '/tmp/id_ed25519', - '-D', - '127.0.0.1:45678' - ]) - ) - expect(args).toEqual(expect.arrayContaining(['-o', 'ExitOnForwardFailure=no'])) - expect(args).not.toContain('ExitOnForwardFailure=yes') - expect(args.indexOf('-D')).toBeLessThan(args.indexOf('--')) - expect(args[args.indexOf('--') + 1]).toBe('orca@ssh.example.com') - expect(spawnMock).toHaveBeenCalledOnce() - - await forward.close() - expect(waitForStopMock).toHaveBeenCalledOnce() - }) - it('kills startup immediately when SSH authority is invalidated', async () => { connectMock.mockImplementation(() => fakeProbe(false)) const controller = new AbortController() diff --git a/src/main/ssh/system-transport/system-ssh-dynamic-forward-process.ts b/src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.ts similarity index 97% rename from src/main/ssh/system-transport/system-ssh-dynamic-forward-process.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.ts index 9696e43db51..b43620ce41d 100644 --- a/src/main/ssh/system-transport/system-ssh-dynamic-forward-process.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.ts @@ -1,8 +1,8 @@ import { spawn, type ChildProcess } from 'node:child_process' import { connect, createServer, type AddressInfo, type Socket } from 'node:net' -import type { SshTarget } from '../../../shared/ssh-types' -import { buildForwardProcessSshArgs, type SystemSshBuildArgsOptions } from './system-ssh-args' -import { findSystemSsh } from './system-ssh-binary' +import type { SshTarget } from '../../../../shared/ssh-types' +import { buildForwardProcessSshArgs, type SystemSshBuildArgsOptions } from '../system-ssh-args' +import { findSystemSsh } from '../system-ssh-binary' import { waitForSystemSshForwardStop } from './system-ssh-forward-process' const STARTUP_TIMEOUT_MS = 10_000 diff --git a/src/main/ssh/system-transport/system-ssh-forward-port-reservation.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts similarity index 87% rename from src/main/ssh/system-transport/system-ssh-forward-port-reservation.test.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts index d4432d00dc7..73aeb6d0eab 100644 --- a/src/main/ssh/system-transport/system-ssh-forward-port-reservation.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts @@ -61,11 +61,4 @@ describe('local forward port reservation', () => { `Local port 127.0.0.1:${port} is not available` ) }) - - it('tries no recovery for a port it cannot bind for any reason but use', async () => { - const cancel = vi.fn(async () => true) - await expect(reserveLocalForwardPort(-1, ['ssh'], cancel)).rejects.toThrow() - expect(stopOrphanMock).not.toHaveBeenCalled() - expect(cancel).not.toHaveBeenCalled() - }) }) diff --git a/src/main/ssh/system-transport/system-ssh-forward-port-reservation.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.ts similarity index 100% rename from src/main/ssh/system-transport/system-ssh-forward-port-reservation.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.ts diff --git a/src/main/ssh/system-transport/system-ssh-forward-process-real-openssh.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process-real-openssh.test.ts similarity index 91% rename from src/main/ssh/system-transport/system-ssh-forward-process-real-openssh.test.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-forward-process-real-openssh.test.ts index 9b87965d3ee..bd7f97cfd5c 100644 --- a/src/main/ssh/system-transport/system-ssh-forward-process-real-openssh.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process-real-openssh.test.ts @@ -1,15 +1,15 @@ /** ORCA_REAL_OPENSSH_TEST=1 requires ssh/sshd; verify listener/refusal ownership even with a user-configured ControlMaster. */ import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import type { SshConnection } from '../connection/ssh-connection' -import { SystemSshPortForwardProvider } from '../port-forwarding/system-ssh-port-forward-provider' -import { checkForwardChannel } from '../ssh-tcp-forwarding-probe' +import type { SshConnection } from '../../connection/ssh-connection' +import { SystemSshPortForwardProvider } from '../../port-forwarding/system-ssh-port-forward-provider' +import { checkForwardChannel } from '../../port-forwarding/ssh-tcp-forwarding-probe' import { REAL_OPENSSH_TEST_ENABLED, dial, freePort, startRealOpenSshFixture, type RealOpenSshFixture -} from './real-openssh-sshd-fixture' +} from '../testing/real-openssh-sshd-fixture' import { startSystemSshPortForwardProcess } from './system-ssh-forward-process' describe.skipIf(!REAL_OPENSSH_TEST_ENABLED)( diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts new file mode 100644 index 00000000000..8392f41cba9 --- /dev/null +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts @@ -0,0 +1,232 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' + +const { + existsSyncMock, + spawnMock, + connectMock, + createServerMock, + stopOrphanMock, + cancelMuxedMock +} = vi.hoisted(() => ({ + existsSyncMock: vi.fn(), + spawnMock: vi.fn(), + connectMock: vi.fn(), + createServerMock: vi.fn(), + stopOrphanMock: vi.fn(), + cancelMuxedMock: vi.fn() +})) + +vi.mock('./system-ssh-orphaned-forward', () => ({ + stopOrphanedOrcaSshForward: stopOrphanMock +})) + +vi.mock('./system-ssh-muxed-forward-cancel', () => ({ + cancelMuxedLocalForward: cancelMuxedMock +})) + +vi.mock('fs', async (importOriginal) => { + const actual = (await importOriginal()) as Record + return { + ...actual, + existsSync: existsSyncMock + } +}) + +vi.mock('child_process', () => ({ + spawn: spawnMock +})) + +vi.mock('net', () => ({ + connect: connectMock, + createServer: createServerMock +})) + +import { + SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS, + startSystemSshPortForwardProcess, + waitForSystemSshForwardStartup +} from './system-ssh-forward-process' +import type { SshTarget } from '../../../../shared/ssh-types' + +const SYSTEM_SSH_PATH = + process.platform === 'win32' ? 'C:\\Windows\\System32\\OpenSSH\\ssh.exe' : '/usr/bin/ssh' + +type FakeChildProcess = EventEmitter & { + stderr: EventEmitter + kill: ReturnType + exitCode: number | null + signalCode: NodeJS.Signals | null +} + +type FakeSocket = EventEmitter & { + setTimeout: ReturnType + destroy: ReturnType +} + +function createTarget(overrides?: Partial): SshTarget { + return { + id: 'target-1', + label: 'Test Server', + host: 'example.com', + port: 22, + username: 'deploy', + ...overrides + } +} + +function createFakeProcess(): FakeChildProcess { + const child = new EventEmitter() as FakeChildProcess + child.stderr = new EventEmitter() + child.kill = vi.fn().mockReturnValue(true) + child.exitCode = null + child.signalCode = null + return child +} + +function createFakeSocket(): FakeSocket { + const socket = new EventEmitter() as FakeSocket + socket.setTimeout = vi.fn() + socket.destroy = vi.fn() + return socket +} + +function createFakeServer() { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fields are assigned on the next lines, before the server is returned. + const server = new EventEmitter() as EventEmitter & { + listen: ReturnType + close: ReturnType + address: ReturnType + } + let boundPort = 0 + server.listen = vi.fn().mockImplementation((port: number) => { + boundPort = port === 0 ? 49800 : port + queueMicrotask(() => server.emit('listening')) + return server + }) + server.address = vi.fn(() => ({ address: '127.0.0.1', port: boundPort })) + server.close = vi.fn().mockImplementation((cb?: () => void) => cb?.()) + return server +} + +function mockSystemSshExists(): void { + existsSyncMock.mockImplementation((p: string) => p === SYSTEM_SSH_PATH) +} + +describe('system SSH forward process', () => { + beforeEach(() => { + existsSyncMock.mockReset() + spawnMock.mockReset() + connectMock.mockReset() + createServerMock.mockReset().mockImplementation(createFakeServer) + stopOrphanMock.mockReset().mockResolvedValue(false) + cancelMuxedMock.mockReset().mockResolvedValue(false) + mockSystemSshExists() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('keeps the port error when nothing Orca orphaned holds the port', async () => { + const server = createFakeServer() + server.listen.mockImplementation(() => { + queueMicrotask(() => + server.emit('error', Object.assign(new Error('EADDRINUSE'), { code: 'EADDRINUSE' })) + ) + return server + }) + createServerMock.mockReturnValue(server) + + await expect( + startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) + ).rejects.toThrow('Local port 127.0.0.1:5173 is not available') + expect(stopOrphanMock).toHaveBeenCalledWith(5173, expect.any(Array)) + expect(cancelMuxedMock).not.toHaveBeenCalled() + expect(spawnMock).not.toHaveBeenCalled() + }) + + it('rejects startup when ssh exits early with stderr', async () => { + vi.useFakeTimers() + const child = createFakeProcess() + const socket = createFakeSocket() + connectMock.mockReturnValue(socket) + + const pending = waitForSystemSshForwardStartup(child as never, 3000) + child.stderr.emit('data', Buffer.from('bind: Address already in use\n')) + child.emit('exit', 255) + + await expect(pending).rejects.toThrow('bind: Address already in use') + }) + + it("rejects startup and stops ssh when it cannot listen on this forward's own port", async () => { + const child = createFakeProcess() + spawnMock.mockReturnValue(child) + connectMock.mockReturnValue(createFakeSocket()) + const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) + + const pending = forward.waitForStartup() + child.stderr.emit('data', Buffer.from('bind [127.0.0.1]:5173: Address already in use\n')) + child.stderr.emit('data', Buffer.from('channel_setup_fwd_listener_tcpip: cannot listen')) + child.stderr.emit('data', Buffer.from(' to port: 5173\n')) + expect(child.kill).toHaveBeenCalledWith('SIGTERM') + child.emit('exit', null) + + await expect(pending).rejects.toThrow('cannot listen to port: 5173') + }) + + it('keeps running when only an ssh_config forward cannot listen', async () => { + vi.useFakeTimers() + const child = createFakeProcess() + spawnMock.mockReturnValue(child) + connectMock.mockImplementation(() => { + const socket = createFakeSocket() + queueMicrotask(() => socket.emit('error', new Error('ECONNREFUSED'))) + return socket + }) + const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) + + const pending = forward.waitForStartup() + child.stderr.emit( + 'data', + Buffer.from( + 'bind [127.0.0.1]:51730: Address already in use\n' + + 'channel_setup_fwd_listener_tcpip: cannot listen to port: 51730\n' + + 'Could not request local forwarding.\n' + ) + ) + await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS) + + await expect(pending).resolves.toBeUndefined() + expect(child.kill).not.toHaveBeenCalled() + }) + + it('rejects startup when the ssh process emits an error', async () => { + vi.useFakeTimers() + const child = createFakeProcess() + connectMock.mockReturnValue(createFakeSocket()) + + const pending = waitForSystemSshForwardStartup(child as never, 3000) + child.emit('error', new Error('spawn failed')) + + await expect(pending).rejects.toThrow('spawn failed') + }) + + it('rejects when no listener appears within the listener timeout', async () => { + vi.useFakeTimers() + const child = createFakeProcess() + connectMock.mockImplementation(() => { + const socket = createFakeSocket() + queueMicrotask(() => socket.emit('error', new Error('ECONNREFUSED'))) + return socket + }) + + spawnMock.mockReturnValue(child) + const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) + + const pending = waitForSystemSshForwardStartup(forward.process, 5173, 5_000) + const assertion = expect(pending).rejects.toThrow('did not listen on 127.0.0.1:5173') + await vi.advanceTimersByTimeAsync(5_000) + await assertion + }) +}) diff --git a/src/main/ssh/system-transport/system-ssh-forward-process.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.ts similarity index 97% rename from src/main/ssh/system-transport/system-ssh-forward-process.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-forward-process.ts index 747bbbcfd5b..00873182918 100644 --- a/src/main/ssh/system-transport/system-ssh-forward-process.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.ts @@ -1,11 +1,11 @@ import type { ChildProcessHandle as ChildProcess } from '@orca/process-host/process-spec' import { spawnProcess } from '@orca/process-host' import { connect } from 'node:net' -import { createSshOperationAbortError } from '../connection/ssh-exec-options' -import { buildForwardProcessSshArgs, type SystemSshBuildArgsOptions } from './system-ssh-args' -import { findSystemSsh } from './system-ssh-binary' +import { createSshOperationAbortError } from '../../connection/ssh-exec-options' +import { buildForwardProcessSshArgs, type SystemSshBuildArgsOptions } from '../system-ssh-args' +import { findSystemSsh } from '../system-ssh-binary' import { reserveLocalForwardPort } from './system-ssh-forward-port-reservation' -import type { SshTarget } from '../../../shared/ssh-types' +import type { SshTarget } from '../../../../shared/ssh-types' export const SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS = 750 export const SYSTEM_SSH_FORWARD_LISTENER_PROBE_INTERVAL_MS = 50 diff --git a/src/main/ssh/system-transport/system-ssh-loopback-route-admission.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route-admission.test.ts similarity index 97% rename from src/main/ssh/system-transport/system-ssh-loopback-route-admission.test.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-loopback-route-admission.test.ts index 3311532a379..b0ccaf106e2 100644 --- a/src/main/ssh/system-transport/system-ssh-loopback-route-admission.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route-admission.test.ts @@ -2,9 +2,9 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, describe, expect, it } from 'vitest' -import type { SshTarget } from '../../../shared/ssh-types' +import type { SshTarget } from '../../../../shared/ssh-types' import { admitSystemSshLoopbackRoute } from './system-ssh-loopback-route-admission' -import { findSystemSsh } from './system-ssh-binary' +import { findSystemSsh } from '../system-ssh-binary' const target: SshTarget = { id: 'target-1', diff --git a/src/main/ssh/system-transport/system-ssh-loopback-route-admission.ts b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route-admission.ts similarity index 97% rename from src/main/ssh/system-transport/system-ssh-loopback-route-admission.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-loopback-route-admission.ts index 05eac097209..074e46cc6c8 100644 --- a/src/main/ssh/system-transport/system-ssh-loopback-route-admission.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route-admission.ts @@ -1,11 +1,11 @@ /** Loopback is optional: any uncertainty retains the direct proxy route. */ import { dirname, join } from 'node:path' import { runProcess } from '@orca/process-host' -import type { SshTarget } from '../../../shared/ssh-types' -import { parseSshGOutput } from '../config/ssh-g-config-resolution' +import type { SshTarget } from '../../../../shared/ssh-types' +import { parseSshGOutput } from '../../config/ssh-g-config-resolution' import { requiresSystemSshForSecurityKey } from '../ssh-transport-selection' -import { buildSshArgs, type SystemSshBuildArgsOptions } from './system-ssh-args' -import { findSystemSsh } from './system-ssh-binary' +import { buildSshArgs, type SystemSshBuildArgsOptions } from '../system-ssh-args' +import { findSystemSsh } from '../system-ssh-binary' const LOOPBACK_ROUTE_ADMISSION_TIMEOUT_MS = 5_000 diff --git a/src/main/ssh/system-transport/system-ssh-loopback-route.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.test.ts similarity index 88% rename from src/main/ssh/system-transport/system-ssh-loopback-route.test.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.test.ts index 8c3459ad023..2158e26da70 100644 --- a/src/main/ssh/system-transport/system-ssh-loopback-route.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.test.ts @@ -34,9 +34,9 @@ vi.mock('child_process', () => ({ spawn: spawnMock })) vi.mock('net', () => ({ connect: connectMock, createServer: createServerMock })) -import type { SshTarget } from '../../../shared/ssh-types' +import type { SshTarget } from '../../../../shared/ssh-types' -import './system-ssh-args' +import '../system-ssh-args' import './system-ssh-forward-process' import { startSystemSshLoopbackRoute } from './system-ssh-loopback-route' @@ -103,17 +103,6 @@ function createListeningSocket(): EventEmitter { return socket } -function answerProbe(proc: FakeProcess, code: number): void { - setImmediate(() => { - if (code === 0) { - proc.stdout.write('ORCA-SYSTEM-SSH-LOOPBACK-OK\n') - } - proc.stdout.end() - proc.emit('exit', code, null) - proc.emit('close', code, null) - }) -} - describe('startSystemSshLoopbackRoute', () => { beforeEach(() => { existsSyncMock.mockReset().mockImplementation((p: string) => p === SYSTEM_SSH_PATH) @@ -144,25 +133,6 @@ describe('startSystemSshLoopbackRoute', () => { await expect(pending).rejects.toThrow('Connection closed by remote host') expect(spawnMock).toHaveBeenCalledTimes(1) }) - it.each(['exit', 'signal'] as const)('does not kill a forward after %s', async (reason) => { - const forward = createFakeProcess() - const probe = createFakeProcess() - spawnMock.mockReturnValueOnce(forward).mockImplementationOnce(() => { - answerProbe(probe, 0) - return probe - }) - const route = await startSystemSshLoopbackRoute(createTarget(), {}, 'win32') - if (reason === 'exit') { - forward.exitCode = 255 - } else { - forward.signalCode = 'SIGTERM' - } - forward.emit('exit', forward.exitCode, forward.signalCode) - route.dispose() - route.dispose() - expect(treeKillMock).not.toHaveBeenCalled() - expect(forward.kill).not.toHaveBeenCalled() - }) it('cancels listener polling and closes its socket without waiting for child exit', async () => { vi.useFakeTimers() try { diff --git a/src/main/ssh/system-transport/system-ssh-loopback-route.ts b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.ts similarity index 95% rename from src/main/ssh/system-transport/system-ssh-loopback-route.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.ts index f07b9b1256d..3beed7c4017 100644 --- a/src/main/ssh/system-transport/system-ssh-loopback-route.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.ts @@ -4,16 +4,16 @@ import { childProcessHasExited, signalProcessTree } from '@orca/process-host/process-tree-termination' -import { createSshOperationAbortError } from '../connection/ssh-exec-options' -import type { SshTarget } from '../../../shared/ssh-types' -import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' +import { createSshOperationAbortError } from '../../connection/ssh-exec-options' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { SshResolvedConfig } from '../../config/ssh-g-config-resolution' import { admitSystemSshLoopbackRoute } from './system-ssh-loopback-route-admission' import { isOpenSshConfigBackedTarget, type SystemSshBuildArgsOptions, type SystemSshLoopbackRouteArgs -} from './system-ssh-args' -import { spawnSystemSshCommand } from './system-ssh-command' +} from '../system-ssh-args' +import { spawnSystemSshCommand } from '../system-ssh-command' import { startSystemSshPortForwardProcess, waitForSystemSshForwardStartup diff --git a/src/main/ssh/system-transport/system-ssh-muxed-forward-cancel.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts similarity index 75% rename from src/main/ssh/system-transport/system-ssh-muxed-forward-cancel.test.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts index 40f270d3834..d509a0d568b 100644 --- a/src/main/ssh/system-transport/system-ssh-muxed-forward-cancel.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts @@ -7,15 +7,14 @@ const { findSystemSshMock, runProcessMock } = vi.hoisted(() => ({ vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -vi.mock('./system-ssh-binary', () => ({ findSystemSsh: findSystemSshMock })) +vi.mock('../system-ssh-binary', () => ({ findSystemSsh: findSystemSshMock })) import { - buildControlPathQueryArgs, buildMuxedLocalForwardCancelArgs, cancelMuxedLocalForward } from './system-ssh-muxed-forward-cancel' -import type { SshTarget } from '../../../shared/ssh-types' +import type { SshTarget } from '../../../../shared/ssh-types' const platform = Object.getOwnPropertyDescriptor(process, 'platform') @@ -33,10 +32,6 @@ function createTarget(overrides?: Partial): SshTarget { const ok = (stdout = '', stderr = '') => ({ code: 0, signal: null, stdout, stderr }) const controlPathAnswer = ok('user deploy\ncontrolpath /tmp/cm-abc123\nport 22\n') -function cancelCall() { - return runProcessMock.mock.calls.find(([request]) => request.args.includes('cancel'))?.[0] -} - describe('system SSH muxed forward cancel', () => { beforeEach(() => { Object.defineProperty(process, 'platform', { value: 'darwin' }) @@ -54,15 +49,6 @@ describe('system SSH muxed forward cancel', () => { } }) - it('reads the control socket with the target’s own args, multiplexed', () => { - const args = buildControlPathQueryArgs( - createTarget({ configHost: 'workbox', source: 'ssh-config' }) - ) - expect(args[0]).toBe('-G') - expect(args.at(-1)).toBe('workbox') - expect(args.some((arg, index) => arg === '-S' && args[index + 1] === 'none')).toBe(false) - }) - // Why: `-O cancel` also cancels every forward a loaded ssh_config declares for the host. it('asks that socket to cancel only this exact forward, reading no ssh_config', () => { const args = buildMuxedLocalForwardCancelArgs( @@ -79,14 +65,6 @@ describe('system SSH muxed forward cancel', () => { expect(args).toContain('127.0.0.1:59418:127.0.0.1:6768') }) - it('asks nothing when the target has no control socket', async () => { - runProcessMock.mockResolvedValue(ok('controlpath none\n')) - await expect(cancelMuxedLocalForward(createTarget(), 59418, '127.0.0.1', 6768)).resolves.toBe( - false - ) - expect(cancelCall()).toBeUndefined() - }) - // Why: a refused cancel exits 0, so only its stderr tells the port apart from a released one. it('reports nothing released when the master refuses the spec but still exits 0', async () => { runProcessMock.mockImplementation(async (request: { args: string[] }) => diff --git a/src/main/ssh/system-transport/system-ssh-muxed-forward-cancel.ts b/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.ts similarity index 93% rename from src/main/ssh/system-transport/system-ssh-muxed-forward-cancel.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.ts index c9640a78686..a9f7531a056 100644 --- a/src/main/ssh/system-transport/system-ssh-muxed-forward-cancel.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.ts @@ -1,8 +1,8 @@ /** A mux forward remains on its master after the client exits; only the master can release it. */ import { runProcess } from '@orca/process-host' -import { buildSshArgs, type SystemSshBuildArgsOptions } from './system-ssh-args' -import { findSystemSsh } from './system-ssh-binary' -import type { SshTarget } from '../../../shared/ssh-types' +import { buildSshArgs, type SystemSshBuildArgsOptions } from '../system-ssh-args' +import { findSystemSsh } from '../system-ssh-binary' +import type { SshTarget } from '../../../../shared/ssh-types' const SYSTEM_SSH_MUXED_FORWARD_CANCEL_TIMEOUT_MS = 5_000 diff --git a/src/main/ssh/system-transport/system-ssh-orphaned-forward.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.test.ts similarity index 100% rename from src/main/ssh/system-transport/system-ssh-orphaned-forward.test.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.test.ts diff --git a/src/main/ssh/system-transport/system-ssh-orphaned-forward.ts b/src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.ts similarity index 96% rename from src/main/ssh/system-transport/system-ssh-orphaned-forward.ts rename to src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.ts index d1253256cc3..9121bfbb85f 100644 --- a/src/main/ssh/system-transport/system-ssh-orphaned-forward.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.ts @@ -1,11 +1,11 @@ /** Recover fixed ports only from parentless processes with the exact same Orca forward/host argv; user SSH and live Orca tunnels are excluded. */ import { parseWindowsCommandLine } from '@orca/process-host/windows-command-line' -import { getFreshShellForegroundSnapshot } from '../../../shared/process-table-snapshot-reader' -import { readWindowsProcessTableFresh } from '../../windows/windows-process-table' +import { getFreshShellForegroundSnapshot } from '../../../../shared/process-table-snapshot-reader' +import { readWindowsProcessTableFresh } from '../../../windows/windows-process-table' import { PROCESS_START_TIME_TOLERANCE_MS, readProcessStartTimeMs -} from '../../runtime/agent-session/ownership/agent-session-process-identity-probe' +} from '../../../runtime/agent-session/ownership/agent-session-process-identity-probe' export type SshForwardProcessRow = { pid: number diff --git a/src/main/ssh/remote-exec/remote-host-failure-producers.test.ts b/src/main/ssh/system-transport/remote-host-failure-producers.test.ts similarity index 63% rename from src/main/ssh/remote-exec/remote-host-failure-producers.test.ts rename to src/main/ssh/system-transport/remote-host-failure-producers.test.ts index 8f5a83411ee..f1c2c1f452e 100644 --- a/src/main/ssh/remote-exec/remote-host-failure-producers.test.ts +++ b/src/main/ssh/system-transport/remote-host-failure-producers.test.ts @@ -7,20 +7,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import '../../../shared/node-runtime-pin' import type { SshTarget } from '../../../shared/ssh-types' import '@orca/process-host' -import '../orcad-remote-node-runtime-report' +import '../../managed-server/install/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 '../system-transport/system-ssh-sftp-transfer' -import { isHostAnsweredSystemSshExit } from '../system-transport/system-ssh-operation-lifecycle' +import '../remote-host/ssh-remote-platform' +import { findSystemSsh } from './system-ssh-binary' +import { uploadDirectoryViaSystemSsh } from './file-transfer/system-ssh-file-transfer' +import './file-transfer/system-ssh-sftp-transfer' +import { isHostAnsweredSystemSshExit } from './system-ssh-operation-lifecycle' vi.mock('@orca/process-host', async (importOriginal) => ({ ...(await importOriginal>()), runProcess: vi.fn() })) -vi.mock('../system-transport/system-ssh-args', () => ({ buildSshArgs: () => ['--', 'host'] })) -vi.mock('../system-transport/system-ssh-binary', () => ({ +vi.mock('./system-ssh-args', () => ({ buildSshArgs: () => ['--', 'host'] })) +vi.mock('./system-ssh-binary', () => ({ findSystemSsh: vi.fn(() => '/usr/bin/ssh') })) @@ -64,18 +64,4 @@ describe.runIf(posix)('system-ssh directory upload', () => { expect(isHostAnsweredSystemSshExit(error)).toBe(true) } }) - - 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') - vi.stubEnv('PATH', `${scratch}:${process.env.PATH}`) - vi.mocked(findSystemSsh).mockReturnValue( - await script('ssh', 'cat >/dev/null\necho "tar: Unexpected EOF in archive" >&2\nexit 2') - ) - const error = await uploadDirectoryViaSystemSsh(target, scratch, '/remote').catch( - (e: unknown) => e - ) - expect(String(error)).toContain('could not chdir to missing') - expect(isHostAnsweredSystemSshExit(error)).toBe(false) - }) }) diff --git a/src/main/ssh/ssh-control-socket.test.ts b/src/main/ssh/system-transport/ssh-control-socket.test.ts similarity index 81% rename from src/main/ssh/ssh-control-socket.test.ts rename to src/main/ssh/system-transport/ssh-control-socket.test.ts index ca6da357740..778d10ce783 100644 --- a/src/main/ssh/ssh-control-socket.test.ts +++ b/src/main/ssh/system-transport/ssh-control-socket.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' -import type { SshTarget } from '../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' const { lstatSyncMock, mkdirSyncMock, tmpdirMock } = vi.hoisted(() => ({ lstatSyncMock: vi.fn(), @@ -70,20 +70,6 @@ describe.skipIf(process.platform === 'win32')('getControlSocketPath', () => { }) }) - it('returns a stable short private socket path for the same effective target', () => { - const first = getControlSocketPath(createTarget(), createResolved()) - const second = getControlSocketPath(createTarget(), createResolved()) - - expect(first).toBe(second) - expect(first).toMatch(new RegExp(`/orca-ssh-${CURRENT_UID}/[0-9a-f]{16}$`)) - // Leave path room for OpenSSH's temporary listener suffix. - expect(first!.length).toBeLessThanOrEqual(90) - expect(mkdirSyncMock).toHaveBeenCalledWith(`/tmp/orca-ssh-${CURRENT_UID}`, { - recursive: true, - mode: 0o700 - }) - }) - it('uses a separate socket for GSSAPI-only authentication', () => { const ordinary = getControlSocketPath(createTarget(), createResolved()) const gssapiOnly = getControlSocketPath(createTarget(), createResolved(), true) diff --git a/src/main/ssh/ssh-control-socket.ts b/src/main/ssh/system-transport/ssh-control-socket.ts similarity index 96% rename from src/main/ssh/ssh-control-socket.ts rename to src/main/ssh/system-transport/ssh-control-socket.ts index c79f25e6dff..20acb94eac0 100644 --- a/src/main/ssh/ssh-control-socket.ts +++ b/src/main/ssh/system-transport/ssh-control-socket.ts @@ -2,8 +2,8 @@ import { createHash } from 'node:crypto' import { lstatSync, mkdirSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { isAbsolute, join as pathJoin } from 'node:path' -import type { SshTarget } from '../../shared/ssh-types' -import type { SshResolvedConfig } from './config/ssh-g-config-resolution' +import type { SshTarget } from '../../../shared/ssh-types' +import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' export type SystemSshResolvedConfig = Pick< SshResolvedConfig, diff --git a/src/main/ssh/ssh-proxy-command.test.ts b/src/main/ssh/system-transport/ssh-proxy-command.test.ts similarity index 87% rename from src/main/ssh/ssh-proxy-command.test.ts rename to src/main/ssh/system-transport/ssh-proxy-command.test.ts index 4be687cdacd..1344c37144b 100644 --- a/src/main/ssh/ssh-proxy-command.test.ts +++ b/src/main/ssh/system-transport/ssh-proxy-command.test.ts @@ -58,30 +58,6 @@ describe('spawnProxyCommand', () => { expect(proc.listenerCount('error')).toBe(0) }) - it('expands a comma-separated ProxyJump chain into -J plus a final hop', () => { - spawnMock.mockReturnValue(createMockProxyProcess()) - - spawnProxyCommand( - { kind: 'jump-host', jumpHost: 'first.example.com, second.example.com,third.example.com' }, - 'target.example.com', - 2222, - 'deploy' - ) - - expect(spawnMock).toHaveBeenCalledWith( - 'ssh', - [ - '-W', - 'target.example.com:2222', - '-J', - 'first.example.com,second.example.com', - '--', - 'third.example.com' - ], - expect.anything() - ) - }) - it('pauses the proxy stdout when the transport stream applies backpressure', () => { const proc = createMockProxyProcess() spawnMock.mockReturnValue(proc) diff --git a/src/main/ssh/ssh-proxy-command.ts b/src/main/ssh/system-transport/ssh-proxy-command.ts similarity index 94% rename from src/main/ssh/ssh-proxy-command.ts rename to src/main/ssh/system-transport/ssh-proxy-command.ts index 8b46a625c40..4c5f88abeb9 100644 --- a/src/main/ssh/ssh-proxy-command.ts +++ b/src/main/ssh/system-transport/ssh-proxy-command.ts @@ -2,10 +2,10 @@ import { spawn, type ChildProcess } from 'node:child_process' import { spawnProcess } from '@orca/process-host' import { Duplex } from 'node:stream' import type { Socket as NetSocket } from 'node:net' -import type { SshTarget } from '../../shared/ssh-types' -import type { SshResolvedConfig } from './config/ssh-g-config-resolution' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { isOpenSshConfigBackedTarget } from './system-transport/system-ssh-args' +import type { SshTarget } from '../../../shared/ssh-types' +import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import { isOpenSshConfigBackedTarget } from './system-ssh-args' // Normalize ProxyJump/jumpHost to the ProxyCommand equivalent so ssh2 has one proxy transport path. type EffectiveProxy = diff --git a/src/main/ssh/ssh-system-transport.integration.test.ts b/src/main/ssh/system-transport/ssh-system-transport.integration.test.ts similarity index 96% rename from src/main/ssh/ssh-system-transport.integration.test.ts rename to src/main/ssh/system-transport/ssh-system-transport.integration.test.ts index f18b1ec9e04..d090ed2d775 100644 --- a/src/main/ssh/ssh-system-transport.integration.test.ts +++ b/src/main/ssh/system-transport/ssh-system-transport.integration.test.ts @@ -6,9 +6,9 @@ vi.mock('electron', () => ({ app: { getAppPath: () => '/mock/app' } })) -import { uploadDirectoryViaSystemSsh } from './system-transport/system-ssh-file-transfer' -import type { SshTarget } from '../../shared/ssh-types' -import { relayArtifactFilenames } from './relay-install-artifacts' +import { uploadDirectoryViaSystemSsh } from './file-transfer/system-ssh-file-transfer' +import type { SshTarget } from '../../../shared/ssh-types' +import { relayArtifactFilenames } from '../legacy-relay/endpoints/relay-install-artifacts' const RELAY_VERSION = '0.1.0+systemtransport' diff --git a/src/main/ssh/ssh-transport-selection.ts b/src/main/ssh/system-transport/ssh-transport-selection.ts similarity index 78% rename from src/main/ssh/ssh-transport-selection.ts rename to src/main/ssh/system-transport/ssh-transport-selection.ts index e54b12afc2b..15212127be4 100644 --- a/src/main/ssh/ssh-transport-selection.ts +++ b/src/main/ssh/system-transport/ssh-transport-selection.ts @@ -1,14 +1,17 @@ -import type { SshTarget } from '../../shared/ssh-types' -import type { SshResolvedConfig } from './config/ssh-g-config-resolution' -import { listDefaultIdentityFilePaths, resolveIdentityFilePaths } from './ssh-auth-resolution' -import { resolveSshConfigHomePath } from './config/ssh-config-path-expansion' +import type { SshTarget } from '../../../shared/ssh-types' +import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' +import { + listDefaultIdentityFilePaths, + resolveIdentityFilePaths +} from '../authentication/ssh-auth-resolution' +import { resolveSshConfigHomePath } from '../config/ssh-config-path-expansion' import { isOpenSshSecurityKeyPrivateKey, isOpenSshSecurityKeyPublicKey -} from './ssh-security-key-identity' -import { readSshIdentityFile } from './ssh-identity-file-read' -import { isOpenSshConfigBackedTarget } from './system-transport/system-ssh-args' -import { findSystemSsh } from './system-transport/system-ssh-binary' +} from '../authentication/ssh-security-key-identity' +import { readSshIdentityFile } from '../authentication/ssh-identity-file-read' +import { isOpenSshConfigBackedTarget } from './system-ssh-args' +import { findSystemSsh } from './system-ssh-binary' type TransportResolvedConfig = Pick< SshResolvedConfig, diff --git a/src/main/ssh/system-transport/system-ssh-args.ts b/src/main/ssh/system-transport/system-ssh-args.ts index b68561b4232..9f33e712dbe 100644 --- a/src/main/ssh/system-transport/system-ssh-args.ts +++ b/src/main/ssh/system-transport/system-ssh-args.ts @@ -1,5 +1,5 @@ import type { SshTarget } from '../../../shared/ssh-types' -import { getControlSocketPath, type SystemSshResolvedConfig } from '../ssh-control-socket' +import { getControlSocketPath, type SystemSshResolvedConfig } from './ssh-control-socket' export type SystemSshBuildArgsOptions = { configFile?: string diff --git a/src/main/ssh/system-transport/system-ssh-command.ts b/src/main/ssh/system-transport/system-ssh-command.ts index 13e965b2c87..a15176200ad 100644 --- a/src/main/ssh/system-transport/system-ssh-command.ts +++ b/src/main/ssh/system-transport/system-ssh-command.ts @@ -2,7 +2,7 @@ import { spawn, type ChildProcess } from 'node:child_process' import { Duplex } from 'node:stream' import type { ClientChannel } from 'ssh2' import type { SshTarget } from '../../../shared/ssh-types' -import { wrapRemoteCommandForPosixShell } from '../ssh-posix-command-wrapper' +import { wrapRemoteCommandForPosixShell } from '../remote-exec/ssh-posix-command-wrapper' import type { SshExecOptions } from '../connection/ssh-exec-options' import { buildSshArgs, type SystemSshBuildArgsOptions } from './system-ssh-args' import { findSystemSsh } from './system-ssh-binary' diff --git a/src/main/ssh/system-transport/system-ssh-forward-process.test.ts b/src/main/ssh/system-transport/system-ssh-forward-process.test.ts deleted file mode 100644 index 2afae887395..00000000000 --- a/src/main/ssh/system-transport/system-ssh-forward-process.test.ts +++ /dev/null @@ -1,459 +0,0 @@ -import { EventEmitter } from 'node:events' -import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' - -const { - existsSyncMock, - spawnMock, - connectMock, - createServerMock, - stopOrphanMock, - cancelMuxedMock -} = vi.hoisted(() => ({ - existsSyncMock: vi.fn(), - spawnMock: vi.fn(), - connectMock: vi.fn(), - createServerMock: vi.fn(), - stopOrphanMock: vi.fn(), - cancelMuxedMock: vi.fn() -})) - -vi.mock('./system-ssh-orphaned-forward', () => ({ - stopOrphanedOrcaSshForward: stopOrphanMock -})) - -vi.mock('./system-ssh-muxed-forward-cancel', () => ({ - cancelMuxedLocalForward: cancelMuxedMock -})) - -vi.mock('fs', async (importOriginal) => { - const actual = (await importOriginal()) as Record - return { - ...actual, - existsSync: existsSyncMock - } -}) - -vi.mock('child_process', () => ({ - spawn: spawnMock -})) - -vi.mock('net', () => ({ - connect: connectMock, - createServer: createServerMock -})) - -import { - SYSTEM_SSH_FORWARD_LISTENER_PROBE_INTERVAL_MS, - SYSTEM_SSH_FORWARD_POST_KILL_TIMEOUT_MS, - SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS, - SYSTEM_SSH_FORWARD_STOP_TIMEOUT_MS, - spawnSystemSshPortForward, - startSystemSshPortForwardProcess, - waitForSystemSshForwardStartup, - waitForSystemSshForwardStop -} from './system-ssh-forward-process' -import type { SshTarget } from '../../../shared/ssh-types' - -const SYSTEM_SSH_PATH = - process.platform === 'win32' ? 'C:\\Windows\\System32\\OpenSSH\\ssh.exe' : '/usr/bin/ssh' - -type FakeChildProcess = EventEmitter & { - stderr: EventEmitter - kill: ReturnType - exitCode: number | null - signalCode: NodeJS.Signals | null -} - -type FakeSocket = EventEmitter & { - setTimeout: ReturnType - destroy: ReturnType -} - -function createTarget(overrides?: Partial): SshTarget { - return { - id: 'target-1', - label: 'Test Server', - host: 'example.com', - port: 22, - username: 'deploy', - ...overrides - } -} - -function expectNoOrcaControlMasterArgs(args: string[]): void { - expect(args).not.toContain('ControlMaster=auto') - expect(args.some((arg) => arg.startsWith('ControlPath='))).toBe(false) - expect(args).not.toContain('ControlPersist=300') -} - -function createFakeProcess(): FakeChildProcess { - const child = new EventEmitter() as FakeChildProcess - child.stderr = new EventEmitter() - child.kill = vi.fn().mockReturnValue(true) - child.exitCode = null - child.signalCode = null - return child -} - -function createFakeSocket(): FakeSocket { - const socket = new EventEmitter() as FakeSocket - socket.setTimeout = vi.fn() - socket.destroy = vi.fn() - return socket -} - -function createFakeServer() { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fields are assigned on the next lines, before the server is returned. - const server = new EventEmitter() as EventEmitter & { - listen: ReturnType - close: ReturnType - address: ReturnType - } - let boundPort = 0 - server.listen = vi.fn().mockImplementation((port: number) => { - boundPort = port === 0 ? 49800 : port - queueMicrotask(() => server.emit('listening')) - return server - }) - server.address = vi.fn(() => ({ address: '127.0.0.1', port: boundPort })) - server.close = vi.fn().mockImplementation((cb?: () => void) => cb?.()) - return server -} - -function mockSystemSshExists(): void { - existsSyncMock.mockImplementation((p: string) => p === SYSTEM_SSH_PATH) -} - -describe('system SSH forward process', () => { - beforeEach(() => { - existsSyncMock.mockReset() - spawnMock.mockReset() - connectMock.mockReset() - createServerMock.mockReset().mockImplementation(createFakeServer) - stopOrphanMock.mockReset().mockResolvedValue(false) - cancelMuxedMock.mockReset().mockResolvedValue(false) - mockSystemSshExists() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('spawns port forwards before the ssh destination terminator', () => { - spawnMock.mockReturnValue(createFakeProcess()) - - spawnSystemSshPortForward(createTarget({ configHost: 'fdpass-host' }), 5173, '127.0.0.1', 3000) - - const args = spawnMock.mock.calls[0][1] as string[] - const terminatorIdx = args.indexOf('--') - const forwardFlagIdx = args.indexOf('-N') - const localForwardIdx = args.indexOf('-L') - const exitOnForwardFailureIdx = args.indexOf('ExitOnForwardFailure=no') - const controlPathIdx = args.indexOf('-S') - - expect(terminatorIdx).toBeGreaterThan(-1) - expect(forwardFlagIdx).toBeGreaterThan(-1) - expect(localForwardIdx).toBeGreaterThan(-1) - expect(exitOnForwardFailureIdx).toBeGreaterThan(-1) - expect(forwardFlagIdx).toBeLessThan(terminatorIdx) - expect(localForwardIdx).toBeLessThan(terminatorIdx) - expect(args[exitOnForwardFailureIdx - 1]).toBe('-o') - expect(exitOnForwardFailureIdx).toBeLessThan(terminatorIdx) - expect(args).not.toContain('ExitOnForwardFailure=yes') - expect(args[controlPathIdx + 1]).toBe('none') - expect(controlPathIdx).toBeLessThan(terminatorIdx) - expectNoOrcaControlMasterArgs(args) - expect(args).toContain('127.0.0.1:5173:127.0.0.1:3000') - expect(args[terminatorIdx + 1]).toBe('fdpass-host') - expect(spawnMock).toHaveBeenCalledWith( - SYSTEM_SSH_PATH, - expect.any(Array), - expect.objectContaining({ stdio: ['ignore', 'ignore', 'pipe'] }) - ) - }) - - // A user master owns the listener and refusal stderr beyond the client's lifetime. - it("never rides the user's ssh_config ControlMaster", () => { - spawnMock.mockReturnValue(createFakeProcess()) - - spawnSystemSshPortForward( - createTarget({ configHost: 'workbox', source: 'ssh-config' }), - 5173, - '127.0.0.1', - 3000, - { - resolvedConfig: { - hostname: 'workbox.internal', - port: 22, - identityFile: [], - forwardAgent: false, - identitiesOnly: false, - proxyUseFdpass: false, - controlMaster: 'auto', - controlPath: '/Users/me/.ssh/cm/%r@%h:%p', - controlPersist: '10m' - } - } - ) - - const args = spawnMock.mock.calls[0][1] as string[] - const controlPathIdx = args.indexOf('-S') - expect(args[controlPathIdx + 1]).toBe('none') - expect(controlPathIdx).toBeLessThan(args.indexOf('--')) - expectNoOrcaControlMasterArgs(args) - expect(args).toContain('workbox') - }) - - it('stops a forward an earlier Orca orphaned on the port, then binds it', async () => { - const busy = createFakeServer() - busy.listen.mockImplementation(() => { - queueMicrotask(() => - busy.emit('error', Object.assign(new Error('EADDRINUSE'), { code: 'EADDRINUSE' })) - ) - return busy - }) - createServerMock.mockReturnValueOnce(busy) - stopOrphanMock.mockResolvedValue(true) - spawnMock.mockReturnValue(createFakeProcess()) - - const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) - - expect(stopOrphanMock).toHaveBeenCalledWith(5173, expect.any(Array)) - expect(spawnMock.mock.calls[0][1]).toEqual(stopOrphanMock.mock.calls[0][1]) - expect(forward.localPort).toBe(5173) - expect(spawnMock).toHaveBeenCalledOnce() - }) - - it('keeps the port error when nothing Orca orphaned holds the port', async () => { - const server = createFakeServer() - server.listen.mockImplementation(() => { - queueMicrotask(() => - server.emit('error', Object.assign(new Error('EADDRINUSE'), { code: 'EADDRINUSE' })) - ) - return server - }) - createServerMock.mockReturnValue(server) - - await expect( - startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) - ).rejects.toThrow('Local port 127.0.0.1:5173 is not available') - expect(stopOrphanMock).toHaveBeenCalledWith(5173, expect.any(Array)) - expect(cancelMuxedMock).not.toHaveBeenCalled() - expect(spawnMock).not.toHaveBeenCalled() - }) - - it('resolves port 0 to a free port first, since OpenSSH never reports the one it bound', async () => { - spawnMock.mockReturnValue(createFakeProcess()) - - const forward = await startSystemSshPortForwardProcess(createTarget(), 0, '127.0.0.1', 3000) - - expect(forward.localPort).toBe(49800) - expect(spawnMock.mock.calls[0][1]).toContain('127.0.0.1:49800:127.0.0.1:3000') - }) - - it('rejects startup when ssh exits early with stderr', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - const socket = createFakeSocket() - connectMock.mockReturnValue(socket) - - const pending = waitForSystemSshForwardStartup(child as never, 3000) - child.stderr.emit('data', Buffer.from('bind: Address already in use\n')) - child.emit('exit', 255) - - await expect(pending).rejects.toThrow('bind: Address already in use') - }) - - it("rejects startup and stops ssh when it cannot listen on this forward's own port", async () => { - const child = createFakeProcess() - spawnMock.mockReturnValue(child) - connectMock.mockReturnValue(createFakeSocket()) - const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) - - const pending = forward.waitForStartup() - child.stderr.emit('data', Buffer.from('bind [127.0.0.1]:5173: Address already in use\n')) - child.stderr.emit('data', Buffer.from('channel_setup_fwd_listener_tcpip: cannot listen')) - child.stderr.emit('data', Buffer.from(' to port: 5173\n')) - expect(child.kill).toHaveBeenCalledWith('SIGTERM') - child.emit('exit', null) - - await expect(pending).rejects.toThrow('cannot listen to port: 5173') - }) - - it('keeps running when only an ssh_config forward cannot listen', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - spawnMock.mockReturnValue(child) - connectMock.mockImplementation(() => { - const socket = createFakeSocket() - queueMicrotask(() => socket.emit('error', new Error('ECONNREFUSED'))) - return socket - }) - const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) - - const pending = forward.waitForStartup() - child.stderr.emit( - 'data', - Buffer.from( - 'bind [127.0.0.1]:51730: Address already in use\n' + - 'channel_setup_fwd_listener_tcpip: cannot listen to port: 51730\n' + - 'Could not request local forwarding.\n' - ) - ) - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS) - - await expect(pending).resolves.toBeUndefined() - expect(child.kill).not.toHaveBeenCalled() - }) - - it('stops ssh when its own listener fails after startup already resolved', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - spawnMock.mockReturnValue(child) - connectMock.mockImplementation(() => { - const socket = createFakeSocket() - queueMicrotask(() => socket.emit('error', new Error('ECONNREFUSED'))) - return socket - }) - const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) - const pending = forward.waitForStartup() - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS) - await expect(pending).resolves.toBeUndefined() - - child.stderr.emit( - 'data', - Buffer.from('channel_setup_fwd_listener_tcpip: cannot listen to port: 5173\n') - ) - - expect(child.kill).toHaveBeenCalledWith('SIGTERM') - }) - - it('rejects startup when the ssh process emits an error', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - connectMock.mockReturnValue(createFakeSocket()) - - const pending = waitForSystemSshForwardStartup(child as never, 3000) - child.emit('error', new Error('spawn failed')) - - await expect(pending).rejects.toThrow('spawn failed') - }) - - it('resolves startup when the local listener probe connects', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - const socket = createFakeSocket() - connectMock.mockReturnValue(socket) - - const pending = waitForSystemSshForwardStartup(child as never, 3000) - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_LISTENER_PROBE_INTERVAL_MS) - socket.emit('connect') - - await expect(pending).resolves.toBeUndefined() - expect(socket.destroy).toHaveBeenCalled() - }) - - // Why: a slow ProxyCommand outlasts the grace period, and a caller that dials the port next needs it listening. - it('waits past the grace period for a listener when a listener timeout is given', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - let listening = false - connectMock.mockImplementation(() => { - const socket = createFakeSocket() - queueMicrotask(() => - listening ? socket.emit('connect') : socket.emit('error', new Error('ECONNREFUSED')) - ) - return socket - }) - - spawnMock.mockReturnValue(child) - const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) - - let settled = false - const pending = waitForSystemSshForwardStartup(forward.process, 5173, 30_000).finally(() => { - settled = true - }) - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS * 4) - expect(settled).toBe(false) - - listening = true - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_LISTENER_PROBE_INTERVAL_MS * 2) - await expect(pending).resolves.toBeUndefined() - }) - - it('rejects when no listener appears within the listener timeout', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - connectMock.mockImplementation(() => { - const socket = createFakeSocket() - queueMicrotask(() => socket.emit('error', new Error('ECONNREFUSED'))) - return socket - }) - - spawnMock.mockReturnValue(child) - const forward = await startSystemSshPortForwardProcess(createTarget(), 5173, '127.0.0.1', 3000) - - const pending = waitForSystemSshForwardStartup(forward.process, 5173, 5_000) - const assertion = expect(pending).rejects.toThrow('did not listen on 127.0.0.1:5173') - await vi.advanceTimersByTimeAsync(5_000) - await assertion - }) - - it('resolves stop after the post-kill bound when the child never reports exit', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - - let resolved = false - const pending = waitForSystemSshForwardStop(child as never).then(() => { - resolved = true - }) - - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_STOP_TIMEOUT_MS) - expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL') - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_POST_KILL_TIMEOUT_MS - 1) - expect(resolved).toBe(false) - - await vi.advanceTimersByTimeAsync(1) - - // Assert before awaiting so a missing bound fails directly; resolving teardown does not prove child exit. - expect(resolved).toBe(true) - expect(child.kill).toHaveBeenCalledTimes(2) - await pending - }) - - it('clears the post-kill timer once the child exits after SIGKILL', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - - const pending = waitForSystemSshForwardStop(child as never) - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_STOP_TIMEOUT_MS) - child.emit('exit', null) - await expect(pending).resolves.toBeUndefined() - - expect(vi.getTimerCount()).toBe(0) - }) - - it('sends no signal to a child that already exited', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - child.exitCode = 0 - - await expect(waitForSystemSshForwardStop(child as never)).resolves.toBeUndefined() - - expect(child.kill).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - }) - - it('sends no SIGKILL or post-kill timer when the child exits after SIGTERM', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - - const pending = waitForSystemSshForwardStop(child as never) - await vi.advanceTimersByTimeAsync(SYSTEM_SSH_FORWARD_STOP_TIMEOUT_MS - 1) - child.emit('exit', null) - await expect(pending).resolves.toBeUndefined() - - expect(child.kill).toHaveBeenCalledExactlyOnceWith('SIGTERM') - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/main/ssh/system-transport/system-ssh-operations.test.ts b/src/main/ssh/system-transport/system-ssh-operations.test.ts index c6fbb424454..9469a873f71 100644 --- a/src/main/ssh/system-transport/system-ssh-operations.test.ts +++ b/src/main/ssh/system-transport/system-ssh-operations.test.ts @@ -22,9 +22,12 @@ vi.mock('child_process', () => ({ import { buildSshArgs } from './system-ssh-args' import { spawnSystemSshCommand } from './system-ssh-command' -import { uploadDirectoryViaSystemSsh, writeFileViaSystemSsh } from './system-ssh-file-transfer' +import { + uploadDirectoryViaSystemSsh, + writeFileViaSystemSsh +} from './file-transfer/system-ssh-file-transfer' import type { SshTarget } from '../../../shared/ssh-types' -import type { SystemSshResolvedConfig } from '../ssh-control-socket' +import type { SystemSshResolvedConfig } from './ssh-control-socket' const SYSTEM_SSH_PATH = process.platform === 'win32' ? 'C:\\Windows\\System32\\OpenSSH\\ssh.exe' : '/usr/bin/ssh' diff --git a/src/main/ssh/system-transport/system-ssh-windows-write-capabilities.test.ts b/src/main/ssh/system-transport/system-ssh-windows-write-capabilities.test.ts deleted file mode 100644 index bc0052566d5..00000000000 --- a/src/main/ssh/system-transport/system-ssh-windows-write-capabilities.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** Cache by execution endpoint so target re-creation and duplicate target rows share host facts. */ -import { afterEach, describe, expect, it } from 'vitest' -import type { SshTarget } from '../../../shared/ssh-types' -import { - clearWindowsRemoteWriteCapabilitiesForTests, - getWindowsRemoteWriteCapabilities -} from './system-ssh-windows-write-capabilities' - -const asTarget = (fields: Partial): SshTarget => fields as SshTarget - -afterEach(() => { - clearWindowsRemoteWriteCapabilitiesForTests() -}) - -describe('getWindowsRemoteWriteCapabilities', () => { - it('shares one cache across targets that reach the same host', () => { - const first = asTarget({ id: 'a', host: 'win.example', username: 'dev', port: 22 }) - const second = asTarget({ id: 'b', host: 'win.example', username: 'dev', port: 22 }) - - getWindowsRemoteWriteCapabilities(first).rememberUnsupported('sftp-subsystem') - - expect(getWindowsRemoteWriteCapabilities(second).shouldTry('sftp-subsystem')).toBe(false) - }) - - it('does not let one host answer for another', () => { - const hardened = asTarget({ id: 'a', host: 'hardened.example', username: 'dev', port: 22 }) - const ordinary = asTarget({ id: 'b', host: 'ordinary.example', username: 'dev', port: 22 }) - - getWindowsRemoteWriteCapabilities(hardened).rememberUnsupported('sftp-subsystem') - - expect(getWindowsRemoteWriteCapabilities(ordinary).shouldTry('sftp-subsystem')).toBe(true) - }) - - it('bounds host capability entries while retaining recent hosts', () => { - const first = asTarget({ id: 'first', host: 'win-first.example', username: 'dev' }) - getWindowsRemoteWriteCapabilities(first).rememberUnsupported('sftp-subsystem') - for (let index = 0; index < 260; index += 1) { - getWindowsRemoteWriteCapabilities( - asTarget({ id: String(index), host: `win-${index}.example`, username: 'dev' }) - ) - } - expect(getWindowsRemoteWriteCapabilities(first).shouldTry('sftp-subsystem')).toBe(true) - }) -}) diff --git a/src/main/ssh/system-transport/real-openssh-sshd-fixture.ts b/src/main/ssh/system-transport/testing/real-openssh-sshd-fixture.ts similarity index 97% rename from src/main/ssh/system-transport/real-openssh-sshd-fixture.ts rename to src/main/ssh/system-transport/testing/real-openssh-sshd-fixture.ts index 5a641c804d4..e32603b6523 100644 --- a/src/main/ssh/system-transport/real-openssh-sshd-fixture.ts +++ b/src/main/ssh/system-transport/testing/real-openssh-sshd-fixture.ts @@ -12,8 +12,8 @@ import { import { connect, createServer } from 'node:net' import { tmpdir, userInfo } from 'node:os' import { join } from 'node:path' -import type { SshTarget } from '../../../shared/ssh-types' -import type { SystemSshBuildArgsOptions } from './system-ssh-args' +import type { SshTarget } from '../../../../shared/ssh-types' +import type { SystemSshBuildArgsOptions } from '../system-ssh-args' const SSHD = '/usr/sbin/sshd' export const REAL_OPENSSH_TEST_ENABLED = diff --git a/src/main/ssh/connection/ssh-connection-store-orcad-ownership.test.ts b/src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts similarity index 73% rename from src/main/ssh/connection/ssh-connection-store-orcad-ownership.test.ts rename to src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts index 50b0367e57c..20f991ab7f5 100644 --- a/src/main/ssh/connection/ssh-connection-store-orcad-ownership.test.ts +++ b/src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts @@ -1,11 +1,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - isManagedOrcadSshTarget, - isRuntimeOwnedSshTarget, - SshConnectionStore -} from './ssh-connection-store' -import { createMockStore } from './ssh-connection-store-test-fixture' -import { emptyDependentStateStore } from '../targets/ssh-target-orcad-dependents-fixture' + +import { SshConnectionStore } from './ssh-connection-store' +import { createMockStore } from './testing/ssh-connection-store-test-fixture' +import { emptyDependentStateStore } from './testing/ssh-target-orcad-dependents-fixture' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), @@ -72,17 +69,4 @@ describe('managed orcad ownership of SSH targets', () => { expect((await sshStore.importFromSshConfig()).targets).toEqual([]) expect(mockStore.updateSshTarget).not.toHaveBeenCalled() }) - - it('tells a managed host apart from a runtime-owned one', () => { - const target = { ...base, id: 'ssh-1' } - const provisioning = { ...target, orcadProvisioning: { requestId: 'r', name: 'n' } } - const fenced = { ...target, orcadFence: { environmentId: 'e' } } - expect(isManagedOrcadSshTarget(target)).toBe(false) - expect(isManagedOrcadSshTarget(provisioning)).toBe(true) - expect(isManagedOrcadSshTarget(fenced)).toBe(true) - expect(isRuntimeOwnedSshTarget(fenced)).toBe(false) - expect( - isRuntimeOwnedSshTarget({ ...target, owner: { type: 'on-demand-runtime', runtimeId: 'vm' } }) - ).toBe(true) - }) }) diff --git a/src/main/ssh/connection/ssh-connection-store-route-dedupe.test.ts b/src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts similarity index 85% rename from src/main/ssh/connection/ssh-connection-store-route-dedupe.test.ts rename to src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts index 2570e283dc0..e670fcdea7e 100644 --- a/src/main/ssh/connection/ssh-connection-store-route-dedupe.test.ts +++ b/src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { SshConnectionStore } from './ssh-connection-store' -import { createMockStore } from './ssh-connection-store-test-fixture' +import { createMockStore } from './testing/ssh-connection-store-test-fixture' import { parseSshGOutput } from '../config/ssh-g-config-resolution' import type { SshTarget } from '../../../shared/ssh-types' @@ -105,18 +105,6 @@ describe('SshConnectionStore import route de-duplication', () => { loadUserSshConfigMock.mockReturnValue([]) }) - it('skips another name for a machine already in Orca, and the picker sees the same decision', async () => { - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('aimp')]) - - expect((await sshStore.refreshSshRouteSnapshot()).duplicateOf.get('aimp')).toBe('AI Box') - expect(sshStore.currentSshRouteSnapshot()?.duplicateOf.get('aimp')).toBe('AI Box') - const resolvedOnce = resolveConfig.mock.calls.length + systemRoute.mock.calls.length - expect((await sshStore.importFromSshConfig()).targets).toEqual([]) - expect(mockStore.addSshTarget).not.toHaveBeenCalled() - // Resolved once, then reused while the config is unchanged. - expect(resolveConfig.mock.calls.length + systemRoute.mock.calls.length).toBe(resolvedOnce) - }) - it('never matches a saved target whose own jump host conflicts with the one it inherits', async () => { mockStore.addSshTarget({ id: 'ssh-own-jump', @@ -204,19 +192,6 @@ describe('SshConnectionStore import route de-duplication', () => { expect([...first.targets, ...second.targets].map((target) => target.id)).toEqual(['ssh-moved']) }) - it('runs overlapping imports one after another, so the second reuses the first snapshot', async () => { - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('aimp')]) - await sshStore.refreshSshRouteSnapshot() - const oneRun = resolveConfig.mock.calls.length + systemRoute.mock.calls.length - resolveConfig.mockClear() - systemRoute.mockClear() - loadUserSshConfigMock.mockReturnValue([{ host: 'aimp' }]) - - await Promise.all([sshStore.importFromSshConfig(), sshStore.importFromSshConfig()]) - - expect(resolveConfig.mock.calls.length + systemRoute.mock.calls.length).toBe(oneRun) - }) - it('rebuilds the snapshot after an import changes targets, so the picker keeps the skipped alias flagged', async () => { sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('aimp'), configCandidate('via-b')]) diff --git a/src/main/ssh/connection/ssh-connection-store.test.ts b/src/main/ssh/targets/ssh-connection-store.test.ts similarity index 53% rename from src/main/ssh/connection/ssh-connection-store.test.ts rename to src/main/ssh/targets/ssh-connection-store.test.ts index e8f30a3a30a..e2212b0bb6c 100644 --- a/src/main/ssh/connection/ssh-connection-store.test.ts +++ b/src/main/ssh/targets/ssh-connection-store.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { SshConnectionStore } from './ssh-connection-store' -import { createMockStore } from './ssh-connection-store-test-fixture' +import { createMockStore } from './testing/ssh-connection-store-test-fixture' import type { SshTarget } from '../../../shared/ssh-types' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ @@ -29,61 +29,6 @@ describe('SshConnectionStore', () => { sshConfigHostsToTargetsMock.mockReset() }) - it('hides runtime-owned targets from normal target lists', () => { - const userTarget = sshStore.addTarget({ - label: 'My Server', - host: 'example.com', - port: 22, - username: 'deploy' - }) - sshStore.upsertRuntimeOwnedTarget('runtime-1', { - label: 'Sandbox', - host: 'sandbox.example.com', - port: 22, - username: 'root' - }) - - expect(sshStore.listTargets()).toEqual([userTarget]) - }) - - it('clears the runtime ladder decision when the runtime choice or endpoint changes', () => { - const resolution = { - rung: 'legacy' as const, - pinnedRefusal: 'missing_lib', - glibc: '2.31', - runtimeSha256: 'a'.repeat(64), - orcaMajor: 1 - } - mockStore.addSshTarget({ - id: 'ssh-ladder', - label: 'Ladder', - host: 'ladder.example.com', - port: 22, - username: 'user', - remoteRuntime: 'pinned-node', - remoteRuntimeResolution: resolution - }) - - sshStore.updateTarget('ssh-ladder', { label: 'Renamed', remoteRuntime: 'pinned-node' }) - expect(mockStore.updateSshTarget).toHaveBeenLastCalledWith('ssh-ladder', { - label: 'Renamed', - remoteRuntime: 'pinned-node' - }) - - sshStore.updateTarget('ssh-ladder', { remoteRuntime: 'legacy' }) - expect(mockStore.updateSshTarget).toHaveBeenLastCalledWith('ssh-ladder', { - remoteRuntime: 'legacy', - remoteRuntimeResolution: undefined - }) - - sshStore.updateTarget('ssh-ladder', { remoteRuntimeResolution: resolution }) - sshStore.updateTarget('ssh-ladder', { host: 'other.example.com' }) - expect(mockStore.updateSshTarget).toHaveBeenLastCalledWith('ssh-ladder', { - host: 'other.example.com', - remoteRuntimeResolution: undefined - }) - }) - describe('importFromSshConfig', () => { function candidate(overrides: Partial & { configHost: string }): SshTarget { return { @@ -96,40 +41,6 @@ describe('SshConnectionStore', () => { } } - it('refreshes host, username, and jump host on sync, not just port', async () => { - mockStore.addSshTarget({ - id: 'ssh-1', - label: 'box', - configHost: 'box', - host: 'old.example.com', - port: 22, - username: 'old', - source: 'ssh-config' - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'box' }]) - sshConfigHostsToTargetsMock.mockReturnValue([ - candidate({ - configHost: 'box', - host: 'new.example.com', - port: 2200, - username: 'newuser', - jumpHost: 'bastion' - }) - ]) - - await sshStore.importFromSshConfig() - - expect(mockStore.updateSshTarget).toHaveBeenCalledWith( - 'ssh-1', - expect.objectContaining({ - host: 'new.example.com', - port: 2200, - username: 'newuser', - jumpHost: 'bastion' - }) - ) - }) - it('adopts a legacy unsourced target into config-sync', async () => { mockStore.addSshTarget({ id: 'ssh-legacy', @@ -260,105 +171,9 @@ describe('SshConnectionStore', () => { ) expect(result).toHaveLength(1) }) - - it('reports every exact repo migration from a multi-host re-import', async () => { - mockStore.addRemovedSshTargetTombstone({ - oldTargetId: 'ssh-old-a', - configHost: 'host-a', - host: 'host-a.example.com', - port: 22, - username: '', - label: 'host-a', - removedAt: 1 - }) - mockStore.addRemovedSshTargetTombstone({ - oldTargetId: 'ssh-old-b', - configHost: 'host-b', - host: 'host-b.example.com', - port: 22, - username: '', - label: 'host-b', - removedAt: 1 - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'host-a' }, { host: 'host-b' }]) - sshConfigHostsToTargetsMock.mockReturnValue([ - candidate({ configHost: 'host-a' }), - candidate({ configHost: 'host-b' }) - ]) - - const { repoReadoptions } = await sshStore.importFromSshConfig({ reAdopt: true }) - - expect(repoReadoptions).toEqual([ - { oldTargetId: 'ssh-old-a', newTargetId: 'tmp-host-a', repoIds: ['repo-1'] }, - { oldTargetId: 'ssh-old-b', newTargetId: 'tmp-host-b', repoIds: ['repo-1'] } - ]) - }) }) describe('re-adoption of orphaned workspaces', () => { - it('does not tombstone runtime-owned targets', () => { - mockStore.addSshTarget({ - id: 'runtime-ssh-abc', - label: 'VM', - host: 'vm.example.com', - port: 22, - username: 'tim', - owner: { type: 'on-demand-runtime', runtimeId: 'abc' } - }) - - sshStore.removeTarget('runtime-ssh-abc') - - expect(mockStore.addRemovedSshTargetTombstone).not.toHaveBeenCalled() - expect(mockStore.addDeletedSshConfigAlias).not.toHaveBeenCalled() - }) - - // Exercise real remove/re-add so default configHost participates in tombstone readoption. - it('re-adopts through an actual removeTarget then re-add of the same host', () => { - const added = sshStore.addTarget({ - label: 'Dev', - host: 'dev.example.com', - port: 22, - username: 'tim' - }) - sshStore.removeTarget(added.id) - const tombstones = mockStore.getRemovedSshTargetTombstones() - expect(tombstones).toHaveLength(1) - expect(tombstones[0]).toMatchObject({ oldTargetId: added.id, configHost: 'dev.example.com' }) - - mockStore.reassignSshTargetId.mockClear() - const readded = sshStore.addTarget({ - label: 'Dev', - host: 'dev.example.com', - port: 22, - username: 'tim' - }) - - expect(mockStore.reassignSshTargetId).toHaveBeenCalledWith(added.id, readded.id) - expect(sshStore.lastRepoReadoptions).toEqual([ - { oldTargetId: added.id, newTargetId: readded.id, repoIds: ['repo-1'] } - ]) - }) - - it('does not re-adopt a different account on the same host', () => { - const alice = sshStore.addTarget({ - label: 'alice', - host: 'dev.example.com', - port: 22, - username: 'alice' - }) - sshStore.removeTarget(alice.id) - mockStore.reassignSshTargetId.mockClear() - - sshStore.addTarget({ - label: 'bob', - host: 'dev.example.com', - port: 2222, - username: 'bob' - }) - - expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled() - }) - it('does not re-adopt when the re-added host identity differs', () => { mockStore.addRemovedSshTargetTombstone({ oldTargetId: 'ssh-old', diff --git a/src/main/ssh/connection/ssh-connection-store.ts b/src/main/ssh/targets/ssh-connection-store.ts similarity index 90% rename from src/main/ssh/connection/ssh-connection-store.ts rename to src/main/ssh/targets/ssh-connection-store.ts index 9ab47772a44..7be0b99b95e 100644 --- a/src/main/ssh/connection/ssh-connection-store.ts +++ b/src/main/ssh/targets/ssh-connection-store.ts @@ -1,24 +1,26 @@ import type { Store } from '../../persistence/loading-store/store' import type { SshRepoReadoption, SshTarget } from '../../../shared/ssh-types' -import { RUNTIME_OWNED_SSH_TARGET_ID_PREFIX } from '../../../shared/execution-host' + import { normalizeSshConfigAlias } from '../../../shared/ssh-config-alias' import { isLegacyConfigImportTarget } from '../../../shared/ssh-target-source' -import { - loadUserSshConfigWithText, - sshConfigHostsToTargets, - type SshConfigHost -} from '../config/ssh-config-parser' -import { - findSshRouteDuplicates, - sshRouteSnapshotFingerprint, - type SshRouteResolvers, - type SshRouteSnapshot -} from '../targets/ssh-target-route-resolution' -import { SshTargetOrcadClaims } from '../targets/ssh-target-orcad-claims' +import { loadUserSshConfigWithText, sshConfigHostsToTargets } from '../config/ssh-config-parser' + +import type { SshConfigHost } from '../config/ssh-config-parser' +import { findSshRouteDuplicates, sshRouteSnapshotFingerprint } from './ssh-target-route-resolution' + +import type { SshRouteResolvers, SshRouteSnapshot } from './ssh-target-route-resolution' + +import { SshTargetOrcadClaims } from './ssh-target-orcad-claims' import { buildRemovedSshTargetTombstone, readoptOrphanedWorkspacesForTarget -} from '../targets/ssh-target-readoption' +} from './ssh-target-readoption' + +import { + getRuntimeOwnedSshTargetId, + isRuntimeOwnedSshTarget, + isManagedOrcadSshTarget +} from './ssh-target-runtime-ownership' // Reuse a snapshot while nothing it was built from changed, but re-resolve now and then: /etc/ssh_config and Match exec can change too. const ROUTE_SNAPSHOT_TTL_MS = 5 * 60_000 @@ -341,25 +343,3 @@ export class SshConnectionStore { return { targets: changed, repoReadoptions: readoptions } } } - -export function getRuntimeOwnedSshTargetId(runtimeId: string): string { - return `${RUNTIME_OWNED_SSH_TARGET_ID_PREFIX}${runtimeId}` -} - -/** Any target Orca created as an implementation detail; hidden from SSH-host surfaces. */ -export function isRuntimeOwnedSshTarget(target: SshTarget): boolean { - return target.owner !== undefined -} - -/** A host serving (or being set up for) a managed Orca server: visible, but never a direct relay. */ -export function isManagedOrcadSshTarget(target: SshTarget): boolean { - return target.orcadFence !== undefined || target.orcadProvisioning !== undefined -} - -/** Managed hosts cannot serve direct relays unless older retained projects still require their previous relay. */ -export function allowsDirectSshRelay(target: SshTarget): boolean { - if (target.orcadProvisioning) { - return false - } - return !target.orcadFence || target.orcadFence.sourceChangedAt !== undefined -} diff --git a/src/main/ssh/targets/ssh-target-orcad-claims.test.ts b/src/main/ssh/targets/ssh-target-orcad-claims.test.ts index b68489af1dc..6eab4968a03 100644 --- a/src/main/ssh/targets/ssh-target-orcad-claims.test.ts +++ b/src/main/ssh/targets/ssh-target-orcad-claims.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import type { SshRemotePtyLease, SshTarget } from '../../../shared/ssh-types' import { SshTargetOrcadClaims } from './ssh-target-orcad-claims' -import { emptyDependentStateStore } from './ssh-target-orcad-dependents-fixture' +import { emptyDependentStateStore } from './testing/ssh-target-orcad-dependents-fixture' type SetupOptions = { target?: Partial diff --git a/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts b/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts index 5c07d7279e5..204294e2e61 100644 --- a/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts +++ b/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts @@ -7,7 +7,7 @@ import { getAllWorktreeMetaForHost } from '../../persistence/loading-store/workt import { normalizeWorktreeLinkedItemMetadata } from '../../persistence/tracking-repos/worktree-metadata-normalization' import { collectDependentStateBlockers } from './ssh-target-orcad-dependents' -import { emptyDependentStateStore } from './ssh-target-orcad-dependents-fixture' +import { emptyDependentStateStore } from './testing/ssh-target-orcad-dependents-fixture' import { orcadTargetBlockerMessage } from './ssh-target-orcad-claims' function blockersFor(overrides: Parameters[0]) { diff --git a/src/main/ssh/targets/ssh-target-orcad-preflight.ts b/src/main/ssh/targets/ssh-target-orcad-preflight.ts index 2ac2a5b0174..35514ec135a 100644 --- a/src/main/ssh/targets/ssh-target-orcad-preflight.ts +++ b/src/main/ssh/targets/ssh-target-orcad-preflight.ts @@ -8,7 +8,7 @@ import type { import { createOrcadMigrationManifest, type OrcadMigrationExportStore -} from '../orcad-migration-manifest-export' +} from '../../persistence/migrating-orcad-catalog/orcad-migration-manifest-export' import { collectTargetCatalogBlockers, resolveOrcadPreflightTarget @@ -17,7 +17,7 @@ import { collectUntransferredDependentBlockers } from './ssh-target-orcad-depend import { preservesOrcadMigrationBridgedPanes, type OrcadMigrationPaneLeasePredicate -} from '../orcad-migration-bridged-panes' +} from '../migration-source/orcad-migration-bridged-panes' export type OrcadMigrationPreflightStore = OrcadMigrationExportStore & Pick< diff --git a/src/main/ssh/targets/ssh-target-registry.ts b/src/main/ssh/targets/ssh-target-registry.ts index c8bd44e64fe..fcc6171dc72 100644 --- a/src/main/ssh/targets/ssh-target-registry.ts +++ b/src/main/ssh/targets/ssh-target-registry.ts @@ -1,4 +1,4 @@ -import type { SshConnectionStore } from '../connection/ssh-connection-store' +import type { SshConnectionStore } from './ssh-connection-store' import type { SshConnectionManager } from '../connection/ssh-connection-manager' import type { SshConnectionState, diff --git a/src/main/ssh/targets/ssh-target-route-resolution.ts b/src/main/ssh/targets/ssh-target-route-resolution.ts index 1a39f303f70..73b59d3d9aa 100644 --- a/src/main/ssh/targets/ssh-target-route-resolution.ts +++ b/src/main/ssh/targets/ssh-target-route-resolution.ts @@ -8,7 +8,7 @@ import { type SshResolvedConfig } from '../config/ssh-g-config-resolution' import { resolveEffectiveSshEndpoint } from '../connection/ssh-connect-config' -import { resolveEffectiveProxy } from '../ssh-proxy-command' +import { resolveEffectiveProxy } from '../system-transport/ssh-proxy-command' import { sshRouteKey, type SshRoute } from './ssh-target-identity' import { mayUserSshConfigClaimAlias } from '../config/ssh-config-alias-claim' import { diff --git a/src/main/ssh/targets/ssh-target-runtime-ownership.ts b/src/main/ssh/targets/ssh-target-runtime-ownership.ts new file mode 100644 index 00000000000..cc7b52502f4 --- /dev/null +++ b/src/main/ssh/targets/ssh-target-runtime-ownership.ts @@ -0,0 +1,24 @@ +import type { SshTarget } from '../../../shared/ssh-types' +import { RUNTIME_OWNED_SSH_TARGET_ID_PREFIX } from '../../../shared/execution-host' + +export function getRuntimeOwnedSshTargetId(runtimeId: string): string { + return `${RUNTIME_OWNED_SSH_TARGET_ID_PREFIX}${runtimeId}` +} + +/** Any target Orca created as an implementation detail; hidden from SSH-host surfaces. */ +export function isRuntimeOwnedSshTarget(target: SshTarget): boolean { + return target.owner !== undefined +} + +/** A host serving (or being set up for) a managed Orca server: visible, but never a direct relay. */ +export function isManagedOrcadSshTarget(target: SshTarget): boolean { + return target.orcadFence !== undefined || target.orcadProvisioning !== undefined +} + +/** Managed hosts cannot serve direct relays unless older retained projects still require their previous relay. */ +export function allowsDirectSshRelay(target: SshTarget): boolean { + if (target.orcadProvisioning) { + return false + } + return !target.orcadFence || target.orcadFence.sourceChangedAt !== undefined +} diff --git a/src/main/ssh/connection/ssh-connection-store-test-fixture.ts b/src/main/ssh/targets/testing/ssh-connection-store-test-fixture.ts similarity index 94% rename from src/main/ssh/connection/ssh-connection-store-test-fixture.ts rename to src/main/ssh/targets/testing/ssh-connection-store-test-fixture.ts index b0cccfaba7b..9b4ab6a7cd3 100644 --- a/src/main/ssh/connection/ssh-connection-store-test-fixture.ts +++ b/src/main/ssh/targets/testing/ssh-connection-store-test-fixture.ts @@ -1,7 +1,7 @@ import { vi } from 'vitest' -import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import type { Repo } from '../../../shared/repo-types' -import type { RemovedSshTargetTombstone, SshTarget } from '../../../shared/ssh-types' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import type { Repo } from '../../../../shared/repo-types' +import type { RemovedSshTargetTombstone, SshTarget } from '../../../../shared/ssh-types' export function createMockStore() { const targets: SshTarget[] = [] diff --git a/src/main/ssh/targets/ssh-target-orcad-dependents-fixture.ts b/src/main/ssh/targets/testing/ssh-target-orcad-dependents-fixture.ts similarity index 73% rename from src/main/ssh/targets/ssh-target-orcad-dependents-fixture.ts rename to src/main/ssh/targets/testing/ssh-target-orcad-dependents-fixture.ts index 428294ccdfb..cee4a769cf1 100644 --- a/src/main/ssh/targets/ssh-target-orcad-dependents-fixture.ts +++ b/src/main/ssh/targets/testing/ssh-target-orcad-dependents-fixture.ts @@ -1,5 +1,5 @@ -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { DependentStateStore } from './ssh-target-orcad-dependents' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { DependentStateStore } from '../ssh-target-orcad-dependents' export function emptyDependentStateStore( overrides: Partial = {} diff --git a/src/main/startup/main-process-ready-foundation.ts b/src/main/startup/main-process-ready-foundation.ts index 1eee5fdfd93..83c363d4128 100644 --- a/src/main/startup/main-process-ready-foundation.ts +++ b/src/main/startup/main-process-ready-foundation.ts @@ -21,8 +21,8 @@ import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' import { initializeBrowserClientHostId } from '../browser/client-hosts/lifecycle/browser-client-host-id' import { scheduleSecretProtectionGapReport } from '../host/deferred-secret-protection-report' import { withholdUnreachableKeychainForServe } from '../host/serve-keychain-guard' -import { initSshHostKeyStoreFile } from '../ssh/ssh-host-key-store' -import { initOrcadHeldFenceTokenFile } from '../ssh/orcad-held-fence-tokens' +import { initSshHostKeyStoreFile } from '../ssh/host-keys/ssh-host-key-store' +import { initOrcadHeldFenceTokenFile } from '../managed-server/activation/orcad-held-fence-tokens' import { neutralizeLegacyTerminalShimDir } from '../pty/shell-startup/legacy-terminal-shim-dir' import { createWindowsShellPathHydration } from './windows-shell-path-hydration' import { @@ -64,7 +64,7 @@ import { agentHookServer } from '../agent-hooks/server' import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import { reportProfileStateWriteFailure } from './profile-state-write-failure' import { reportProfileStateSaveDelay } from './profile-state-save-delay' -import { preloadSsh2 } from '../ssh/ssh2-module-load' +import { preloadSsh2 } from '../ssh/authentication/ssh2-module-load' export async function initializeReadyFoundation(): Promise { logStartupMilestone('app-ready') diff --git a/src/main/startup/main-process-ready-identity-write.test.ts b/src/main/startup/main-process-ready-identity-write.test.ts index 78c2da1c4d1..945f25eec73 100644 --- a/src/main/startup/main-process-ready-identity-write.test.ts +++ b/src/main/startup/main-process-ready-identity-write.test.ts @@ -139,7 +139,7 @@ vi.mock('../browser/client-hosts/lifecycle/browser-client-host-id', () => ({ vi.mock('../host/deferred-secret-protection-report', () => ({ scheduleSecretProtectionGapReport: vi.fn() })) -vi.mock('../ssh/ssh-host-key-store', () => ({ initSshHostKeyStoreFile: vi.fn() })) +vi.mock('../ssh/host-keys/ssh-host-key-store', () => ({ initSshHostKeyStoreFile: vi.fn() })) vi.mock('../pty/shell-startup/legacy-terminal-shim-dir', () => ({ neutralizeLegacyTerminalShimDir: vi.fn() })) diff --git a/src/main/telemetry/wsl-move-telemetry.ts b/src/main/telemetry/wsl-move-telemetry.ts index 3691c2331f4..e0db23da55c 100644 --- a/src/main/telemetry/wsl-move-telemetry.ts +++ b/src/main/telemetry/wsl-move-telemetry.ts @@ -3,7 +3,7 @@ * waiting for its host, with the phase it reached, a reason code and duration and size buckets. * Every raw code is narrowed onto the schema's enums here; nothing a user or host named leaves. */ -import type { EventProps } from '../../shared/telemetry-events' +import type { EventProps } from '../../shared/telemetry-event-classification' import { WSL_MOVE_REFUSAL_VALUES, WSL_MOVE_RESET_REASON_VALUES diff --git a/src/main/text-generation/source-control-remote-generation.ts b/src/main/text-generation/source-control-remote-generation.ts index f188327c4b5..6f734710f11 100644 --- a/src/main/text-generation/source-control-remote-generation.ts +++ b/src/main/text-generation/source-control-remote-generation.ts @@ -1,5 +1,5 @@ import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' -import { isSshRequestOutcomeUnverifiable } from '../ssh/ssh-channel-multiplexer' +import { isSshRequestOutcomeUnverifiable } from '../ssh/protocol/ssh-channel-multiplexer' import { WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR } from '../../shared/windows-batch-spawn' import { finalizeFromAgentOutput, diff --git a/src/main/window/agent-pane-activity-relay.ts b/src/main/window/agent-pane-activity-relay.ts new file mode 100644 index 00000000000..a8c33e8231d --- /dev/null +++ b/src/main/window/agent-pane-activity-relay.ts @@ -0,0 +1,29 @@ +import type { BrowserWindow } from 'electron' + +import type { + AgentListPublication, + AgentPaneActivityChange, + AgentPaneActivityReply +} from '../../shared/agent-status/presentation/agent-list-status' +import { requestRendererReply } from './renderer-reply-request' + +// Under the client's call timeout, so the client hears a refusal rather than losing the reply. +const AGENT_PANE_ACTIVITY_TIMEOUT_MS = 10_000 + +/** Asks the window to apply a client's Agents-list change and answer with the verdicts it leaves. */ +export async function requestAgentPaneActivityFromRenderer( + mainWindow: BrowserWindow, + change: AgentPaneActivityChange +): Promise { + const reply = await requestRendererReply(mainWindow, { + requestChannel: 'ui:applyAgentPaneActivity', + replyChannel: 'ui:agentPaneActivityReply', + payload: change, + timeoutMs: AGENT_PANE_ACTIVITY_TIMEOUT_MS, + timeoutError: 'agent_activity_timeout' + }) + if ('error' in reply) { + throw new Error(reply.error) + } + return reply.publication +} diff --git a/src/main/window/main-window-service-stubs.test-fixture.ts b/src/main/window/main-window-service-stubs.test-fixture.ts index 0063c111933..b308406db67 100644 --- a/src/main/window/main-window-service-stubs.test-fixture.ts +++ b/src/main/window/main-window-service-stubs.test-fixture.ts @@ -30,6 +30,8 @@ type RuntimeStub = { markRendererReloadCancelled: MockFn markGraphReloadFailed: MockFn markGraphUnavailable: MockFn + readAgentListPublication: MockFn + setAgentListPublication: MockFn } export function createMainWindowServiceStub( @@ -67,7 +69,9 @@ export function createRuntime(): RuntimeStub { markRendererReloading: vi.fn(), markRendererReloadCancelled: vi.fn(), markGraphReloadFailed: vi.fn(), - markGraphUnavailable: vi.fn() + markGraphUnavailable: vi.fn(), + readAgentListPublication: vi.fn(() => null), + setAgentListPublication: vi.fn() } } diff --git a/src/main/window/renderer-reply-request.ts b/src/main/window/renderer-reply-request.ts new file mode 100644 index 00000000000..80582d8b885 --- /dev/null +++ b/src/main/window/renderer-reply-request.ts @@ -0,0 +1,65 @@ +import { randomUUID } from 'node:crypto' + +import { ipcMain, type BrowserWindow } from 'electron' + +import { addFanoutListener } from '../runtime/events/event-listener-fanout' +import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' + +/** Sends one request to the window and resolves with the reply its own renderer sends; rejects when it goes away or times out. */ +export function requestRendererReply( + mainWindow: BrowserWindow, + options: { + requestChannel: string + replyChannel: string + payload: object + timeoutMs: number + timeoutError: string + } +): Promise { + if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) { + return Promise.reject(new Error('renderer_unavailable')) + } + const webContents = mainWindow.webContents + const requestId = randomUUID() + return new Promise((resolve, reject) => { + let settled = false + const releaseListeners: (() => void)[] = [] + const finish = (error: Error | null, reply?: TReply): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + for (const release of releaseListeners) { + release() + } + if (reply) { + resolve(reply) + } else { + reject(error) + } + } + const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) + const timeout = setTimeout(() => finish(new Error(options.timeoutError)), options.timeoutMs) + const onReply = (event: Electron.IpcMainEvent, reply: TReply): void => { + // Visible request IDs confer no authority; only the targeted window can answer. + if (event.sender !== webContents || reply?.requestId !== requestId) { + return + } + finish(null, reply) + } + const lifetime = abortWhenRendererGone(webContents) + lifetime.signal.addEventListener('abort', onRendererUnavailable, { once: true }) + releaseListeners.push( + lifetime.dispose, + () => lifetime.signal.removeEventListener('abort', onRendererUnavailable), + addFanoutListener(mainWindow, 'closed', onRendererUnavailable), + addFanoutListener(ipcMain, options.replyChannel, onReply) + ) + try { + webContents.send(options.requestChannel, { ...options.payload, requestId }) + } catch { + finish(new Error('renderer_unavailable')) + } + }) +} diff --git a/src/main/window/runtime-window-lifecycle.ts b/src/main/window/runtime-window-lifecycle.ts index 003ba029679..9af8fcb8048 100644 --- a/src/main/window/runtime-window-lifecycle.ts +++ b/src/main/window/runtime-window-lifecycle.ts @@ -8,6 +8,7 @@ import type { RuntimeMobileSessionTabMove } from '../../shared/runtime-types' import type { TerminalTabCreateReply } from '../../shared/workspace-layout/terminal-reveal-identity' import { runWorktreeChangeInvalidators } from '../ipc/worktrees/listing/worktree-change-invalidators' import { requestAgentLaunchTabPublishFromRenderer } from './agent-launch-tab-publish-relay' +import { requestAgentPaneActivityFromRenderer } from './agent-pane-activity-relay' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { registerRendererDocumentNavigation } from './renderer-document-navigation' import { createRuntimeRendererNotificationSender } from './runtime-renderer-notification-sender' @@ -16,6 +17,8 @@ import { requestTerminalPaneMoveFromRenderer } from './terminal-pane-move-reques import { revealTerminalPaneInWindow } from './terminal-pane-reveal-relay' import { requestTerminalTabCloseFromRenderer } from './terminal-tab-close-request-relay' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../shared/sidebar-inputs-switch' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' +import { addFanoutListener } from '../runtime/events/event-listener-fanout' let runtimeNotifierTokenCounter = 0 let activeRuntimeNotifierToken: number | null = null @@ -219,6 +222,7 @@ export function registerRuntimeWindowLifecycle( requestTerminalTabCloseFromRenderer(mainWindow, tabId, options), workspaceSleepChanged: (notice) => send('ui:workspaceSleep', notice), resumeSleepingAgents: (worktreeId) => send('ui:resumeSleepingAgents', { worktreeId }), + applyAgentPaneActivity: (change) => requestAgentPaneActivityFromRenderer(mainWindow, change), terminalFitOverrideChanged: (ptyId, mode, cols, rows) => send('runtime:terminalFitOverrideChanged', { ptyId, mode, cols, rows }), terminalDriverChanged: (ptyId, driver) => @@ -244,13 +248,29 @@ export function registerRuntimeWindowLifecycle( { consumesTerminalSideEffects: false } ) : null + // Only this window's live document speaks for the Agents list; a gone one leaves no verdicts behind. + const releaseAgentListVerdicts = addFanoutListener( + ipcMain, + 'agentStatus:listVerdicts', + (event: Electron.IpcMainEvent, publication: AgentListPublication | null) => { + if (event.sender === mainWebContents && event.senderFrame === mainWebContents.mainFrame) { + runtime.setAgentListPublication(publication) + } + } + ) registerRendererDocumentNavigation(mainWebContents, () => { rendererNotifications.onMainFrameReloadStarted() + const agentListBeforeReload = runtime.readAgentListPublication() + runtime.setAgentListPublication(null) const fence = runtime.markRendererReloading(mainWindow.id) return () => { if (fence && runtime.markRendererReloadCancelled(mainWindow.id, fence)) { rendererNotifications.onMainFrameReloadCancelled() } + // The surviving document only re-sends on change. + if (runtime.readAgentListPublication() === null) { + runtime.setAgentListPublication(agentListBeforeReload) + } } }) mainWebContents.on('did-finish-load', () => { @@ -258,9 +278,12 @@ export function registerRuntimeWindowLifecycle( }) mainWebContents.on('render-process-gone', () => { rendererNotifications.onRendererProcessGone() + runtime.setAgentListPublication(null) }) mainWindow.on('closed', () => { detachSidebarInputsNotices?.() + releaseAgentListVerdicts() + runtime.setAgentListPublication(null) rendererNotifications.close() runtime.markGraphUnavailable(mainWindow.id) if (activeRuntimeNotifierToken === notifierToken) { diff --git a/src/main/window/terminal-pane-reveal-relay.ts b/src/main/window/terminal-pane-reveal-relay.ts index 2238704d08f..837cc459556 100644 --- a/src/main/window/terminal-pane-reveal-relay.ts +++ b/src/main/window/terminal-pane-reveal-relay.ts @@ -1,14 +1,11 @@ -import { randomUUID } from 'node:crypto' - -import { app, ipcMain, type BrowserWindow } from 'electron' +import { app, type BrowserWindow } from 'electron' import type { TerminalPaneRevealReply, TerminalPaneRevealTarget } from '../../shared/workspace-layout/terminal-pane-reveal' -import { addFanoutListener } from '../runtime/events/event-listener-fanout' -import { abortWhenRendererGone } from '../ipc/renderer-lifetime-abort' import { focusExistingMainWindow } from './focus-existing-window' +import { requestRendererReply } from './renderer-reply-request' const TERMINAL_PANE_REVEAL_TIMEOUT_MS = 10_000 @@ -17,7 +14,14 @@ export async function revealTerminalPaneInWindow( mainWindow: BrowserWindow, target: TerminalPaneRevealTarget ): Promise { - const revealed = await requestTerminalPaneRevealFromRenderer(mainWindow, target) + const reply = await requestRendererReply(mainWindow, { + requestChannel: 'ui:revealTerminalPane', + replyChannel: 'ui:terminalPaneRevealReply', + payload: target, + timeoutMs: TERMINAL_PANE_REVEAL_TIMEOUT_MS, + timeoutError: 'terminal_reveal_timeout' + }) + const revealed = reply.revealed === true if (revealed) { focusExistingMainWindow({ app, @@ -29,58 +33,3 @@ export async function revealTerminalPaneInWindow( } return revealed } - -function requestTerminalPaneRevealFromRenderer( - mainWindow: BrowserWindow, - target: TerminalPaneRevealTarget -): Promise { - if (mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) { - return Promise.reject(new Error('renderer_unavailable')) - } - const webContents = mainWindow.webContents - const requestId = randomUUID() - return new Promise((resolve, reject) => { - let settled = false - const releaseListeners: (() => void)[] = [] - const finish = (error: Error | null, revealed = false): void => { - if (settled) { - return - } - settled = true - clearTimeout(timeout) - for (const release of releaseListeners) { - release() - } - if (error) { - reject(error) - } else { - resolve(revealed) - } - } - const onRendererUnavailable = (): void => finish(new Error('renderer_unavailable')) - const timeout = setTimeout( - () => finish(new Error('terminal_reveal_timeout')), - TERMINAL_PANE_REVEAL_TIMEOUT_MS - ) - const onReply = (event: Electron.IpcMainEvent, reply: TerminalPaneRevealReply): void => { - // Visible request IDs confer no authority; only the targeted window can answer. - if (event.sender !== webContents || reply.requestId !== requestId) { - return - } - finish(null, reply.revealed === true) - } - const lifetime = abortWhenRendererGone(webContents) - lifetime.signal.addEventListener('abort', onRendererUnavailable, { once: true }) - releaseListeners.push( - lifetime.dispose, - () => lifetime.signal.removeEventListener('abort', onRendererUnavailable), - addFanoutListener(mainWindow, 'closed', onRendererUnavailable), - addFanoutListener(ipcMain, 'ui:terminalPaneRevealReply', onReply) - ) - try { - webContents.send('ui:revealTerminalPane', { ...target, requestId }) - } catch { - finish(new Error('renderer_unavailable')) - } - }) -} diff --git a/src/main/wsl/discovery/wsl-distro-unsupported.ts b/src/main/wsl/discovery/wsl-distro-unsupported.ts index 1d5d867fd26..2d25769addc 100644 --- a/src/main/wsl/discovery/wsl-distro-unsupported.ts +++ b/src/main/wsl/discovery/wsl-distro-unsupported.ts @@ -4,7 +4,7 @@ */ import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' import { OrcadHostGlibcUnsupportedError } from '../../managed-server/lifecycle/orcad-runtime-target' -import { RemoteNodeRuntimeSelfTestError } from '../../ssh/orcad-remote-node-runtime-report' +import { RemoteNodeRuntimeSelfTestError } from '../../managed-server/install/orcad-remote-node-runtime-report' import { wslHostAddRefusalText } from '../../../shared/wsl-host-failure-copy' /** Keeps OrcadHostUnsupportedError's name, so callers that classify by name still see it. */ diff --git a/src/main/ssh/relay-bundle-paths.ts b/src/main/wsl/execution/relay-bundle-paths.ts similarity index 86% rename from src/main/ssh/relay-bundle-paths.ts rename to src/main/wsl/execution/relay-bundle-paths.ts index aa793e516f7..20de15826ff 100644 --- a/src/main/ssh/relay-bundle-paths.ts +++ b/src/main/wsl/execution/relay-bundle-paths.ts @@ -1,6 +1,6 @@ import { join } from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' -import type { RelayPlatform } from './remote-exec/remote-frame-protocol' +import { getAppEnvironment } from '../../../shared/app-environment' +import type { RelayPlatform } from '../../ssh/remote-host/ssh-remote-platform' function currentAppPath(): string | undefined { try { diff --git a/src/main/wsl/execution/wsl-guest-process-identity.ts b/src/main/wsl/execution/wsl-guest-process-identity.ts index ae0040aabe2..4ee30b043e2 100644 --- a/src/main/wsl/execution/wsl-guest-process-identity.ts +++ b/src/main/wsl/execution/wsl-guest-process-identity.ts @@ -1,6 +1,6 @@ /** Use kernel boot ID and /proc start ticks for distro/process identity; wall-clock jumps after host sleep can misidentify live processes (microsoft/WSL#4179/#10006). */ import type { OrcadProcessIncarnation } from '../../orcad/orcad-process-start-time' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' export type WslGuestIdentity = { diff --git a/src/main/wsl/execution/wsl-node-runtime-download-budget.ts b/src/main/wsl/execution/wsl-node-runtime-download-budget.ts index 448c97b8a50..85ecdea6241 100644 --- a/src/main/wsl/execution/wsl-node-runtime-download-budget.ts +++ b/src/main/wsl/execution/wsl-node-runtime-download-budget.ts @@ -1,4 +1,4 @@ -import type { NodeRuntimeDownloadBudget } from '../../ssh/orcad-node-runtime-install-options' +import type { NodeRuntimeDownloadBudget } from '../../managed-server/install/orcad-node-runtime-install-options' /** * A first WSL deploy fetches the pinned Node archive. Behind a firewall that drops packets the default diff --git a/src/main/wsl/execution/wsl-node-runtime-prefetch.test.ts b/src/main/wsl/execution/wsl-node-runtime-prefetch.test.ts index f08dd1b8796..41e582b191b 100644 --- a/src/main/wsl/execution/wsl-node-runtime-prefetch.test.ts +++ b/src/main/wsl/execution/wsl-node-runtime-prefetch.test.ts @@ -2,7 +2,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { orcadNodeRuntimeInstallOptions } from '../../ssh/orcad-node-runtime-install-options' +import { orcadNodeRuntimeInstallOptions } from '../../managed-server/install/orcad-node-runtime-install-options' import { prefetchWslNodeRuntime, resetWslNodeRuntimePrefetchForTests, diff --git a/src/main/wsl/execution/wsl-pinned-runtime.ts b/src/main/wsl/execution/wsl-pinned-runtime.ts index ef56eeebc65..2d62333b635 100644 --- a/src/main/wsl/execution/wsl-pinned-runtime.ts +++ b/src/main/wsl/execution/wsl-pinned-runtime.ts @@ -12,9 +12,12 @@ import { import { REMOTE_NODE_RUNTIME_READY, assertRemoteNodeRuntimePromoted -} from '../../ssh/orcad-remote-node-runtime-report' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import { isGlibcBelow, PINNED_NODE_GLIBC_FLOOR } from '../../ssh/pinned-runtime-host-target' +} from '../../managed-server/install/orcad-remote-node-runtime-report' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { + isGlibcBelow, + PINNED_NODE_GLIBC_FLOOR +} from '../../managed-server/install/pinned-runtime-host-target' import type { WslSpec } from './wsl-runner' const downloads = new Map>() diff --git a/src/main/wsl/filesystem/wsl-directory-upload.ts b/src/main/wsl/filesystem/wsl-directory-upload.ts index 355f2420f43..56134c5f0cc 100644 --- a/src/main/wsl/filesystem/wsl-directory-upload.ts +++ b/src/main/wsl/filesystem/wsl-directory-upload.ts @@ -8,11 +8,11 @@ import type { RemoteInstallTransport } from '../../managed-server/install/remote import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { REMOTE_INSTALL_TIMEOUT_MS } from '../../managed-server/install/remote-deploy-timing' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { collectLocalUploadPlan, type LocalUploadPlan -} from '../../ssh/system-transport/system-ssh-file-transfer' +} from '../../ssh/system-transport/file-transfer/system-ssh-file-transfer' import { buildUstarEntryHeader, USTAR_BLOCK_BYTES, diff --git a/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts b/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts index 3f000fdb706..7a8ac4fef03 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts @@ -20,7 +20,7 @@ import { import { rewriteOrcadMigrationPathValue, type OrcadMigrationPathRewriter -} from '../../ssh/orcad-migration-path-rewrite' +} from '../../persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' import { wslUncDrivePathToWindows } from '../../../shared/wsl-paths' export type WslDriveUncRewriteScope = { diff --git a/src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts b/src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts index dbb3fbee8da..a690af455ae 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-automation-enable.test.ts @@ -26,7 +26,7 @@ vi.mock('../../../shared/remote-runtime/pairing/pairing', () => ({ encodePairingOffer: () => 'code', parsePairingCode: () => ({ code: 'code' }) })) -vi.mock('../../ssh/orcad-migration-catalog-client', () => ({ +vi.mock('../../managed-server/migration/catalog/orcad-migration-request', () => ({ sendSupportedMigrationRequest: async ( _pairing: unknown, method: string, diff --git a/src/main/wsl/host-lifecycle/wsl-host-automation-enable.ts b/src/main/wsl/host-lifecycle/wsl-host-automation-enable.ts index c9a3fd5ea62..aef7231ff8f 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-automation-enable.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-automation-enable.ts @@ -6,7 +6,7 @@ import { } from '../../../shared/remote-runtime/pairing/pairing' import { getPreferredPairingOffer } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { sendSupportedMigrationRequest } from '../../ssh/orcad-migration-catalog-client' +import { sendSupportedMigrationRequest } from '../../managed-server/migration/catalog/orcad-migration-request' import { getWslHostService } from './wsl-host-service-instance' import type { WslMoveMovedAutomation } from '../../persistence/moving-wsl-projects/wsl-move-host-automations-rewrite' diff --git a/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts b/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts index 5a51c3aa0ed..05b54127ddf 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts @@ -10,7 +10,7 @@ import { wslUnsupportedDistroFixMessage } from '../discovery/wsl-distro-unsupported' import { wslHostAddRefusal } from './wsl-host-add-admission' -import { RemoteNodeRuntimeSelfTestError } from '../../ssh/orcad-remote-node-runtime-report' +import { RemoteNodeRuntimeSelfTestError } from '../../managed-server/install/orcad-remote-node-runtime-report' import type { WslOrcadConnection } from '../orcad/wsl-orcad-connection-types' type WslHostAddRefusal = Extract diff --git a/src/main/wsl/host-lifecycle/wsl-host-server-stop.ts b/src/main/wsl/host-lifecycle/wsl-host-server-stop.ts index dd529018115..c75e3a7e82b 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-server-stop.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-server-stop.ts @@ -7,7 +7,7 @@ import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' import type { RuntimeTerminalListResult } from '../../../shared/runtime-terminal-contracts' import { wslHostServerStopReason } from '../../../shared/wsl-host-failure-copy' import type { WslHostServerStop } from '../../../shared/wsl-host-types' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { readRemoteOrcadManagedStopTarget } from '../../managed-server/lifecycle/orcad-managed-remote-stop' import { managedOrcadSlot } from '../../managed-server/lifecycle/orcad-managed-runtime-context' import { resolveOrcadRemoteContext } from '../../managed-server/install/orcad-remote-context' diff --git a/src/main/wsl/host-lifecycle/wsl-host-service.test.ts b/src/main/wsl/host-lifecycle/wsl-host-service.test.ts index df7c4858cf6..460df53600c 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-service.test.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-service.test.ts @@ -13,7 +13,7 @@ import { getWslHostDeploymentStorePath } from '../../../shared/remote-runtime/ho import { getPreferredPairingOffer } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import type { WslHostStatus } from '../../../shared/wsl-host-types' import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' -import { RemoteNodeRuntimeSelfTestError } from '../../ssh/orcad-remote-node-runtime-report' +import { RemoteNodeRuntimeSelfTestError } from '../../managed-server/install/orcad-remote-node-runtime-report' import { WslHostService } from './wsl-host-service' import type { WslHostConnector } from './wsl-host-connector-contract' import { WslOrcadLaunchDeferredError } from '../orcad/wsl-orcad-connection-errors' diff --git a/src/main/wsl/host-lifecycle/wsl-host-ssh-orcad-conflict.ts b/src/main/wsl/host-lifecycle/wsl-host-ssh-orcad-conflict.ts index 0e1e3459b24..47bc4f4c616 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-ssh-orcad-conflict.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-ssh-orcad-conflict.ts @@ -7,7 +7,7 @@ import { getPreferredPairingOffer, type KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { wslHostAddRefusal } from './wsl-host-add-admission' diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts index 2883306faf9..441ab6a6ca4 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts @@ -8,7 +8,7 @@ import { ORCAD_STDIO_BRIDGE_REFUSED, orcadPosixStdioBridgeCommand } from '../../../managed-server/lifecycle/orcad-stdio-bridge-script' -import type { OrcadStdioBridge } from '../../../ssh/orcad-stdio-bridge' +import type { OrcadStdioBridge } from '../../../managed-server/lifecycle/orcad-stdio-bridge' export type FakeWslBridgeChildren = { spawn: PipedProcessSpawner diff --git a/src/main/wsl/orcad/wsl-orcad-active-probe.test.ts b/src/main/wsl/orcad/wsl-orcad-active-probe.test.ts index 509360a9481..bc15cf8a45e 100644 --- a/src/main/wsl/orcad/wsl-orcad-active-probe.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-active-probe.test.ts @@ -5,15 +5,15 @@ vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ( ...(await importOriginal()), execCommand: vi.fn() })) -vi.mock('../../ssh/orcad-local-build-hash', () => ({ +vi.mock('../../managed-server/install/orcad-local-build-hash', () => ({ computeLocalOrcadBuildHash: () => 'abc123def4567890' })) import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { emptyOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' -import { OrcadActiveReadinessError } from '../../ssh/orcad-active-readiness' +import { OrcadActiveReadinessError } from '../../managed-server/activation/orcad-active-readiness' import { probeWslActiveOrcad, wslOrcadActiveProbeCommand } from './wsl-orcad-active-probe' const mockExec = vi.mocked(execCommand) diff --git a/src/main/wsl/orcad/wsl-orcad-active-probe.ts b/src/main/wsl/orcad/wsl-orcad-active-probe.ts index c39f80802fc..10920a5fe72 100644 --- a/src/main/wsl/orcad/wsl-orcad-active-probe.ts +++ b/src/main/wsl/orcad/wsl-orcad-active-probe.ts @@ -2,7 +2,7 @@ * WSL reads an active slot's liveness, readiness and pid in one guest command; SSH keeps * `probeActiveOrcadReadiness`'s separate reads. The answers are judged exactly as those are. */ -import type { OrcadHostTarget } from '../../ssh/orcad-host-transport' +import type { OrcadHostTarget } from '../../managed-server/install/orcad-host-transport' import type { OrcadRemoteContext } from '../../managed-server/install/orcad-remote-context' import { orcadLivenessProbeCommand } from '../../managed-server/install/orcad-remote-launch' import { readOrcadReadinessNowCommand } from '../../managed-server/install/orcad-remote-readiness-wait' @@ -13,12 +13,12 @@ import { activeOrcadReadinessFromOutput, assertActiveOrcadLive, OrcadActiveReadinessError -} from '../../ssh/orcad-active-readiness' -import { computeLocalOrcadBuildHash } from '../../ssh/orcad-local-build-hash' +} from '../../managed-server/activation/orcad-active-readiness' +import { computeLocalOrcadBuildHash } from '../../managed-server/install/orcad-local-build-hash' import type { ServeReadiness } from '../../server/serve-readiness' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { joinRemotePath } from '../../ssh/ssh-remote-platform' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' const SECTION_END = '__ORCA_WSL_ACTIVE_PROBE_END__' diff --git a/src/main/wsl/orcad/wsl-orcad-bridge-activity.test.ts b/src/main/wsl/orcad/wsl-orcad-bridge-activity.test.ts index db2b1bbce5e..73ebda350a2 100644 --- a/src/main/wsl/orcad/wsl-orcad-bridge-activity.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-bridge-activity.test.ts @@ -1,6 +1,9 @@ import { connect, createServer, type Server, type Socket } from 'node:net' import { afterEach, describe, expect, it, vi } from 'vitest' -import { checkOrcadStdioBridge, openOrcadStdioBridgeChannel } from '../../ssh/orcad-stdio-bridge' +import { + checkOrcadStdioBridge, + openOrcadStdioBridgeChannel +} from '../../managed-server/lifecycle/orcad-stdio-bridge' import type { StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' import { WslOrcadBridgeActivity } from './wsl-orcad-bridge-activity' import { diff --git a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.test.ts b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.test.ts index b0c87e9ae3a..e2a6c2aef0c 100644 --- a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.test.ts @@ -16,8 +16,8 @@ import { serializeOrcadActivationRecord, withActivatedVersion } from '../../managed-server/activation/orcad-activation-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { createWslOrcadConnectStateReader, parseWslOrcadConnectState, diff --git a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts index 4f357273c04..a534753826a 100644 --- a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts +++ b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts @@ -28,12 +28,12 @@ import { type WslGuestIdentity } from '../execution/wsl-guest-process-identity' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform -} from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform' // The record stores' own caps; a larger file reads as unreadable, as theirs does. const RECORD_MAX_BYTES = 64 * 1024 diff --git a/src/main/wsl/orcad/wsl-orcad-connect-stop-fence.ts b/src/main/wsl/orcad/wsl-orcad-connect-stop-fence.ts index 0b540a3dc24..9fe9031ebc9 100644 --- a/src/main/wsl/orcad/wsl-orcad-connect-stop-fence.ts +++ b/src/main/wsl/orcad/wsl-orcad-connect-stop-fence.ts @@ -4,11 +4,11 @@ * the connect fails instead of booting the distro again. */ import { onWslDistroGateNote } from '../discovery/wsl-background-distro-gate' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { wslDistroHolderKey } from '../discovery/wsl-distro-holder-record' import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' import { WslDistroNotRunningError } from './wsl-orcad-connection-errors' -import type { WslOrcadDeployOptions } from './wsl-orcad-deploy' +import type { WslOrcadDeployOptions } from './wsl-orcad-launch-contract' // A previous run's holder has no exit listener here; its process-table row is polled instead. export const ADOPTED_HOLDER_POLL_MS = 1_000 diff --git a/src/main/wsl/orcad/wsl-orcad-connection-errors.ts b/src/main/wsl/orcad/wsl-orcad-connection-errors.ts index f383ad32b49..cc6aac6d781 100644 --- a/src/main/wsl/orcad/wsl-orcad-connection-errors.ts +++ b/src/main/wsl/orcad/wsl-orcad-connection-errors.ts @@ -1,6 +1,6 @@ import type { WslRunningDistrosRead } from '../discovery/wsl-background-distro-gate' import { wslDistroHolderKey } from '../discovery/wsl-distro-holder-record' -import type { WslOrcadLaunch } from './wsl-orcad-deploy' +import type { WslOrcadLaunch } from './wsl-orcad-launch-contract' import { confirmsRunning } from './wsl-orcad-liveness-evidence' type WslOrcadDeferredLaunch = Extract diff --git a/src/main/wsl/orcad/wsl-orcad-connection-types.ts b/src/main/wsl/orcad/wsl-orcad-connection-types.ts index 00ae0bde9ed..ae3d4d1841a 100644 --- a/src/main/wsl/orcad/wsl-orcad-connection-types.ts +++ b/src/main/wsl/orcad/wsl-orcad-connection-types.ts @@ -1,15 +1,12 @@ +import type { WslHostDeferredUpdate } from '../../../shared/wsl-host-types' import type { PairingOffer } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' import type { OrcadTunnelIdentity } from '../../managed-server/lifecycle/orcad-managed-tunnel-identity' import type { ServeReadiness } from '../../server/serve-readiness' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import type { StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' import type { WslOrcadConnectionStatus } from './wsl-orcad-connection-status' -import type { - WslOrcadDeferredUpdate, - WslOrcadDeployOptions, - WslOrcadLaunch -} from './wsl-orcad-deploy' +import type { WslOrcadDeployOptions, WslOrcadLaunch } from './wsl-orcad-launch-contract' import type { WslOrcadHostTarget } from './wsl-orcad-host-target' import type { WslOrcadPairingRecovery } from './wsl-orcad-pairing-identity' import type { WslOrcadStdioBridgeOptions } from './wsl-orcad-stdio-bridge' @@ -28,7 +25,7 @@ export type WslOrcadConnection = { /** orcad's pairing code, with its endpoint rewritten to `ws://127.0.0.1:`. */ pairingOffer: string /** An app update the incumbent `fullVersion` is waiting to take (live terminals). */ - deferredUpdate: WslOrcadDeferredUpdate | null + deferredUpdate: WslHostDeferredUpdate | null close(): Promise } diff --git a/src/main/wsl/orcad/wsl-orcad-connection.test.ts b/src/main/wsl/orcad/wsl-orcad-connection.test.ts index d07aaf8b140..049e278556b 100644 --- a/src/main/wsl/orcad/wsl-orcad-connection.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-connection.test.ts @@ -17,7 +17,10 @@ import { getPreferredPairingOffer, type KnownRuntimeEnvironment } from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { checkOrcadStdioBridge, openOrcadStdioBridgeChannel } from '../../ssh/orcad-stdio-bridge' +import { + checkOrcadStdioBridge, + openOrcadStdioBridgeChannel +} from '../../managed-server/lifecycle/orcad-stdio-bridge' import { startEchoServer } from '../../managed-server/lifecycle/orcad-stdio-bridge-test-channel' import { fakeWslBridgeChildren, @@ -33,7 +36,7 @@ import { WslOrcadConnectionSupersededError, WslOrcadLaunchDeferredError } from './wsl-orcad-connection-errors' -import type { WslOrcadLaunch } from './wsl-orcad-deploy' +import type { WslOrcadLaunch } from './wsl-orcad-launch-contract' import { createWslOrcadHostTransport } from './wsl-orcad-host-transport' import { listenWslOrcadStdioBridge } from './wsl-orcad-stdio-bridge' import { wslOrcadHostDistro } from './wsl-orcad-host-environments' diff --git a/src/main/wsl/orcad/wsl-orcad-connection.ts b/src/main/wsl/orcad/wsl-orcad-connection.ts index c03f97a5483..d9b3579af86 100644 --- a/src/main/wsl/orcad/wsl-orcad-connection.ts +++ b/src/main/wsl/orcad/wsl-orcad-connection.ts @@ -13,18 +13,15 @@ import type { WslHostConnectIntent } from '../../../shared/wsl-host-types' import { errorMessage } from '../../../shared/error-message' import { parsePairingCode } from '../../../shared/remote-runtime/pairing/pairing' import type { PairingOffer } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import type { StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' import { wslConnectFailedStatus, type WslOrcadConnectionStatus } from './wsl-orcad-connection-status' import { wslDistroHolderKey } from '../discovery/wsl-distro-holder-record' -import { - defaultWslOrcadEnvironmentId, - deployAndLaunchWslOrcad, - type WslOrcadLaunch -} from './wsl-orcad-deploy' +import { defaultWslOrcadEnvironmentId, deployAndLaunchWslOrcad } from './wsl-orcad-deploy' +import type { WslOrcadLaunch } from './wsl-orcad-launch-contract' import type { WslOrcadHostTarget } from './wsl-orcad-host-target' import { createWslOrcadHostTransport } from './wsl-orcad-host-transport' import { resolveWslOrcadPairing } from './wsl-orcad-pairing-identity' diff --git a/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts b/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts index b3f43810681..b577859aeea 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts @@ -1,6 +1,6 @@ // Split from wsl-orcad-deploy.test.ts: the connect across an app update (E1), with the same host mocks. import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import type * as ActiveProbe from './wsl-orcad-active-probe' import type * as ManagedRuntimeContext from '../../managed-server/lifecycle/orcad-managed-runtime-context' import type * as RemoteVersionedInstall from '../../managed-server/install/remote-versioned-install' @@ -8,7 +8,7 @@ import { emptyOrcadActivationRecord, type OrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' import type { WslOrcadHostTarget } from './wsl-orcad-host-target' @@ -40,7 +40,7 @@ vi.mock('../../managed-server/install/remote-versioned-install', async (importOr readLocalFullVersion: mocks.localVersion })) vi.mock('./wsl-orcad-instance-adoption', () => ({ adoptUnrecordedWslOrcad: mocks.adopt })) -vi.mock('../../ssh/orcad-running-version-adoption', () => ({ +vi.mock('../../managed-server/activation/orcad-running-version-adoption', () => ({ adoptRunningOrcadVersion: mocks.adoptRunning })) @@ -57,7 +57,7 @@ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ vi.mock('../../orcad/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) -vi.mock('../../ssh/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) +vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) vi.mock('./wsl-orcad-active-probe', async (importOriginal) => ({ ...(await importOriginal()), probeWslActiveOrcad: async (...args: unknown[]) => ({ diff --git a/src/main/wsl/orcad/wsl-orcad-deploy.test.ts b/src/main/wsl/orcad/wsl-orcad-deploy.test.ts index 585788be594..323ca16f7d2 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy.test.ts @@ -1,11 +1,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import type * as ActiveProbe from './wsl-orcad-active-probe' import type * as ManagedRuntimeContext from '../../managed-server/lifecycle/orcad-managed-runtime-context' import type * as RemoteVersionedInstall from '../../managed-server/install/remote-versioned-install' import { emptyOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import { OrcadActiveReadinessError } from '../../ssh/orcad-active-readiness' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { OrcadActiveReadinessError } from '../../managed-server/activation/orcad-active-readiness' import { WslDistroNotRunningError } from './wsl-orcad-connection-errors' import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' import type { WslOrcadHostTarget } from './wsl-orcad-host-target' @@ -42,7 +42,7 @@ vi.mock('../../managed-server/install/remote-versioned-install', async (importOr readLocalFullVersion: mocks.localVersion })) vi.mock('./wsl-orcad-instance-adoption', () => ({ adoptUnrecordedWslOrcad: mocks.adopt })) -vi.mock('../../ssh/orcad-running-version-adoption', () => ({ +vi.mock('../../managed-server/activation/orcad-running-version-adoption', () => ({ adoptRunningOrcadVersion: mocks.adoptRunning })) @@ -59,7 +59,7 @@ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ vi.mock('../../orcad/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) -vi.mock('../../ssh/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) +vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) vi.mock('./wsl-orcad-active-probe', async (importOriginal) => ({ ...(await importOriginal()), probeWslActiveOrcad: async (...args: unknown[]) => ({ diff --git a/src/main/wsl/orcad/wsl-orcad-deploy.ts b/src/main/wsl/orcad/wsl-orcad-deploy.ts index 2204020dfb6..5505eb2c432 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy.ts @@ -1,14 +1,16 @@ +import type { WslHostDeferredUpdate } from '../../../shared/wsl-host-types' +import type { WslOrcadLaunch, WslOrcadDeployOptions } from './wsl-orcad-launch-contract' /** D1/D2b/D8 reuse SSH installation, activation journals/fences and admission over wsl.exe. C5 pairs through the reported loopback port. */ import { getAppEnvironment } from '../../../shared/app-environment' -import type { PairingOffer } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' + import { ORCAD_MANAGED_REMOTE_PORT } from '../../../shared/orcad-managed-runtime' import type { ServeReadiness } from '../../server/serve-readiness' -import type { WslHostDeferredUpdate } from '../../../shared/wsl-host-types' + import { recoverInterruptedOrcadActivation } from '../../managed-server/activation/orcad-activation-recovery' import { readOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record-store' import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../../ssh/orcad-installed-activation' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' +import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../../managed-server/activation/orcad-installed-activation' import { orcadBoundPort } from '../../managed-server/lifecycle/orcad-managed-bound-port' import { isForceableOrcadDeferral, @@ -22,14 +24,17 @@ import type { OrcadActivationRecord } from '../../managed-server/activation/orca import { errorMessage } from '../../../shared/error-message' import { pruneWslOrcadVersionsUntilClean } from './wsl-orcad-version-gc-memo' import { pruneSupersededOrcadCandidates } from '../../managed-server/lifecycle/orcad-managed-version-gc' -import { wakeAlreadyActiveOrcad } from '../../ssh/orcad-already-active-wake' -import { OrcadActiveReadinessError } from '../../ssh/orcad-active-readiness' +import { wakeAlreadyActiveOrcad } from '../../managed-server/lifecycle/orcad-already-active-wake' +import { OrcadActiveReadinessError } from '../../managed-server/activation/orcad-active-readiness' import { WslDistroNotRunningError } from './wsl-orcad-connection-errors' -import { deployOrcad, type OrcadDeployOptions } from '../../ssh/orcad-remote-deploy' +import { + deployOrcad, + type OrcadDeployOptions +} from '../../managed-server/install/orcad-remote-deploy' import { isWslMoveUnderwayOnHost } from '../../persistence/moving-wsl-projects/wsl-move-running-moves' import { readLocalFullVersion } from '../../managed-server/install/remote-versioned-install' import { createWslDistroHolder } from '../discovery/wsl-distro-holder' -import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' + import { wslDistroHolderKey } from '../discovery/wsl-distro-holder-record' import { readWslDistroRegistryIdShared } from '../discovery/wsl-distro-registry-id' import type { WslOrcadHostTarget } from './wsl-orcad-host-target' @@ -51,48 +56,6 @@ import { import { withOwnBuildLaunchEnv } from './wsl-orcad-own-build-launch-env' import { WSL_NODE_RUNTIME_DOWNLOAD_BUDGET } from '../execution/wsl-node-runtime-download-budget' -/** An update this app carries that the host may not take yet; the incumbent keeps serving. */ -export type WslOrcadDeferredUpdate = WslHostDeferredUpdate - -export type WslOrcadLaunch = - | { - outcome: 'ready' - distro: string - /** The Lxss registration GUID for the deployment record's `distroId`; null if unreadable. */ - distroId: string | null - /** The loopback port orcad bound inside the distro (another one when the preferred was taken). */ - port: number - fullVersion: string - pid: number | null - readiness: ServeReadiness - holder: 'adopted' | 'spawned' | 'unverifiable' - /** An orcad the record did not name (e.g. left by a failed Remove), now recorded. */ - adoptedInstance?: { version: string; pid: number } - /** Set when `fullVersion` is the incumbent because the update must wait. */ - deferredUpdate?: WslOrcadDeferredUpdate - } - | ({ outcome: 'deferred'; distro: string } & WslOrcadDeferredUpdate) - -export type WslOrcadDeployOptions = { - /** The WSL environment's id; keys host-scoped state (wake dedupe). Defaults per distro. */ - environmentId?: string - label?: string - /** Defaults to a connect. */ - intent?: OrcadUpdateIntent - signal?: AbortSignal - /** Defaults to one created over `userData`; the app should pass its shared instance. */ - holder?: WslDistroHolder - createTransport?: (target: WslOrcadHostTarget) => OrcadHostTransport & { dispose?(): void } - readRegistryId?: (distro: string) => Promise - readIncumbent?: typeof readWslOrcadIncumbent - /** This desktop's enrolled pairing, which the incumbent's terminal count authenticates with. */ - pairedOffer?: PairingOffer | null - /** The orcad template to deploy from; defaults to the packaged one (the C10 lane swaps it). */ - templateDir?: string - /** A no-boot connect's running check (E9), re-read before any further wake. */ - requireRunning?: () => Promise -} - /** Until the persisted deployment record (C7) assigns one, the environment is keyed per distro. */ export function defaultWslOrcadEnvironmentId(distro: string): string { return `wsl:${wslDistroHolderKey(distro)}` @@ -242,7 +205,7 @@ async function launchOverTransport( return retried } } - const deferredUpdate: WslOrcadDeferredUpdate = { + const deferredUpdate: WslHostDeferredUpdate = { candidateVersion: deployed.fullVersion, code: await wslOrcadDeferralCode(slot, deployed, appVersion), reason: deployed.reason, diff --git a/src/main/wsl/orcad/wsl-orcad-failed-install-removal.ts b/src/main/wsl/orcad/wsl-orcad-failed-install-removal.ts index 6f1ad81879e..578ffcb8efa 100644 --- a/src/main/wsl/orcad/wsl-orcad-failed-install-removal.ts +++ b/src/main/wsl/orcad/wsl-orcad-failed-install-removal.ts @@ -11,9 +11,12 @@ import { ORCAD_INSTALL_MODEL, remoteInstallDirName } from '../../managed-server/install/remote-install-model' -import { readOrcadGcTransactionPins } from '../../ssh/orcad-gc-transaction-pins' -import { orcadSlotDir, type OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' -import type { OrcadDeployResult } from '../../ssh/orcad-remote-deploy' +import { readOrcadGcTransactionPins } from '../../managed-server/activation/orcad-gc-transaction-pins' +import { + orcadSlotDir, + type OrcadSlotOptions +} from '../../managed-server/activation/orcad-recovery-slot' +import type { OrcadDeployResult } from '../../managed-server/install/orcad-remote-deploy' import { isWslOrcadSlotInUse } from './wsl-orcad-slot-process-probe' export async function removeFailedFreshWslOrcadInstall( 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 e56fa323e75..f0d9ac7435a 100644 --- a/src/main/wsl/orcad/wsl-orcad-held-context.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-held-context.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' const mocks = vi.hoisted(() => { const state: { diff --git a/src/main/wsl/orcad/wsl-orcad-held-context.ts b/src/main/wsl/orcad/wsl-orcad-held-context.ts index 119334493eb..bcef3e8f478 100644 --- a/src/main/wsl/orcad/wsl-orcad-held-context.ts +++ b/src/main/wsl/orcad/wsl-orcad-held-context.ts @@ -1,12 +1,12 @@ import { resolveOrcadRemoteContext } from '../../managed-server/install/orcad-remote-context' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { remoteHostPlatformFromUnameProbe, UNAME_PLATFORM_PROBE_COMMAND, UNAME_PLATFORM_PROBE_MARKER -} from '../../ssh/ssh-remote-platform-detection' -import type { RemoteHostPlatform } from '../../ssh/ssh-remote-platform' +} from '../../ssh/remote-host/ssh-remote-platform-detection' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { LINUX_LIBC_FIRST_PROBE } from '../../node-runtime/linux-libc-probe' import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' import { refuseMissingWslDistro, WslDistroVersion1Error } from '../discovery/wsl-distro-unsupported' diff --git a/src/main/wsl/orcad/wsl-orcad-host-transport.ts b/src/main/wsl/orcad/wsl-orcad-host-transport.ts index 4e2847e163c..b432c690d3f 100644 --- a/src/main/wsl/orcad/wsl-orcad-host-transport.ts +++ b/src/main/wsl/orcad/wsl-orcad-host-transport.ts @@ -6,13 +6,13 @@ import { commandLineLength, MAX_COMMAND_LINE_CHARS } from '../../../shared/windows-command-line-budget' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import type { RemoteCommandChannel } from '../../managed-server/install/remote-install-transport' import { createSshOperationAbortError, type SshExecOptions } from '../../ssh/connection/ssh-exec-options' -import { writeStringViaExecStdin } from '../../ssh/ssh-exec-stdin-file-transfer' +import { writeStringViaExecStdin } from '../../ssh/file-transfer/ssh-exec-stdin-file-transfer' import { resolveWslInteropSpawnCwd } from '../execution/wsl-interop-spawn-directory' import { wrapWslCommandProcess } from '../execution/wsl-command-channel' import { WSL_COMMAND_LOOP_ARGV0, WSL_COMMAND_LOOP_SCRIPT } from '../execution/wsl-command-loop' diff --git a/src/main/wsl/orcad/wsl-orcad-incumbent.ts b/src/main/wsl/orcad/wsl-orcad-incumbent.ts index be1073ba819..3edbb51453b 100644 --- a/src/main/wsl/orcad/wsl-orcad-incumbent.ts +++ b/src/main/wsl/orcad/wsl-orcad-incumbent.ts @@ -8,21 +8,21 @@ import { UNVERIFIABLE_ORCAD_TERMINAL_CENSUS } from '../../../shared/orcad-terminal-census' import type { ServeReadiness } from '../../server/serve-readiness' -import { probeActiveOrcadReadiness } from '../../ssh/orcad-active-readiness' +import { probeActiveOrcadReadiness } from '../../managed-server/activation/orcad-active-readiness' import { orcadBoundPort } from '../../managed-server/lifecycle/orcad-managed-bound-port' import { managedOrcadInstallDir } from '../../managed-server/lifecycle/orcad-managed-runtime-context' import { wakeStoppedManagedOrcad } from '../../managed-server/lifecycle/orcad-managed-wake' import type { OrcadRemoteContext } from '../../managed-server/install/orcad-remote-context' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import type { OrcadSlotOptions } from '../../managed-server/activation/orcad-recovery-slot' import { readRemoteOrcadBuildHash } from '../../managed-server/install/orcad-remote-build-hash' import { requestOrcadTerminalCensus, type OrcadTerminalCensusRequestOptions -} from '../../ssh/orcad-terminal-census-client' -import { updateTerminalCounts } from '../../ssh/orcad-fenced-stop' -import { tunneledOrcadPairingCode } from '../../ssh/orcad-tunneled-pairing' +} from '../../managed-server/lifecycle/orcad-terminal-census-client' +import { updateTerminalCounts } from '../../managed-server/activation/orcad-fenced-stop' +import { tunneledOrcadPairingCode } from '../../managed-server/lifecycle/orcad-tunneled-pairing' import type { StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import type { WslOrcadHostTarget } from './wsl-orcad-host-target' import { listenWslOrcadStdioBridge } from './wsl-orcad-stdio-bridge' diff --git a/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts b/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts index 85e9843e05a..f861a356a7d 100644 --- a/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts +++ b/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts @@ -1,9 +1,9 @@ /** Adopt serving unrecorded orcad under the activation fence only when lock, readiness and installed build identify the same process. Never kill it without census; launching another loses the instance lock. Normal update admission handles version changes. */ +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' import { - ORCAD_LOCK_FILE_NAME, parseOrcadInstanceLockRecord, type OrcadLockRecord -} from '../../orcad/orcad-instance-lock' +} from '../../orcad/orcad-instance-lock-record' import { compareOrcadProcessIdentity } from '../../orcad/orcad-process-start-time' import type { OrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' import { @@ -19,7 +19,7 @@ import { orcadSlotDir, resolveOrcadSlotIdentity, type OrcadSlotOptions -} from '../../ssh/orcad-recovery-slot' +} from '../../managed-server/activation/orcad-recovery-slot' import { ORCAD_PID_FILENAME } from '../../managed-server/install/orcad-remote-host-support' import { parseOrcadReadinessWaitOutput, @@ -33,7 +33,7 @@ import { remoteInstallVersionDirRegex } from '../../managed-server/install/remote-install-model' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' -import { joinRemotePath } from '../../ssh/ssh-remote-platform' +import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { readWslGuestIdentity, wslGuestOrcadIncarnation, diff --git a/src/main/wsl/orcad/wsl-orcad-launch-contract.ts b/src/main/wsl/orcad/wsl-orcad-launch-contract.ts new file mode 100644 index 00000000000..963f3196e40 --- /dev/null +++ b/src/main/wsl/orcad/wsl-orcad-launch-contract.ts @@ -0,0 +1,47 @@ +import type { PairingOffer } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type { WslHostDeferredUpdate } from '../../../shared/wsl-host-types' +import type { ServeReadiness } from '../../server/serve-readiness' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' +import type { OrcadUpdateIntent } from '../../managed-server/lifecycle/orcad-managed-update-decision' +import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' +import type { WslOrcadHostTarget } from './wsl-orcad-host-target' +import type { readWslOrcadIncumbent } from './wsl-orcad-incumbent' + +export type WslOrcadLaunch = + | { + outcome: 'ready' + distro: string + /** The Lxss registration GUID for the deployment record's `distroId`; null if unreadable. */ + distroId: string | null + /** The loopback port orcad bound inside the distro (another one when the preferred was taken). */ + port: number + fullVersion: string + pid: number | null + readiness: ServeReadiness + holder: 'adopted' | 'spawned' | 'unverifiable' + /** An orcad the record did not name (e.g. left by a failed Remove), now recorded. */ + adoptedInstance?: { version: string; pid: number } + /** Set when `fullVersion` is the incumbent because the update must wait. */ + deferredUpdate?: WslHostDeferredUpdate + } + | ({ outcome: 'deferred'; distro: string } & WslHostDeferredUpdate) + +export type WslOrcadDeployOptions = { + /** The WSL environment's id; keys host-scoped state (wake dedupe). Defaults per distro. */ + environmentId?: string + label?: string + /** Defaults to a connect. */ + intent?: OrcadUpdateIntent + signal?: AbortSignal + /** Defaults to one created over `userData`; the app should pass its shared instance. */ + holder?: WslDistroHolder + createTransport?: (target: WslOrcadHostTarget) => OrcadHostTransport & { dispose?(): void } + readRegistryId?: (distro: string) => Promise + readIncumbent?: typeof readWslOrcadIncumbent + /** This desktop's enrolled pairing, which the incumbent's terminal count authenticates with. */ + pairedOffer?: PairingOffer | null + /** The orcad template to deploy from; defaults to the packaged one (the C10 lane swaps it). */ + templateDir?: string + /** A no-boot connect's running check (E9), re-read before any further wake. */ + requireRunning?: () => Promise +} diff --git a/src/main/wsl/orcad/wsl-orcad-liveness-wiring.ts b/src/main/wsl/orcad/wsl-orcad-liveness-wiring.ts index 5c0e141d677..cf57fa12549 100644 --- a/src/main/wsl/orcad/wsl-orcad-liveness-wiring.ts +++ b/src/main/wsl/orcad/wsl-orcad-liveness-wiring.ts @@ -9,7 +9,7 @@ import { type OrcadTerminalCensus, UNVERIFIABLE_ORCAD_TERMINAL_CENSUS } from '../../../shared/orcad-terminal-census' -import { requestOrcadTerminalCensus } from '../../ssh/orcad-terminal-census-client' +import { requestOrcadTerminalCensus } from '../../managed-server/lifecycle/orcad-terminal-census-client' import { subscribeSystemPowerLifecycle } from '../../power/system-power-lifecycle' import { deferUntilWslDistroRunning, diff --git a/src/main/wsl/orcad/wsl-orcad-one-fence-deploy.ts b/src/main/wsl/orcad/wsl-orcad-one-fence-deploy.ts index f6e9f118e01..85af049c4b0 100644 --- a/src/main/wsl/orcad/wsl-orcad-one-fence-deploy.ts +++ b/src/main/wsl/orcad/wsl-orcad-one-fence-deploy.ts @@ -6,8 +6,11 @@ */ import type { OrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' import { wakeExpectedOrcadUnderOneFence } from '../../managed-server/lifecycle/orcad-managed-wake' -import type { OrcadDeployOptions, OrcadDeployResult } from '../../ssh/orcad-remote-deploy' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import type { + OrcadDeployOptions, + OrcadDeployResult +} from '../../managed-server/install/orcad-remote-deploy' +import type { OrcadSlotOptions } from '../../managed-server/activation/orcad-recovery-slot' type DeployExtra = Pick diff --git a/src/main/wsl/orcad/wsl-orcad-own-build-launch-env.ts b/src/main/wsl/orcad/wsl-orcad-own-build-launch-env.ts index 2daf5c99646..25a243d7b91 100644 --- a/src/main/wsl/orcad/wsl-orcad-own-build-launch-env.ts +++ b/src/main/wsl/orcad/wsl-orcad-own-build-launch-env.ts @@ -1,5 +1,5 @@ import { hostMallocTunablesLaunchEnv } from '../../memory/host-malloc-tunables' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' /** An older slot would leak GLIBC_TUNABLES to user shells, so only this build's own slot gets it. */ export function withOwnBuildLaunchEnv( diff --git a/src/main/wsl/orcad/wsl-orcad-pairing-identity.ts b/src/main/wsl/orcad/wsl-orcad-pairing-identity.ts index 759398dd744..52c3a849c2b 100644 --- a/src/main/wsl/orcad/wsl-orcad-pairing-identity.ts +++ b/src/main/wsl/orcad/wsl-orcad-pairing-identity.ts @@ -7,13 +7,13 @@ import { verifyOrcadPairingIdentity, type OrcadTunnelIdentity } from '../../managed-server/lifecycle/orcad-managed-tunnel-identity' -import { tunneledOrcadPairingCode } from '../../ssh/orcad-tunneled-pairing' +import { tunneledOrcadPairingCode } from '../../managed-server/lifecycle/orcad-tunneled-pairing' import { getPreferredPairingOffer } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { buildWithPairingRepair, type ManagedOrcadPairingRecovery } from '../../managed-server/lifecycle/orcad-managed-tunnel-pairing-recovery' -import type { WslOrcadLaunch } from './wsl-orcad-deploy' +import type { WslOrcadLaunch } from './wsl-orcad-launch-contract' /** The managed repair gate a refused enrolled token goes through, for one WSL host. */ export type WslOrcadPairingRecovery = Omit & { diff --git a/src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts b/src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts index d85a4882de5..d35894d34c7 100644 --- a/src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts @@ -19,7 +19,7 @@ import { ORCAD_LAUNCHER_FILENAME, ORCAD_TEMPLATE_MANIFEST_FILENAME } from '../../../shared/orcad-artifacts' -import { requestOrcadTerminalCensus } from '../../ssh/orcad-terminal-census-client' +import { requestOrcadTerminalCensus } from '../../managed-server/lifecycle/orcad-terminal-census-client' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { readConfirmedRunningWslDistros } from '../discovery/wsl-background-distro-gate' import { readWindowsProcessTableFresh } from '../../windows/windows-process-table' diff --git a/src/main/wsl/orcad/wsl-orcad-slot-process-probe.test.ts b/src/main/wsl/orcad/wsl-orcad-slot-process-probe.test.ts index cfcc1df9058..7e6c4994d10 100644 --- a/src/main/wsl/orcad/wsl-orcad-slot-process-probe.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-slot-process-probe.test.ts @@ -14,7 +14,7 @@ vi.mock('../../ssh/remote-exec/remote-exec-command', () => ({ })) import { wslOrcadSlotProcessProbeCommand } from './wsl-orcad-slot-process-probe' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' const host = getRemoteHostPlatform('linux-x64') diff --git a/src/main/wsl/orcad/wsl-orcad-slot-process-probe.ts b/src/main/wsl/orcad/wsl-orcad-slot-process-probe.ts index 1ceaf74e1f2..6e3e6213257 100644 --- a/src/main/wsl/orcad/wsl-orcad-slot-process-probe.ts +++ b/src/main/wsl/orcad/wsl-orcad-slot-process-probe.ts @@ -6,8 +6,8 @@ import { execCommand, isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' -import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' +import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import type { OrcadSlotOptions } from '../../managed-server/activation/orcad-recovery-slot' // Every shell running this probe carries it in argv, so the probe never counts itself. const PROBE_MARKER = '__ORCA_SLOT_PROCESS_PROBE__' 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 486f8acd6d3..25a5e178315 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 @@ -1,7 +1,10 @@ import { connect, createServer, type Server, type Socket } from 'node:net' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as ProcessHost from '@orca/process-host' -import { checkOrcadStdioBridge, openOrcadStdioBridgeChannel } from '../../ssh/orcad-stdio-bridge' +import { + checkOrcadStdioBridge, + openOrcadStdioBridgeChannel +} from '../../managed-server/lifecycle/orcad-stdio-bridge' import type { StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' import { fakeWslBridgeChildren, diff --git a/src/main/wsl/orcad/wsl-orcad-stdio-bridge.test.ts b/src/main/wsl/orcad/wsl-orcad-stdio-bridge.test.ts index 5998eca166a..596537b75eb 100644 --- a/src/main/wsl/orcad/wsl-orcad-stdio-bridge.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-stdio-bridge.test.ts @@ -1,6 +1,9 @@ import { connect, type Server, type Socket } from 'node:net' import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest' -import { checkOrcadStdioBridge, openOrcadStdioBridgeChannel } from '../../ssh/orcad-stdio-bridge' +import { + checkOrcadStdioBridge, + openOrcadStdioBridgeChannel +} from '../../managed-server/lifecycle/orcad-stdio-bridge' import { ORCAD_STDIO_BRIDGE_MAX_CHANNELS } from '../../managed-server/lifecycle/orcad-stdio-bridge-listener' import { startEchoServer } from '../../managed-server/lifecycle/orcad-stdio-bridge-test-channel' import type { StartedPortForward } from '../../ssh/port-forwarding/ssh-port-forward-provider' diff --git a/src/main/wsl/orcad/wsl-orcad-stdio-bridge.ts b/src/main/wsl/orcad/wsl-orcad-stdio-bridge.ts index 4824a2c2cd5..125d3afd658 100644 --- a/src/main/wsl/orcad/wsl-orcad-stdio-bridge.ts +++ b/src/main/wsl/orcad/wsl-orcad-stdio-bridge.ts @@ -3,7 +3,7 @@ import { observeWslOrcadBridgeChannel, type WslOrcadBridgeChannelEvents } from './wsl-orcad-bridge-activity' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { ORCAD_STDIO_BRIDGE_DEPENDENCIES, startOrcadStdioBridge, diff --git a/src/main/wsl/orcad/wsl-orcad-update-admission-move-hold.test.ts b/src/main/wsl/orcad/wsl-orcad-update-admission-move-hold.test.ts index 620348e4bbd..3fe218eeae8 100644 --- a/src/main/wsl/orcad/wsl-orcad-update-admission-move-hold.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-update-admission-move-hold.test.ts @@ -2,13 +2,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { ORCAD_UPDATE_WSL_MOVE_RUNNING_CODE } from '../../../shared/wsl-host-types' import type { OrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' import type { ServeReadiness } from '../../server/serve-readiness' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { OrcadSlotOptions } from '../../managed-server/activation/orcad-recovery-slot' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { admitWslOrcadUpdate } from './wsl-orcad-update-admission' const { adoptRunningOrcadVersion } = vi.hoisted(() => ({ adoptRunningOrcadVersion: vi.fn() })) -vi.mock('../../ssh/orcad-running-version-adoption', () => ({ adoptRunningOrcadVersion })) +vi.mock('../../managed-server/activation/orcad-running-version-adoption', () => ({ + adoptRunningOrcadVersion +})) vi.mock('../../managed-server/activation/orcad-activation-record-store', () => ({ readOrcadActivationRecord: vi.fn() })) diff --git a/src/main/wsl/orcad/wsl-orcad-update-admission.test.ts b/src/main/wsl/orcad/wsl-orcad-update-admission.test.ts index f0a281dbe6b..c70b8748039 100644 --- a/src/main/wsl/orcad/wsl-orcad-update-admission.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-update-admission.test.ts @@ -4,8 +4,8 @@ import type { OrcadActivationRecord } from '../../managed-server/activation/orca import { recordOrcadUpdateFailedThisLaunch } from '../../managed-server/lifecycle/orcad-managed-update-failure-memory' import type { ServeReadiness } from '../../server/serve-readiness' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' +import type { OrcadSlotOptions } from '../../managed-server/activation/orcad-recovery-slot' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { admitWslOrcadUpdate } from './wsl-orcad-update-admission' const { adoptRunningOrcadVersion, readOrcadActivationRecord } = vi.hoisted(() => ({ @@ -13,7 +13,9 @@ const { adoptRunningOrcadVersion, readOrcadActivationRecord } = vi.hoisted(() => readOrcadActivationRecord: vi.fn() })) -vi.mock('../../ssh/orcad-running-version-adoption', () => ({ adoptRunningOrcadVersion })) +vi.mock('../../managed-server/activation/orcad-running-version-adoption', () => ({ + adoptRunningOrcadVersion +})) vi.mock('../../managed-server/activation/orcad-activation-record-store', () => ({ readOrcadActivationRecord })) diff --git a/src/main/wsl/orcad/wsl-orcad-update-admission.ts b/src/main/wsl/orcad/wsl-orcad-update-admission.ts index 92f9359b150..72b2357ba90 100644 --- a/src/main/wsl/orcad/wsl-orcad-update-admission.ts +++ b/src/main/wsl/orcad/wsl-orcad-update-admission.ts @@ -4,7 +4,7 @@ import { ORCAD_UPDATE_WSL_MOVE_RUNNING_CODE, type WslHostDeferredUpdate } from '../../../shared/wsl-host-types' -import { refuseOrcadHostDowngrade } from '../../ssh/orcad-host-version-admission' +import { refuseOrcadHostDowngrade } from '../../managed-server/activation/orcad-host-version-admission' import type { ServeReadiness } from '../../server/serve-readiness' import type { OrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' import { readOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record-store' @@ -22,10 +22,10 @@ import { type OrcadUpdateFailure, type OrcadUpdateFailureHost } from '../../managed-server/lifecycle/orcad-managed-update-failure-memory' -import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../../ssh/orcad-installed-activation' -import type { OrcadSlotOptions } from '../../ssh/orcad-recovery-slot' -import { adoptRunningOrcadVersion } from '../../ssh/orcad-running-version-adoption' -import type { WslOrcadLaunch } from './wsl-orcad-deploy' +import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../../managed-server/activation/orcad-installed-activation' +import type { OrcadSlotOptions } from '../../managed-server/activation/orcad-recovery-slot' +import { adoptRunningOrcadVersion } from '../../managed-server/activation/orcad-running-version-adoption' +import type { WslOrcadLaunch } from './wsl-orcad-launch-contract' type WslOrcadReadyLaunch = Extract diff --git a/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts b/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts index 1b275ae664d..4ced00c4809 100644 --- a/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts @@ -32,8 +32,8 @@ import { isWslMoveRunning, isWslMoveUnderwayOnHost } from '../../persistence/moving-wsl-projects/wsl-move-running-moves' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import type { WslDistroHolder } from '../discovery/wsl-distro-holder-types' import type { WslOrcadHostTarget } from './wsl-orcad-host-target' @@ -73,7 +73,7 @@ vi.mock('../../managed-server/install/remote-versioned-install', async (importOr vi.mock('./wsl-orcad-instance-adoption', () => ({ adoptUnrecordedWslOrcad: async () => ({ outcome: 'none' }) })) -vi.mock('../../ssh/orcad-running-version-adoption', () => ({ +vi.mock('../../managed-server/activation/orcad-running-version-adoption', () => ({ adoptRunningOrcadVersion: host.adoptRunning })) vi.mock('../../ssh/remote-exec/remote-exec-command', () => ({ execCommand: host.exec })) @@ -86,7 +86,7 @@ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ vi.mock('../../orcad/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) -vi.mock('../../ssh/orcad-remote-deploy', () => ({ deployOrcad: host.deploy })) +vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: host.deploy })) vi.mock('../../managed-server/lifecycle/orcad-managed-version-gc', () => ({ provenLiveDaemonVersion: () => null, pruneManagedOrcadVersions: vi.fn() diff --git a/src/main/wsl/orcad/wsl-orcad-watch.test.ts b/src/main/wsl/orcad/wsl-orcad-watch.test.ts index ca0f0489162..7e027c635e4 100644 --- a/src/main/wsl/orcad/wsl-orcad-watch.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-watch.test.ts @@ -1,6 +1,6 @@ import { createServer, type Server, type Socket } from 'node:net' import { afterEach, describe, expect, it } from 'vitest' -import { openOrcadStdioBridgeChannel } from '../../ssh/orcad-stdio-bridge' +import { openOrcadStdioBridgeChannel } from '../../managed-server/lifecycle/orcad-stdio-bridge' import { fakeWslBridgeChildren, posixOrcadStdioBridge diff --git a/src/main/wsl/orcad/wsl-orcad-watch.ts b/src/main/wsl/orcad/wsl-orcad-watch.ts index 6b4a670ea37..0eb93f9f730 100644 --- a/src/main/wsl/orcad/wsl-orcad-watch.ts +++ b/src/main/wsl/orcad/wsl-orcad-watch.ts @@ -1,6 +1,9 @@ /** Hold an unwritten bridge as liveness watch/port probe: orcad closes it on socket loss or distro stop. Measured exits arrive ~69ms/~40ms respectively; exit codes still require independent liveness evidence. */ -import type { OrcadHostTransport } from '../../ssh/orcad-host-transport' -import { openOrcadStdioBridgeChannel, resolveOrcadStdioBridge } from '../../ssh/orcad-stdio-bridge' +import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' +import { + openOrcadStdioBridgeChannel, + resolveOrcadStdioBridge +} from '../../managed-server/lifecycle/orcad-stdio-bridge' import { OrcadStdioBridgeDecoder, type OrcadStdioBridgeSignal diff --git a/src/preload/api/agent-status-api.ts b/src/preload/api/agent-status-api.ts index d34fa917782..5df1f88ef65 100644 --- a/src/preload/api/agent-status-api.ts +++ b/src/preload/api/agent-status-api.ts @@ -7,6 +7,7 @@ import type { import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' import type { ComputerAwakeStatus } from '../../shared/computer-awake-mode' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' export type AgentStatusApi = { /** Listen for agent status updates forwarded from native hook receivers. */ @@ -45,6 +46,8 @@ export type AgentStatusApi = { /** Lift one pane's retirement fence when a live PTY re-attaches to it. Closed tabs stay retired. */ restorePaneAuthority: (paneKey: string) => void transferPaneAuthority: (args: { fromPaneKey: string; toPaneKey: string; ptyId?: string }) => void + /** The Agents list's verdicts, for worktree.ps to show paired clients. Fire-and-forget. */ + publishListVerdicts?: (publication: AgentListPublication | null) => void } export type AgentAwakeApi = { diff --git a/src/preload/api/agent-status-bridge.ts b/src/preload/api/agent-status-bridge.ts index dbf6ebb6f86..1a57c712b49 100644 --- a/src/preload/api/agent-status-bridge.ts +++ b/src/preload/api/agent-status-bridge.ts @@ -7,6 +7,7 @@ import type { } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' +import type { AgentListPublication } from '../../shared/agent-status/presentation/agent-list-status' import type { PreloadApi } from '../api-types' export const agentStatusApi = { @@ -72,6 +73,9 @@ export const agentStatusApi = { dropPersistedBatch: (identities: readonly AgentStatusCacheIdentity[]): void => { ipcRenderer.send('agentStatus:dropPersistedBatch', identities) }, + publishListVerdicts: (publication: AgentListPublication | null): void => { + ipcRenderer.send('agentStatus:listVerdicts', publication) + }, reconcileEndedProcess: (paneKey: string): void => { ipcRenderer.send('agentStatus:reconcileEndedProcess', paneKey) }, diff --git a/src/preload/api/gh-bridge-mutations-and-projects.ts b/src/preload/api/gh-bridge-mutations-and-projects.ts index f687a91f02d..a057485be6d 100644 --- a/src/preload/api/gh-bridge-mutations-and-projects.ts +++ b/src/preload/api/gh-bridge-mutations-and-projects.ts @@ -94,8 +94,9 @@ export const ghMutationsAndProjectsApi = { sourceContext?: TaskSourceContext | null number: number updates: unknown - }): Promise<{ ok: true } | { ok: false; error: string }> => - ipcRenderer.invoke('gh:updateIssue', args), + }): Promise< + { ok: true; bodyImageUrls?: Record } | { ok: false; error: string } + > => ipcRenderer.invoke('gh:updateIssue', args), addIssueComment: (args: { repoPath: string repoId?: string | null diff --git a/src/preload/api/github-work-item-api.ts b/src/preload/api/github-work-item-api.ts index 52c6a93314f..f4ce0fc4d66 100644 --- a/src/preload/api/github-work-item-api.ts +++ b/src/preload/api/github-work-item-api.ts @@ -120,7 +120,7 @@ export type GithubWorkItemApi = { updates: GitHubIssueUpdate ownerRepo?: GitHubOwnerRepo } - ) => Promise<{ ok: true } | { ok: false; error: string }> + ) => Promise<{ ok: true; bodyImageUrls?: Record } | { ok: false; error: string }> addIssueComment: ( args: GitHubRepoSelectorArgs & { number: number diff --git a/src/preload/api/runtime-api.ts b/src/preload/api/runtime-api.ts index 8c7d1f57133..5a590a01475 100644 --- a/src/preload/api/runtime-api.ts +++ b/src/preload/api/runtime-api.ts @@ -9,10 +9,10 @@ import type { RuntimeHostStatusSnapshot } from '../../shared/remote-runtime/host import type { RuntimeBrowserDriverState, RuntimeRendererSyncWindowGraph, - RuntimeStatus, RuntimeSyncWindowGraphResult, RuntimeTerminalDriverState } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' import type { ClientHostedBrowserRowsEvent } from '../../shared/client-hosted-browser-rows' import type { SidebarInputsChangedEvent } from '../../shared/sidebar-list/sidebar-inputs-feed-contract' diff --git a/src/preload/api/runtime-environments-bridge.ts b/src/preload/api/runtime-environments-bridge.ts index e72707f68ea..715605b216f 100644 --- a/src/preload/api/runtime-environments-bridge.ts +++ b/src/preload/api/runtime-environments-bridge.ts @@ -4,7 +4,7 @@ import { type RuntimeHostStatusSnapshot } from '../../shared/remote-runtime/host-status/runtime-host-status' import type { VerifyAndAddRuntimeEnvironmentResult } from '../../shared/remote-runtime/pairing/remote-pairing-verification' -import type { RuntimeStatus } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-session-contracts' import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' import type { PublicKnownRuntimeEnvironment, diff --git a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts index b7638093379..ed9e8eb9b0a 100644 --- a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts +++ b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts @@ -11,6 +11,10 @@ import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import type { TerminalSurfaceCloseTarget } from '../../shared/workspace-layout/terminal-surface-close-target' import type { ClipboardImageThumbnail } from '../../shared/clipboard-image' import type { ReadClipboardTextOptions } from '../../shared/clipboard-text' +import type { + AgentPaneActivityReply, + AgentPaneActivityRequest +} from '../../shared/agent-status/presentation/agent-list-status' import type { PreloadApi } from '../api-types' export const uiClipboardAndWindowControlsApi = { @@ -85,6 +89,15 @@ export const uiClipboardAndWindowControlsApi = { ipcRenderer.on('ui:resumeSleepingAgents', listener) return () => ipcRenderer.removeListener('ui:resumeSleepingAgents', listener) }, + onApplyAgentPaneActivity: (callback: (data: AgentPaneActivityRequest) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: AgentPaneActivityRequest) => + callback(data) + ipcRenderer.on('ui:applyAgentPaneActivity', listener) + return () => ipcRenderer.removeListener('ui:applyAgentPaneActivity', listener) + }, + replyAgentPaneActivity: (reply: AgentPaneActivityReply): void => { + ipcRenderer.send('ui:agentPaneActivityReply', reply) + }, onTerminalZoom: (callback: (direction: 'in' | 'out' | 'reset') => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, direction: 'in' | 'out' | 'reset') => callback(direction) diff --git a/src/preload/api/ui-command-event-api.ts b/src/preload/api/ui-command-event-api.ts index cfb796cc184..f9895cec986 100644 --- a/src/preload/api/ui-command-event-api.ts +++ b/src/preload/api/ui-command-event-api.ts @@ -26,6 +26,10 @@ import type { TerminalPaneRevealReply, TerminalPaneRevealRequest } from '../../shared/workspace-layout/terminal-pane-reveal' +import type { + AgentPaneActivityReply, + AgentPaneActivityRequest +} from '../../shared/agent-status/presentation/agent-list-status' import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation' import type { ProjectMovePauseRequest, @@ -225,6 +229,8 @@ export type UiCommandEventApi = { onLaunchRecipe: (callback: (data: PaneLaunchRecipe) => void) => () => void onRevealTerminalPane: (callback: (data: TerminalPaneRevealRequest) => void) => () => void replyTerminalPaneReveal: (reply: TerminalPaneRevealReply) => void + onApplyAgentPaneActivity: (callback: (data: AgentPaneActivityRequest) => void) => () => void + replyAgentPaneActivity: (reply: AgentPaneActivityReply) => void onSplitTerminal: ( callback: (data: { tabId: string diff --git a/src/renderer/src/app-shell/AppBackgroundServices.tsx b/src/renderer/src/app-shell/AppBackgroundServices.tsx index d1c9ce9c824..0fa98b6070d 100644 --- a/src/renderer/src/app-shell/AppBackgroundServices.tsx +++ b/src/renderer/src/app-shell/AppBackgroundServices.tsx @@ -12,8 +12,12 @@ import { ActiveWorkspaceSyncGate } from './ActiveWorkspaceSyncGate' import { StructuredAgentSessionAttentionBridge } from '../components/native-chat/session/attention/StructuredAgentSessionAttentionBridge' import { StructuredAgentSessionStatusBridge } from '../components/native-chat/session/status/StructuredAgentSessionStatusBridge' import { NativeChatVisualGuestThemePublisher } from '../components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher' +import { usePairedMobileDevices } from '../components/mobile/paired-mobile-devices' const DashboardPopoutBridge = lazy(() => import('../components/dashboard/DashboardPopoutBridge')) +const AgentListVerdictPublisher = lazy( + () => import('../components/activity/agent-list-verdict-publisher') +) /** Isolate high-churn subscriptions from App rendering; services outlive their consuming surfaces. */ export function AppBackgroundServices(): React.JSX.Element { @@ -21,6 +25,9 @@ export function AppBackgroundServices(): React.JSX.Element { const dashboardPopoutEnabled = useAppStore( (s) => s.settings?.experimentalAgentDashboardPopout === true ) + const canPublishAgentList = Boolean(window.api.agentStatus?.publishListVerdicts) + // The list builds on every agent update, so only a desktop with a paired phone pays for it. + const { hasPairedDevice } = usePairedMobileDevices({ enabled: canPublishAgentList }) return ( <> @@ -40,6 +47,12 @@ export function AppBackgroundServices(): React.JSX.Element { ) : null} + {/* Paired phones list agents with the desktop Agents list's verdicts; web clients have no host to tell. */} + {canPublishAgentList && hasPairedDevice ? ( + + + + ) : null} {/* Background chats have no mounted pane but still need completion attention. */} diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 996f314de67..f5412aa291f 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -588,6 +588,42 @@ body[data-modal-overlay-open] [data-toasts-raised] [data-sonner-toaster] { margin-left: 0; } +/* Why: Sonner's 24px buttons with untokened fills don't match Orca; mirror Button size="sm" default/secondary. */ +[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-button] { + height: 2rem; + padding: 0 0.75rem; + border-radius: calc(var(--radius) - 2px); + font-size: 0.875rem; + font-weight: 500; + background: var(--primary); + color: var(--primary-foreground); + transition: + opacity 0.4s, + box-shadow 0.2s, + background-color 150ms; +} + +[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-button]:hover { + background: color-mix(in oklab, var(--primary) 90%, transparent); +} + +[data-sonner-toaster][data-sonner-theme] + [data-sonner-toast][data-styled='true'] + [data-button][data-cancel] { + background: var(--secondary); + color: var(--secondary-foreground); +} + +[data-sonner-toaster][data-sonner-theme] + [data-sonner-toast][data-styled='true'] + [data-button][data-cancel]:hover { + background: color-mix(in oklab, var(--secondary) 80%, transparent); +} + +[data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-button]:focus-visible { + box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent); +} + [data-sonner-toaster] [data-sonner-toast][data-styled='true'] [data-title] { line-height: 1.35; } diff --git a/src/renderer/src/components/AgentStateDot.tsx b/src/renderer/src/components/AgentStateDot.tsx index 1cbc1ca512b..f9449bdfb64 100644 --- a/src/renderer/src/components/AgentStateDot.tsx +++ b/src/renderer/src/components/AgentStateDot.tsx @@ -14,25 +14,11 @@ import { StateIndicatorTooltip, type StateIndicatorTooltipSide } from '@/components/StateIndicatorTooltip' +import type { AgentListStatus } from '../../../shared/agent-status/presentation/agent-list-status' // Share state glyphs across agent surfaces. Keep the agent identity icon separate; completion uses a check while sidebar StatusIndicator uses an emerald dot/tooltip. -export type AgentDotState = - | 'working' - | 'monitoring' - | 'blocked' - | 'waiting' - | 'interrupted' - // Transcript-derived failure is an outcome, distinct from live blocked attention. - | 'failed' - | 'done' - | 'idle' - // A live PTY with stale reporting proves only missing evidence, not idle/work/completion. - | 'unverifiable' - // The turn ended without a proven outcome; use the missing-evidence glyph, never completion. - | 'unconfirmed' - // Sidebar combines blocked/waiting as permission; retain its vocabulary with the shared question glyph/token. - | 'permission' +export type AgentDotState = AgentListStatus /** Return the accessible label shared by every visual agent-state marker. */ export function agentStateLabel(state: AgentDotState): string { diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index 1a10320518e..b3214247197 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -22,7 +22,7 @@ import { DEFAULT_DISABLED_TUI_AGENTS, filterEnabledTuiAgents } from '../../../shared/agent-launch/catalog/tui-agent-selection' -import type { RuntimeStatus } from '../../../shared/runtime-types' +import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { NewWorkspaceComposerAdvancedSection } from './new-workspace/NewWorkspaceComposerAdvancedSection' import { NewWorkspaceComposerAgentSection } from './new-workspace/NewWorkspaceComposerAgentSection' diff --git a/src/renderer/src/components/activity/activity-paired-client-change.ts b/src/renderer/src/components/activity/activity-paired-client-change.ts new file mode 100644 index 00000000000..401dcc2d718 --- /dev/null +++ b/src/renderer/src/components/activity/activity-paired-client-change.ts @@ -0,0 +1,37 @@ +import { useAppStore } from '@/store' +import type { + AgentListPublication, + AgentPaneActivityChange +} from '../../../../shared/agent-status/presentation/agent-list-status' +import { clearActivityThread } from './activity-clear-completed' +import { publishAgentListNow, readPublishedAgentPaneThreads } from './agent-list-verdict-publisher' + +/** Applies a paired client's change with the same actions as the Agents list row, then answers with the list it leaves. */ +export function applyPairedClientActivityChange( + change: AgentPaneActivityChange +): Promise { + const state = useAppStore.getState() + const threads = readPublishedAgentPaneThreads() + // Unhydrated maps are empty, and main would persist them over the saved ones. + if (!state.persistedUIReady || !threads) { + throw new Error('agent_activity_not_ready') + } + if (change.kind === 'read') { + state.acknowledgeAgents(change.paneKeys, undefined, 'explicit') + } else if (change.kind === 'unread') { + state.unacknowledgeAgents(change.paneKeys) + } else { + const paneKeys = new Set(change.paneKeys) + let cleared = 0 + for (const thread of threads) { + if (paneKeys.has(thread.paneKey) && clearActivityThread(thread)) { + cleared += 1 + } + } + // Answering success would let the phone drop its guess and show the row again with no word why. + if (cleared === 0) { + throw new Error('agent_activity_not_clearable') + } + } + return publishAgentListNow() +} diff --git a/src/renderer/src/components/activity/activity-thread-child-agent.ts b/src/renderer/src/components/activity/activity-thread-child-agent.ts index 3b6c75339f9..2f2297f3d04 100644 --- a/src/renderer/src/components/activity/activity-thread-child-agent.ts +++ b/src/renderer/src/components/activity/activity-thread-child-agent.ts @@ -46,6 +46,14 @@ function firstReportedTerminalHandle(thread: ChildAgentClassifiableThread): stri export function collectHiddenChildAgentPaneKeys( threads: readonly ChildAgentClassifiableThread[] ): Set { + return classifyChildAgents(threads).hidden +} + +/** Each child's parent and the children a hidden-children view folds away. */ +export function classifyChildAgents(threads: readonly ChildAgentClassifiableThread[]): { + parentPaneKeyByChild: Map + hidden: Set +} { const baseRows: AgentLineageSourceRow[] = threads.map((thread) => ({ paneKey: thread.paneKey, entry: { terminalHandle: firstReportedTerminalHandle(thread) } @@ -83,11 +91,18 @@ export function collectHiddenChildAgentPaneKeys( const livePaneKeys = new Set( threads.filter((thread) => thread.currentAgentState).map((thread) => thread.paneKey) ) + const tree = buildAgentRowLineageTree(rows) + const parentPaneKeyByChild = new Map() + for (const [parentPaneKey, children] of tree.childrenByParentPaneKey) { + for (const child of children) { + parentPaneKeyByChild.set(child.paneKey, parentPaneKey) + } + } const hidden = new Set() - for (const paneKey of buildAgentRowLineageTree(rows).childPaneKeys) { + for (const paneKey of tree.childPaneKeys) { if (!livePaneKeys.has(paneKey)) { hidden.add(paneKey) } } - return hidden + return { parentPaneKeyByChild, hidden } } diff --git a/src/renderer/src/components/activity/activity-thread-grouping.ts b/src/renderer/src/components/activity/activity-thread-grouping.ts index 997a0404437..1fcea62126c 100644 --- a/src/renderer/src/components/activity/activity-thread-grouping.ts +++ b/src/renderer/src/components/activity/activity-thread-grouping.ts @@ -10,30 +10,14 @@ import { agentMeta, agentSummary, agentTitle, - threadAgentStateLabel, - type ActivityThreadStatusId + threadAgentStateLabel } from './activity-thread-presentation' +import { AGENT_LIST_STATUS_RANK } from '../../../../shared/agent-status/presentation/agent-list-status' import type { ActivityGroupBy } from '../../../../shared/agents-view-thread-filters' import type { ActivityThreadGroup, AgentPaneThread } from './activity-thread-types' -// Use exhaustive, unique attention ranks so new states fail typecheck and recency cannot reorder headers. -const ACTIVITY_STATUS_GROUP_RANK: Record = { - waiting: 0, - blocked: 1, - permission: 2, - failed: 3, - unconfirmed: 4, - working: 5, - monitoring: 6, - // A user's Stop is not news, so it follows live work, but it is not a finish either. - interrupted: 7, - unverifiable: 8, - done: 9, - idle: 10 -} - function activityStatusRank(thread: AgentPaneThread): number { - return ACTIVITY_STATUS_GROUP_RANK[activityThreadStatusId(thread)] + return AGENT_LIST_STATUS_RANK[activityThreadStatusId(thread)] } export function getActivityThreadGroup( diff --git a/src/renderer/src/components/activity/agent-list-verdict-publisher.ts b/src/renderer/src/components/activity/agent-list-verdict-publisher.ts new file mode 100644 index 00000000000..862eb825ddf --- /dev/null +++ b/src/renderer/src/components/activity/agent-list-verdict-publisher.ts @@ -0,0 +1,134 @@ +import { useEffect, useMemo, useState } from 'react' +import { useAppStore } from '@/store' +import type { + AgentListPublication, + AgentListVerdict +} from '../../../../shared/agent-status/presentation/agent-list-status' +import { isClearableActivityThread } from './activity-clear-completed' +import { classifyChildAgents } from './activity-thread-child-agent' +import { activityThreadStatusId } from './activity-thread-presentation' +import type { AgentPaneThread } from './activity-thread-types' +import { useAllAgentPaneThreads } from './use-agent-pane-threads' + +const PUBLISH_INTERVAL_MS = 250 + +/** The Agents list's verdict for every pane the window knows; a pane with no thread is unlisted. */ +function buildAgentListVerdicts( + threads: readonly AgentPaneThread[], + knownPaneKeys: readonly string[] +): Record { + const { parentPaneKeyByChild, hidden } = classifyChildAgents(threads) + const verdicts: Record = {} + for (const paneKey of knownPaneKeys) { + verdicts[paneKey] = { listed: false } + } + for (const thread of threads) { + const childOf = parentPaneKeyByChild.get(thread.paneKey) + verdicts[thread.paneKey] = { + listed: true, + status: activityThreadStatusId(thread), + unread: thread.unread, + clearable: isClearableActivityThread(thread), + sortAt: thread.latestTimestamp, + title: thread.paneTitle, + ...(childOf ? { childOf } : {}), + ...(hidden.has(thread.paneKey) ? { foldedChild: true as const } : {}) + } + } + return verdicts +} + +// One publisher per window; a paired client's change reads its threads and waits for its next publish. +let published: { threads: readonly AgentPaneThread[]; publication: AgentListPublication } | null = + null +let requestRender: (() => void) | null = null +let waiters: ((publication: AgentListPublication) => void)[] = [] +let lastSentVerdicts: string | null = null +let lastSentAt = 0 +let timer: ReturnType | null = null + +function send(publication: AgentListPublication): void { + if (timer !== null) { + clearTimeout(timer) + timer = null + } + lastSentAt = Date.now() + const verdicts = JSON.stringify(publication.verdicts) + if (verdicts !== lastSentVerdicts) { + lastSentVerdicts = verdicts + window.api.agentStatus.publishListVerdicts?.(publication) + } +} + +/** The threads behind the last published verdicts; null until the publisher has run. */ +export function readPublishedAgentPaneThreads(): readonly AgentPaneThread[] | null { + return published?.threads ?? null +} + +/** Resolves with the verdicts once the publisher has rendered the store as it is now. */ +export function publishAgentListNow(): Promise { + const render = requestRender + if (!render) { + return Promise.reject(new Error('agent_activity_not_ready')) + } + return new Promise((resolve) => { + waiters.push(resolve) + render() + }) +} + +/** Sends the desktop Agents list's verdicts to main, so worktree.ps shows paired clients the same list. */ +export default function AgentListVerdictPublisher(): null { + const ready = useAppStore((s) => s.persistedUIReady) + // The unscoped list: view filters and the child-agent toggle only narrow what one surface shows. + const { storeData, allThreads } = useAllAgentPaneThreads() + const [renderRequest, setRenderRequest] = useState(0) + useEffect(() => { + requestRender = () => setRenderRequest((count) => count + 1) + return () => { + requestRender = null + published = null + lastSentVerdicts = null + // Unmounted with no phone paired: stale verdicts would hide new agents from a later pairing. + window.api.agentStatus.publishListVerdicts?.(null) + if (timer !== null) { + clearTimeout(timer) + timer = null + } + } + }, []) + const verdicts = useMemo( + () => buildAgentListVerdicts(allThreads, Object.keys(storeData.agentStatusByPaneKey)), + [allThreads, storeData.agentStatusByPaneKey] + ) + useEffect(() => { + // Unhydrated read stamps would mark every agent unread. + if (!ready) { + return + } + const publication = { publishedAt: Date.now(), verdicts } + published = { threads: allThreads, publication } + const pending = waiters + waiters = [] + if (pending.length > 0) { + send(publication) + for (const resolve of pending) { + resolve(publication) + } + return + } + // Each run reschedules from the last send, so a busy store cannot starve the publish. + const scheduled = setTimeout( + () => published && send(published.publication), + Math.max(0, lastSentAt + PUBLISH_INTERVAL_MS - Date.now()) + ) + timer = scheduled + return () => { + clearTimeout(scheduled) + if (timer === scheduled) { + timer = null + } + } + }, [ready, allThreads, verdicts, renderRequest]) + return null +} diff --git a/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts b/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts index 4e647f4f26f..cc2aac04cb3 100644 --- a/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts +++ b/src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts @@ -16,7 +16,7 @@ import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' -export type AgentPaneThreadsStoreData = Pick< +export type AllAgentPaneThreadsStoreData = Pick< AppState, | 'agentStatusByPaneKey' | 'runtimeAgentOrchestrationByPaneKey' @@ -39,11 +39,20 @@ export type AgentPaneThreadsStoreData = Pick< worktreeMap: ReturnType repoMap: ReturnType generatedTitlesEnabled: boolean +} + +export type AgentPaneThreadsStoreData = AllAgentPaneThreadsStoreData & { /** Focused-host fallback for hostless worktrees, shared by the scope filter and the row actions. */ defaultHostId: ExecutionHostId } -export function useAgentPaneThreadStoreData(): AgentPaneThreadsStoreData { +/** Focused-host fallback for the scope filter and row actions; the unscoped list never reads it. */ +export function useAgentPaneThreadsDefaultHostId(): ExecutionHostId { + return useAppStore((s) => getSettingsFocusedExecutionHostId(s.settings)) +} + +/** Store inputs for every Activity thread, before any view scope. */ +export function useAllAgentPaneThreadStoreData(): AllAgentPaneThreadsStoreData { // Keep original native tabs for owner-qualified names; preserve terminal projections across focus writes. const tabProjectionRef = useRef<{ raw: AppState['unifiedTabsByWorktree'] | null @@ -77,8 +86,7 @@ export function useAgentPaneThreadStoreData(): AgentPaneThreadsStoreData { activityClearedAtByPaneKey: s.activityClearedAtByPaneKey, acknowledgeAgents: s.acknowledgeAgents, unacknowledgeAgents: s.unacknowledgeAgents, - generatedTitlesEnabled: s.settings?.tabAutoGenerateTitle === true, - defaultHostId: getSettingsFocusedExecutionHostId(s.settings) + generatedTitlesEnabled: s.settings?.tabAutoGenerateTitle === true })) ) } diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.ts b/src/renderer/src/components/activity/use-agent-pane-threads.ts index 32836ff12b8..e32bb3c9ec2 100644 --- a/src/renderer/src/components/activity/use-agent-pane-threads.ts +++ b/src/renderer/src/components/activity/use-agent-pane-threads.ts @@ -4,8 +4,10 @@ import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structur import { buildActivityEvents, createActivityEventBuildCache } from './activity-event-builder' import { freshActivityLiveAgentState } from './activity-event-state' import { - useAgentPaneThreadStoreData, - type AgentPaneThreadsStoreData + useAgentPaneThreadsDefaultHostId, + useAllAgentPaneThreadStoreData, + type AgentPaneThreadsStoreData, + type AllAgentPaneThreadsStoreData } from './use-agent-pane-thread-store-data' import { buildAgentPaneThreads, createAgentPaneThreadReuseCache } from './activity-thread-builder' import { collectHiddenChildAgentPaneKeys } from './activity-thread-child-agent' @@ -34,56 +36,12 @@ const EMPTY_ACTIVITY_BUILD: ReturnType = { paneEntryByPaneKey: {} } -/** Shared Activity/sidebar pipeline: store data to events, threads, filters and groups. */ -export function useAgentPaneThreads(args: { - query: string - readFilter: ThreadReadFilter - groupBy: ActivityGroupBy - selectedPaneKey: string | null - showChildAgents?: boolean - /** Prepare only live badge rows, omitting list groups and bulk-action sets. */ - badgeOnly?: boolean -}): { - storeData: AgentPaneThreadsStoreData +/** Every Activity thread before any view filter: store data to events and threads. */ +export function useAllAgentPaneThreads({ badgeOnly = false }: { badgeOnly?: boolean } = {}): { + storeData: AllAgentPaneThreadsStoreData allThreads: AgentPaneThread[] - selectedPaneKeyIsLive: boolean - effectiveSelectedPaneKey: string | null - /** Every active view filter applies here; destructive Clear completed must not touch hidden rows. */ - visibleThreads: AgentPaneThread[] - /** Badge-coherent threads after child classification; ignore transient search/scope/read filters so Mark all read can clear the badge. */ - markAllReadThreads: AgentPaneThread[] - visibleThreadGroups: ActivityThreadGroup[] } { - const { - query, - readFilter, - groupBy, - selectedPaneKey, - showChildAgents = false, - badgeOnly = false - } = args - const agentsVisibleHostIds = useAppStore((s) => s.agentsVisibleHostIds) - const agentsFilterRepoIds = useAppStore((s) => s.agentsFilterRepoIds) - const hideWorkspacesFromOtherDevices = useAppStore((s) => s.agentsHideWorkspacesFromOtherDevices) - const hideAutomationGeneratedWorkspaces = useAppStore( - (s) => s.agentsHideAutomationGeneratedWorkspaces - ) - const hideCliCreatedWorkspaces = useAppStore((s) => s.agentsHideCliCreatedWorkspaces) - // Why gated selectors: runtime status churns, and only the other-device filter reads it. - const runtimeEnvironments = useAppStore((s) => - s.agentsHideWorkspacesFromOtherDevices ? s.runtimeEnvironments : null - ) - const runtimeStatusByEnvironmentId = useAppStore((s) => - s.agentsHideWorkspacesFromOtherDevices ? s.runtimeStatusByEnvironmentId : null - ) - const pairedDeviceIdsByEnvironment = useMemo( - () => - runtimeEnvironments && runtimeStatusByEnvironmentId - ? getPairedDeviceIdsByEnvironment(runtimeEnvironments, runtimeStatusByEnvironmentId) - : EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, - [runtimeEnvironments, runtimeStatusByEnvironmentId] - ) - const storeData = useAgentPaneThreadStoreData() + const storeData = useAllAgentPaneThreadStoreData() // Why: agentStatusEpoch is a dep (not used in the body) so the memo recomputes when freshness boundaries expire even without new PTY data. const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) const chatNames = useStructuredChatTabNames() @@ -153,6 +111,65 @@ export function useAgentPaneThreads(args: { [allEvents, liveAgentByPaneKey, paneEntryByPaneKey, storeData.generatedTitlesEnabled, badgeOnly] ) + return { storeData, allThreads } +} + +/** Shared Activity/sidebar pipeline: store data to events, threads, filters and groups. */ +export function useAgentPaneThreads(args: { + query: string + readFilter: ThreadReadFilter + groupBy: ActivityGroupBy + selectedPaneKey: string | null + showChildAgents?: boolean + /** Prepare only live badge rows, omitting list groups and bulk-action sets. */ + badgeOnly?: boolean +}): { + storeData: AgentPaneThreadsStoreData + allThreads: AgentPaneThread[] + selectedPaneKeyIsLive: boolean + effectiveSelectedPaneKey: string | null + /** Every active view filter applies here; destructive Clear completed must not touch hidden rows. */ + visibleThreads: AgentPaneThread[] + /** Badge-coherent threads after child classification; ignore transient search/scope/read filters so Mark all read can clear the badge. */ + markAllReadThreads: AgentPaneThread[] + visibleThreadGroups: ActivityThreadGroup[] +} { + const { + query, + readFilter, + groupBy, + selectedPaneKey, + showChildAgents = false, + badgeOnly = false + } = args + const agentsVisibleHostIds = useAppStore((s) => s.agentsVisibleHostIds) + const agentsFilterRepoIds = useAppStore((s) => s.agentsFilterRepoIds) + const hideWorkspacesFromOtherDevices = useAppStore((s) => s.agentsHideWorkspacesFromOtherDevices) + const hideAutomationGeneratedWorkspaces = useAppStore( + (s) => s.agentsHideAutomationGeneratedWorkspaces + ) + const hideCliCreatedWorkspaces = useAppStore((s) => s.agentsHideCliCreatedWorkspaces) + // Why gated selectors: runtime status churns, and only the other-device filter reads it. + const runtimeEnvironments = useAppStore((s) => + s.agentsHideWorkspacesFromOtherDevices ? s.runtimeEnvironments : null + ) + const runtimeStatusByEnvironmentId = useAppStore((s) => + s.agentsHideWorkspacesFromOtherDevices ? s.runtimeStatusByEnvironmentId : null + ) + const pairedDeviceIdsByEnvironment = useMemo( + () => + runtimeEnvironments && runtimeStatusByEnvironmentId + ? getPairedDeviceIdsByEnvironment(runtimeEnvironments, runtimeStatusByEnvironmentId) + : EMPTY_PAIRED_DEVICE_IDS_BY_ENVIRONMENT, + [runtimeEnvironments, runtimeStatusByEnvironmentId] + ) + const { storeData: unscopedStoreData, allThreads } = useAllAgentPaneThreads({ badgeOnly }) + const defaultHostId = useAgentPaneThreadsDefaultHostId() + const storeData = useMemo( + () => ({ ...unscopedStoreData, defaultHostId }), + [unscopedStoreData, defaultHostId] + ) + const selectedPaneKeyIsLive = selectedPaneKey === null || allThreads.some((thread) => thread.paneKey === selectedPaneKey) const effectiveSelectedPaneKey = selectedPaneKeyIsLive ? selectedPaneKey : null @@ -201,7 +218,8 @@ export function useAgentPaneThreads(args: { const normalizedQuery = isActivitySearchQueryTooLarge(deferredQuery) ? null : deferredQuery.trim().toLowerCase() - let matchesSearchQuery: ReturnType | undefined + const matchesSearchQuery = + normalizedQuery === null ? null : createActivityThreadSearchMatcher(normalizedQuery) return scopeVisibleThreads.filter((thread) => { // Why: keep the just-selected thread visible after auto-mark-read flips it to read, else unread-only mode makes the clicked row vanish from the list. if ( @@ -219,11 +237,7 @@ export function useAgentPaneThreads(args: { ) { return false } - if (normalizedQuery === null) { - return false - } - matchesSearchQuery ??= createActivityThreadSearchMatcher(normalizedQuery) - return matchesSearchQuery(thread) + return matchesSearchQuery !== null && matchesSearchQuery(thread) }) }, [ scopeVisibleThreads, diff --git a/src/renderer/src/components/automations/automation-host-catalog-source.ts b/src/renderer/src/components/automations/automation-host-catalog-source.ts index 9d567599c43..8f551e83044 100644 --- a/src/renderer/src/components/automations/automation-host-catalog-source.ts +++ b/src/renderer/src/components/automations/automation-host-catalog-source.ts @@ -2,7 +2,7 @@ import { getLocalExecutionHostLabel } from '../../../../shared/execution-host' import { AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY } from '../../../../shared/automations/automation-runtime-capabilities' -import type { RuntimeStatus } from '../../../../shared/runtime-types' +import type { RuntimeStatus } from '../../../../shared/runtime-session-contracts' import type { SshConnectionStatus } from '../../../../shared/ssh-types' import type { StableAutomationAuthorityRef } from '../../../../shared/automations/ownership/automation-owner-ref' import type { diff --git a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx b/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx index f7afff82f5b..eedfbceef48 100644 --- a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx +++ b/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-comment-card.tsx @@ -148,6 +148,7 @@ export function renderCommentCard( /> resolvedBodyDraft: string markdownGitHubRepo: GitHubOwnerRepo | null setBodyDraft: (value: string) => void @@ -136,6 +138,7 @@ export function ConversationTabDescription({ ) : body.trim() ? ( ({ update: vi.fn().mockResolvedValue(undefined) })) +vi.mock('@/components/github/github-work-item-edit-mutations', () => ({ + runWorkItemBodyUpdate: mocks.update +})) +vi.mock('@/store', () => ({ + useAppStore: { getState: () => ({ recordFeatureInteraction: () => {} }) } +})) +vi.mock('@/lib/pr-bot-author-overrides', () => ({ usePRBotAuthorOverrides: () => ({}) })) +vi.mock('./conversation-tab-activity', () => ({ ConversationTabActivity: () => null })) +vi.mock('./conversation-tab-pr-sidebar', () => ({ ConversationTabPRSidebar: () => null })) +vi.mock('./gh-comment-composer', () => ({ GHCommentComposer: () => null })) +vi.mock('@/components/github/GitHubMarkdownComposer', () => ({ + GitHubMarkdownComposer: ({ + value, + onChange + }: { + value: string + onChange: (value: string) => void + }) => ( +