From c18bf6529bbdcf0b912cacbae04f56b2ee954659 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 30 Oct 2026 10:03:37 -0700 Subject: [PATCH] test: remove 46 low-value test suites (#36403) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/scripts/ci-shard-timings.json | 39 ---------- .../claude/claude-cli-flag-prewarm.test.ts | 74 ------------------ .../codex-config-mirror-wsl-stopped.test.ts | 72 ------------------ .../codex-structured-owner-identity.test.ts | 71 ----------------- src/main/codex/codex-trust-grant-host.test.ts | 72 ------------------ .../daemon/daemon-endpoint-windows.test.ts | 70 ----------------- .../daemon/daemon-lifecycle-event.test.ts | 73 ------------------ .../spawn-preflight-health-probe.test.ts | 72 ------------------ .../github/pr-start-point-wsl-gate.test.ts | 75 ------------------ .../issue-command-wsl-running-signal.test.ts | 70 ----------------- ...orktree-hook-check-background-gate.test.ts | 76 ------------------- .../codex-hook-reconcile-spawn.test.ts | 73 ------------------ ...restored-appimage-cli-shim-refresh.test.ts | 76 ------------------- .../pty/runtime/spawn-commit-response.test.ts | 74 ------------------ ...tected-provider-listing-meta-index.test.ts | 70 ----------------- ...ed-agent-session-restart-reconcile.test.ts | 75 ------------------ .../orcad-wsl-host-login-environment.test.ts | 74 ------------------ .../runtime/rpc/methods/client-events.test.ts | 71 ----------------- .../files-write-disk-precondition.test.ts | 71 ----------------- .../rpc/methods/terminal-navigation.test.ts | 72 ------------------ src/main/runtime/rpc/methods/updater.test.ts | 73 ------------------ .../rpc/terminal-subscribe-lease-only.test.ts | 72 ------------------ ...ntime-git-branch-compare-admission.test.ts | 76 ------------------- ...ect-group-controller-folder-delete.test.ts | 75 ------------------ .../runtime-session-search-settings.test.ts | 73 ------------------ ...ntime-workspace-view-change-events.test.ts | 70 ----------------- ...rve-update-handoff.app-environment.test.ts | 75 ------------------ .../ssh/config/ssh-config-resolver.test.ts | 75 ------------------ .../clipboard-text-write-verify.test.ts | 76 ------------------- ...main-window-updater-headless-serve.test.ts | 71 ----------------- ...avigate-browser-page-notebook-link.test.ts | 74 ------------------ .../DashboardPopoutRoot.test.tsx | 71 ----------------- ...or-dropped-file-open.escaping-link.test.ts | 76 ------------------- .../editor/editor-save-grant.test.ts | 71 ----------------- .../editor/pdf-document-loader.test.ts | 73 ------------------ ...itor-decorations.doc-link-refresh.test.tsx | 70 ----------------- ...tructured-session-takeover-report.test.tsx | 76 ------------------- .../PluginContributionActionLanguage.test.tsx | 73 ------------------ .../AgentDashboardSidebarHost.test.tsx | 75 ------------------ .../worktree-attachment-editing.test.ts | 72 ------------------ .../terminal-link-escaping-file-open.test.ts | 75 ------------------ .../terminal-pane-paste-execution.test.ts | 73 ------------------ ...IpcEvents-agent-dashboard-shortcut.test.ts | 75 ------------------ .../src/lib/ai-vault-resume-shell.test.ts | 71 ----------------- .../src/lib/cmd-j-github-url-lookup.test.ts | 73 ------------------ ...gent-status-live-freshness-request.test.ts | 70 ----------------- .../terminal-tab-close-providers.test.ts | 71 ----------------- 47 files changed, 3395 deletions(-) delete mode 100644 src/main/claude/claude-cli-flag-prewarm.test.ts delete mode 100644 src/main/codex-accounts/codex-config-mirror-wsl-stopped.test.ts delete mode 100644 src/main/codex/codex-structured-owner-identity.test.ts delete mode 100644 src/main/codex/codex-trust-grant-host.test.ts delete mode 100644 src/main/daemon/daemon-endpoint-windows.test.ts delete mode 100644 src/main/daemon/daemon-lifecycle-event.test.ts delete mode 100644 src/main/daemon/pty-subprocess/spawn-preflight-health-probe.test.ts delete mode 100644 src/main/github/pr-start-point-wsl-gate.test.ts delete mode 100644 src/main/ipc/hooks/issue-command-wsl-running-signal.test.ts delete mode 100644 src/main/ipc/hooks/worktree-hook-check-background-gate.test.ts delete mode 100644 src/main/ipc/pty/host-env/codex-hook-reconcile-spawn.test.ts delete mode 100644 src/main/ipc/pty/pty-restored-appimage-cli-shim-refresh.test.ts delete mode 100644 src/main/ipc/pty/runtime/spawn-commit-response.test.ts delete mode 100644 src/main/ipc/worktrees/listing/detected-provider-listing-meta-index.test.ts delete mode 100644 src/main/native-chat/agent-session-wire/structured-agent-session-restart-reconcile.test.ts delete mode 100644 src/main/orcad/orcad-wsl-host-login-environment.test.ts delete mode 100644 src/main/runtime/rpc/methods/client-events.test.ts delete mode 100644 src/main/runtime/rpc/methods/files-write-disk-precondition.test.ts delete mode 100644 src/main/runtime/rpc/methods/terminal-navigation.test.ts delete mode 100644 src/main/runtime/rpc/methods/updater.test.ts delete mode 100644 src/main/runtime/rpc/terminal-subscribe-lease-only.test.ts delete mode 100644 src/main/runtime/runtime-git-branch-compare-admission.test.ts delete mode 100644 src/main/runtime/runtime-project-group-controller-folder-delete.test.ts delete mode 100644 src/main/runtime/runtime-session-search-settings.test.ts delete mode 100644 src/main/runtime/runtime-workspace-view-change-events.test.ts delete mode 100644 src/main/serve-update-handoff.app-environment.test.ts delete mode 100644 src/main/ssh/config/ssh-config-resolver.test.ts delete mode 100644 src/main/window/clipboard-text-write-verify.test.ts delete mode 100644 src/main/window/main-window-updater-headless-serve.test.ts delete mode 100644 src/renderer/src/components/browser-pane/navigate/navigate-browser-page-notebook-link.test.ts delete mode 100644 src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.test.tsx delete mode 100644 src/renderer/src/components/editor/editor-dropped-file-open.escaping-link.test.ts delete mode 100644 src/renderer/src/components/editor/editor-save-grant.test.ts delete mode 100644 src/renderer/src/components/editor/pdf-document-loader.test.ts delete mode 100644 src/renderer/src/components/editor/use-monaco-editor-decorations.doc-link-refresh.test.tsx delete mode 100644 src/renderer/src/components/native-chat/structured-session-takeover-report.test.tsx delete mode 100644 src/renderer/src/components/plugins/page/PluginContributionActionLanguage.test.tsx delete mode 100644 src/renderer/src/components/sidebar/AgentDashboardSidebarHost.test.tsx delete mode 100644 src/renderer/src/components/sidebar/worktree-attachment-editing.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-link-escaping-file-open.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-pane-paste-execution.test.ts delete mode 100644 src/renderer/src/hooks/useIpcEvents-agent-dashboard-shortcut.test.ts delete mode 100644 src/renderer/src/lib/ai-vault-resume-shell.test.ts delete mode 100644 src/renderer/src/lib/cmd-j-github-url-lookup.test.ts delete mode 100644 src/renderer/src/store/slices/agent-status/agent-status-live-freshness-request.test.ts delete mode 100644 src/renderer/src/store/terminals/terminal-tab-close-providers.test.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 63a9307cce6..a2ac47efdb5 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1494,7 +1494,6 @@ "src/main/claude/claude-child-process-environment.test.ts": 47, "src/main/claude/claude-child-work-decoder.test.ts": 42, "src/main/claude/claude-child-work-evidence-retention.test.ts": 453, - "src/main/claude/claude-cli-flag-prewarm.test.ts": 190, "src/main/claude/claude-cli-flag-support.test.ts": 452, "src/main/claude/claude-close-turn-end.test.ts": 607, "src/main/claude/claude-command-lifecycle-frames.test.ts": 307, @@ -1864,7 +1863,6 @@ "src/main/codex/codex-structured-launch-resolution.test.ts": 392, "src/main/codex/codex-structured-live-provider-process.test.ts": 317, "src/main/codex/codex-structured-message-options.test.ts": 587, - "src/main/codex/codex-structured-owner-identity.test.ts": 77, "src/main/codex/codex-structured-permission-policy.test.ts": 43, "src/main/codex/codex-structured-prompt-items.test.ts": 152, "src/main/codex/codex-structured-prompt-ownership.test.ts": 400, @@ -1901,7 +1899,6 @@ "src/main/codex/codex-tool-identity-translation.test.ts": 82, "src/main/codex/codex-trust-config-concurrent-launch.test.ts": 181, "src/main/codex/codex-trust-config-mutation-queue.test.ts": 52, - "src/main/codex/codex-trust-grant-host.test.ts": 99, "src/main/codex/codex-trust-grant-ledger.test.ts": 70, "src/main/codex/codex-turn-ordinals.test.ts": 74, "src/main/codex/codex-usage-limits.test.ts": 238, @@ -2046,7 +2043,6 @@ "src/main/daemon/daemon-electron-to-node-adoption.electron.test.ts": 2527, "src/main/daemon/daemon-endpoint-ownership.test.ts": 505, "src/main/daemon/daemon-endpoint-publish.test.ts": 164, - "src/main/daemon/daemon-endpoint-windows.test.ts": 51, "src/main/daemon/daemon-entry-path-layouts.test.ts": 659, "src/main/daemon/daemon-entry.test.ts": 551, "src/main/daemon/daemon-errors.test.ts": 250, @@ -2088,7 +2084,6 @@ "src/main/daemon/daemon-inventory-routing-authority.test.ts": 241, "src/main/daemon/daemon-launched-child-identity.test.ts": 62, "src/main/daemon/daemon-launched-child-spawn.test.ts": 120, - "src/main/daemon/daemon-lifecycle-event.test.ts": 130, "src/main/daemon/daemon-liveness-report.test.ts": 524, "src/main/daemon/daemon-mac-code-identity.test.ts": 51, "src/main/daemon/daemon-main.test.ts": 595, @@ -2235,7 +2230,6 @@ "src/main/daemon/pty-subprocess/foreground-fallback-process.test.ts": 54, "src/main/daemon/pty-subprocess/native-pty-spawn-windows.test.ts": 98, "src/main/daemon/pty-subprocess/spawn-file-foreground-rejected-agents.test.ts": 91, - "src/main/daemon/pty-subprocess/spawn-preflight-health-probe.test.ts": 103, "src/main/daemon/reattach-snapshot.test.ts": 908, "src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts": 580, "src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts": 138, @@ -2982,7 +2976,6 @@ "src/main/ipc/pty/delivery/pty-renderer-lifecycle-delivery-reset.test.ts": 2922, "src/main/ipc/pty/delivery/pty-reset-input-modes.test.ts": 3403, "src/main/ipc/pty/host-env/claude-agent-view.test.ts": 74, - "src/main/ipc/pty/host-env/codex-hook-reconcile-spawn.test.ts": 441, "src/main/ipc/pty/host-env/codex-terminal-clipboard.test.ts": 38, "src/main/ipc/pty/host-env/omp-launch-environment.test.ts": 81, "src/main/ipc/pty/host-env/opencode-hook-installation.test.ts": 558, @@ -3050,7 +3043,6 @@ "src/main/ipc/pty/pty-persisted-incarnation-repair.test.ts": 3684, "src/main/ipc/pty/pty-renderer-liveness-guard.test.ts": 3983, "src/main/ipc/pty/pty-restore-record-seeding.test.ts": 4277, - "src/main/ipc/pty/pty-restored-appimage-cli-shim-refresh.test.ts": 2955, "src/main/ipc/pty/pty-runtime-hidden-at-spawn-mark.test.ts": 3336, "src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts": 3265, "src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts": 3975, @@ -3080,7 +3072,6 @@ "src/main/ipc/pty/runtime/kill-same-id-respawn.test.ts": 3462, "src/main/ipc/pty/runtime/queried-host-kinds.test.ts": 484, "src/main/ipc/pty/runtime/spawn-commit-pty-size.test.ts": 758, - "src/main/ipc/pty/runtime/spawn-commit-response.test.ts": 357, "src/main/ipc/pty/runtime/spawn-commit-run-facts.test.ts": 909, "src/main/ipc/pty/runtime/spawn-preflight-requested-shell.test.ts": 1391, "src/main/ipc/pty/runtime/spawn-preflight-saved-resume.test.ts": 1081, @@ -3297,7 +3288,6 @@ "src/main/ipc/worktrees-wsl-move-fence.test.ts": 1654, "src/main/ipc/worktrees-wsl-runtime-routing.test.ts": 1425, "src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts": 684, - "src/main/ipc/worktrees/listing/detected-provider-listing-meta-index.test.ts": 741, "src/main/ipc/worktrees/listing/detected-provider-listing-overtaken-scan.test.ts": 793, "src/main/ipc/worktrees/listing/detected-scan-failure-authority.test.ts": 934, "src/main/ipc/worktrees/listing/detected-worktree-classification.test.ts": 324, @@ -3717,7 +3707,6 @@ "src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-withdrawal.test.ts": 2367, "src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts": 2267, "src/main/native-chat/agent-session-wire/structured-agent-session-restart-provider-output.test.ts": 1978, - "src/main/native-chat/agent-session-wire/structured-agent-session-restart-reconcile.test.ts": 131, "src/main/native-chat/agent-session-wire/structured-agent-session-restart-recovery-output.test.ts": 1568, "src/main/native-chat/agent-session-wire/structured-agent-session-restart-restore-gate.test.ts": 44, "src/main/native-chat/agent-session-wire/structured-agent-session-restart-restore.test.ts": 457, @@ -4084,7 +4073,6 @@ "src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts": 64, "src/main/orcad/orcad-ws-port-policy.test.ts": 46, "src/main/orcad/orcad-wsl-guest-shell-path.test.ts": 178, - "src/main/orcad/orcad-wsl-host-login-environment.test.ts": 53, "src/main/orcad/serve-profile-ssh-targets.test.ts": 290, "src/main/own-chromium-tree-kill-guard.test.ts": 116, "src/main/persistence-local-only-worktree-meta.test.ts": 1152, @@ -5283,7 +5271,6 @@ "src/main/runtime/rpc/methods/browser-network-tunnel.test.ts": 858, "src/main/runtime/rpc/methods/browser-tab-create-schema.test.ts": 82, "src/main/runtime/rpc/methods/browser.test.ts": 767, - "src/main/runtime/rpc/methods/client-events.test.ts": 2457, "src/main/runtime/rpc/methods/client-native-chat-settings.test.ts": 631, "src/main/runtime/rpc/methods/client-ui-pairing-local-fields.test.ts": 757, "src/main/runtime/rpc/methods/client-ui-set-collapsed.test.ts": 625, @@ -5300,7 +5287,6 @@ "src/main/runtime/rpc/methods/files-watch-batch-cadence.test.ts": 527, "src/main/runtime/rpc/methods/files-watch-cancellation.test.ts": 801, "src/main/runtime/rpc/methods/files-watch-cleanup.test.ts": 555, - "src/main/runtime/rpc/methods/files-write-disk-precondition.test.ts": 409, "src/main/runtime/rpc/methods/files.test.ts": 707, "src/main/runtime/rpc/methods/git-diff-transport-budget.test.ts": 473, "src/main/runtime/rpc/methods/git.test.ts": 658, @@ -5487,7 +5473,6 @@ "src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts": 1065, "src/main/runtime/rpc/methods/terminal-legacy-stream-id-characterization.test.ts": 1515, "src/main/runtime/rpc/methods/terminal-manifest-characterization.test.ts": 999, - "src/main/runtime/rpc/methods/terminal-navigation.test.ts": 1154, "src/main/runtime/rpc/methods/terminal-quick-command-client-capabilities.test.ts": 2031, "src/main/runtime/rpc/methods/terminal-read-screen-cursor.test.ts": 1054, "src/main/runtime/rpc/methods/terminal-reveal.test.ts": 1159, @@ -5498,7 +5483,6 @@ "src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts": 47, "src/main/runtime/rpc/methods/terminal/terminal-subscription-registration.test.ts": 86, "src/main/runtime/rpc/methods/terminal/terminal-viewer-colors-method.test.ts": 1068, - "src/main/runtime/rpc/methods/updater.test.ts": 138, "src/main/runtime/rpc/methods/usage-credentials.test.ts": 601, "src/main/runtime/rpc/methods/workspace-cleanup-ui-schema.test.ts": 185, "src/main/runtime/rpc/methods/workspace-layout-apply.test.ts": 5567, @@ -5596,7 +5580,6 @@ "src/main/runtime/rpc/terminal-subscribe-blank-mount.test.ts": 1615, "src/main/runtime/rpc/terminal-subscribe-buffer.test.ts": 1716, "src/main/runtime/rpc/terminal-subscribe-late-renderer-desktop-depth.test.ts": 926, - "src/main/runtime/rpc/terminal-subscribe-lease-only.test.ts": 1253, "src/main/runtime/rpc/terminal-subscribe-mount-replay.test.ts": 1245, "src/main/runtime/rpc/terminal-subscribe-mounted-pane.test.ts": 1486, "src/main/runtime/rpc/terminal-subscribe-ownership.test.ts": 1703, @@ -5640,7 +5623,6 @@ "src/main/runtime/runtime-folder-workspace-delete-lifecycle.test.ts": 3681, "src/main/runtime/runtime-folder-workspace.test.ts": 71, "src/main/runtime/runtime-folder-worktree-create.test.ts": 107, - "src/main/runtime/runtime-git-branch-compare-admission.test.ts": 339, "src/main/runtime/runtime-git-command-target.test.ts": 476, "src/main/runtime/runtime-git-conflict-operation-routing.test.ts": 507, "src/main/runtime/runtime-git-execution-host-ownership.test.ts": 702, @@ -5687,7 +5669,6 @@ "src/main/runtime/runtime-pairing-desktop-control-grant.test.ts": 3176, "src/main/runtime/runtime-pane-admission.test.ts": 92, "src/main/runtime/runtime-project-group-controller-folder-create.test.ts": 258, - "src/main/runtime/runtime-project-group-controller-folder-delete.test.ts": 285, "src/main/runtime/runtime-project-host-setup-controller.test.ts": 839, "src/main/runtime/runtime-project-host-setup-git-remote-link.test.ts": 595, "src/main/runtime/runtime-project-host-setup-publication.test.ts": 635, @@ -5737,7 +5718,6 @@ "src/main/runtime/runtime-search-line-fragments.test.ts": 646, "src/main/runtime/runtime-server-environment-commands.test.ts": 136, "src/main/runtime/runtime-server-git-availability.test.ts": 27, - "src/main/runtime/runtime-session-search-settings.test.ts": 106, "src/main/runtime/runtime-skill-install-authority.test.ts": 68, "src/main/runtime/runtime-skill-install-commands.test.ts": 542, "src/main/runtime/runtime-skill-install-queries.test.ts": 374, @@ -5759,7 +5739,6 @@ "src/main/runtime/runtime-visible-catalog.test.ts": 54, "src/main/runtime/runtime-workspace-launch-contracts.test.ts": 3887, "src/main/runtime/runtime-workspace-session-controller-twin-repo.test.ts": 148, - "src/main/runtime/runtime-workspace-view-change-events.test.ts": 122, "src/main/runtime/runtime-worktree-agent-rows-structured.test.ts": 623, "src/main/runtime/runtime-worktree-agent-rows-verdict.test.ts": 1106, "src/main/runtime/runtime-worktree-agent-sources.test.ts": 146, @@ -6057,7 +6036,6 @@ "src/main/runtime/worktree-teardown.test.ts": 689, "src/main/runtime/worktree-terminal-mutation-lock.test.ts": 48, "src/main/runtime/worktree-terminal-sleep-host-twin.test.ts": 4038, - "src/main/serve-update-handoff.app-environment.test.ts": 1228, "src/main/serve-update-handoff.test.ts": 58, "src/main/server/serve-readiness.test.ts": 40, "src/main/server/serve-stdout-boundary.test.ts": 56, @@ -6204,7 +6182,6 @@ "src/main/ssh/config/ssh-config-loader.test.ts": 83, "src/main/ssh/config/ssh-config-parser-host-patterns.test.ts": 30, "src/main/ssh/config/ssh-config-parser.test.ts": 431, - "src/main/ssh/config/ssh-config-resolver.test.ts": 38, "src/main/ssh/config/ssh-g-config-resolution.test.ts": 81, "src/main/ssh/config/ssh-known-hosts-source.test.ts": 89, "src/main/ssh/config/ssh-known-hosts.test.ts": 74, @@ -6617,7 +6594,6 @@ "src/main/window/clipboard-remote-file-staging.test.ts": 57, "src/main/window/clipboard-runtime-owned-ssh-paste.test.ts": 356, "src/main/window/clipboard-text-publisher.test.ts": 312, - "src/main/window/clipboard-text-write-verify.test.ts": 54, "src/main/window/clipboard-windows-image-file.test.ts": 50, "src/main/window/createMainWindow-close-confirmation.test.ts": 2158, "src/main/window/createMainWindow-low-commit-oom-recovery.test.ts": 2188, @@ -6648,7 +6624,6 @@ "src/main/window/macos-tahoe-release.test.ts": 54, "src/main/window/main-window-state-lifecycle.test.ts": 49, "src/main/window/main-window-updater-deferred-setup.test.ts": 128, - "src/main/window/main-window-updater-headless-serve.test.ts": 99, "src/main/window/main-window-visibility.test.ts": 36, "src/main/window/main-window-webview-security.test.ts": 145, "src/main/window/native-chat-paste-files.test.ts": 591, @@ -7156,7 +7131,6 @@ "src/renderer/src/components/browser-pane/navigate/browser-webview-load-failure.test.ts": 105, "src/renderer/src/components/browser-pane/navigate/chromium-error-page-poll-visibility.test.ts": 2172, "src/renderer/src/components/browser-pane/navigate/chromium-error-page-polling.test.ts": 25, - "src/renderer/src/components/browser-pane/navigate/navigate-browser-page-notebook-link.test.ts": 494, "src/renderer/src/components/browser-pane/navigate/use-browser-page-navigation-downloads.file-drop.test.tsx": 1587, "src/renderer/src/components/browser-pane/navigate/use-browser-page-reload-actions.test.tsx": 1454, "src/renderer/src/components/browser-pane/restored-client-hosted-recovery-window.test.tsx": 2512, @@ -7229,7 +7203,6 @@ "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.settings-geometry.test.tsx": 1712, "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.settings-lifetime.test.tsx": 1564, "src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx": 2249, - "src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.test.tsx": 271, "src/renderer/src/components/dashboard-popout/agent-board-filtering.test.ts": 50, "src/renderer/src/components/dashboard-popout/dashboard-agent-status-patch.test.ts": 59, "src/renderer/src/components/dashboard-popout/preview-grid-claim.test.ts": 322, @@ -7411,7 +7384,6 @@ "src/renderer/src/components/editor/editor-cmd-save-target.test.ts": 127, "src/renderer/src/components/editor/editor-content-dirty-state.test.ts": 54, "src/renderer/src/components/editor/editor-deleted-file-reload.test.ts": 60, - "src/renderer/src/components/editor/editor-dropped-file-open.escaping-link.test.ts": 440, "src/renderer/src/components/editor/editor-dropped-file-open.test.ts": 380, "src/renderer/src/components/editor/editor-external-watch-path-index.test.ts": 1341, "src/renderer/src/components/editor/editor-file-save-attempt.test.ts": 430, @@ -7619,7 +7591,6 @@ "src/renderer/src/components/editor/use-markdown-preview-document.test.tsx": 278, "src/renderer/src/components/editor/use-markdown-preview-navigation.test.tsx": 504, "src/renderer/src/components/editor/use-markdown-preview-search-reveal.test.tsx": 243, - "src/renderer/src/components/editor/use-monaco-editor-decorations.doc-link-refresh.test.tsx": 183, "src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx": 755, "src/renderer/src/components/editor/use-monaco-editor-mount.stale-cache.test.tsx": 473, "src/renderer/src/components/editor/use-monaco-reveal-scheduler.test.tsx": 180, @@ -8043,7 +8014,6 @@ "src/renderer/src/components/native-chat/structured-chat-sleep-startup.test.tsx": 1342, "src/renderer/src/components/native-chat/structured-child-records-switch.test.tsx": 2162, "src/renderer/src/components/native-chat/structured-conversation-command-send.test.ts": 454, - "src/renderer/src/components/native-chat/structured-session-takeover-report.test.tsx": 901, "src/renderer/src/components/native-chat/use-host-model-catalog-upgrade.test.tsx": 1675, "src/renderer/src/components/native-chat/use-host-model-catalog-upgrade.unavailable.test.tsx": 1567, "src/renderer/src/components/native-chat/use-native-chat-appearance-style.test.tsx": 315, @@ -8730,7 +8700,6 @@ "src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx": 681, "src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts": 170, "src/renderer/src/components/sidebar/AddWslHostFormPanel.test.tsx": 220, - "src/renderer/src/components/sidebar/AgentDashboardSidebarHost.test.tsx": 1548, "src/renderer/src/components/sidebar/AutoRenameFailedDialog.test.tsx": 1246, "src/renderer/src/components/sidebar/CommentMarkdown.code-block-renderer.test.tsx": 2013, "src/renderer/src/components/sidebar/CommentMarkdown.file-link-cases.test.tsx": 1688, @@ -8979,7 +8948,6 @@ "src/renderer/src/components/sidebar/worktree-agent-remote-attribution.test.ts": 885, "src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts": 43, "src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx": 1878, - "src/renderer/src/components/sidebar/worktree-attachment-editing.test.ts": 60, "src/renderer/src/components/sidebar/worktree-card-agent-ack-inputs.test.tsx": 145, "src/renderer/src/components/sidebar/worktree-card-agent-summary.test.ts": 2036, "src/renderer/src/components/sidebar/worktree-card-compact-agent-row-program-status.test.ts": 1088, @@ -9769,7 +9737,6 @@ "src/renderer/src/components/terminal-pane/terminal-link-click-behavior.test.ts": 41, "src/renderer/src/components/terminal-pane/terminal-link-click-fallback.test.ts": 958, "src/renderer/src/components/terminal-pane/terminal-link-client-local-file.test.ts": 797, - "src/renderer/src/components/terminal-pane/terminal-link-escaping-file-open.test.ts": 789, "src/renderer/src/components/terminal-pane/terminal-link-file-open-routing.test.ts": 787, "src/renderer/src/components/terminal-pane/terminal-link-host-granted-file-link.test.ts": 655, "src/renderer/src/components/terminal-pane/terminal-link-host-workspace-file.test.ts": 817, @@ -9814,7 +9781,6 @@ "src/renderer/src/components/terminal-pane/terminal-pane-local-windows-conpty.test.ts": 1431, "src/renderer/src/components/terminal-pane/terminal-pane-mount-bootstrap.test.ts": 1256, "src/renderer/src/components/terminal-pane/terminal-pane-mount-events-layout-owner.test.ts": 743, - "src/renderer/src/components/terminal-pane/terminal-pane-paste-execution.test.ts": 1123, "src/renderer/src/components/terminal-pane/terminal-pane-recovery-host-rebind-cap.test.ts": 521, "src/renderer/src/components/terminal-pane/terminal-pane-recovery-unsettled-fallback.test.ts": 764, "src/renderer/src/components/terminal-pane/terminal-pane-recovery.test.ts": 676, @@ -10172,7 +10138,6 @@ "src/renderer/src/hooks/useGitHubSlugMetadata.test.tsx": 169, "src/renderer/src/hooks/useInstalledAgentSkills.react.test.tsx": 1532, "src/renderer/src/hooks/useInstalledAgentSkills.test.ts": 1193, - "src/renderer/src/hooks/useIpcEvents-agent-dashboard-shortcut.test.ts": 28, "src/renderer/src/hooks/useIpcEvents-agent-launch-closed-tab.test.ts": 1512, "src/renderer/src/hooks/useIpcEvents-agent-status-batch-projection.test.ts": 1717, "src/renderer/src/hooks/useIpcEvents-agent-status-connection-attribution.test.ts": 2611, @@ -10318,7 +10283,6 @@ "src/renderer/src/lib/ai-vault-omp-cold-resume.test.ts": 1621, "src/renderer/src/lib/ai-vault-resume-command.drop-repin.test.ts": 463, "src/renderer/src/lib/ai-vault-resume-command.test.ts": 350, - "src/renderer/src/lib/ai-vault-resume-shell.test.ts": 487, "src/renderer/src/lib/ai-vault-resume-target.test.ts": 199, "src/renderer/src/lib/ai-vault-session-drag.test.ts": 45, "src/renderer/src/lib/ai-vault-session-resume-preparation.test.ts": 135, @@ -10353,7 +10317,6 @@ "src/renderer/src/lib/claude-session-account-move.test.ts": 1543, "src/renderer/src/lib/client-creation-action-policy.test.ts": 1332, "src/renderer/src/lib/clipboard-image-copy.test.ts": 324, - "src/renderer/src/lib/cmd-j-github-url-lookup.test.ts": 56, "src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts": 344, "src/renderer/src/lib/cmd-j-linear-issue-intent.test.ts": 37, "src/renderer/src/lib/codex-account-display-label.test.ts": 44, @@ -11306,7 +11269,6 @@ "src/renderer/src/store/slices/agent-status/agent-status-drop-ipc.test.ts": 1430, "src/renderer/src/store/slices/agent-status/agent-status-freshness-cache.test.ts": 63, "src/renderer/src/store/slices/agent-status/agent-status-freshness-scheduler.test.ts": 76, - "src/renderer/src/store/slices/agent-status/agent-status-live-freshness-request.test.ts": 241, "src/renderer/src/store/slices/agent-status/agent-status-live-map-leak.test.ts": 2528, "src/renderer/src/store/slices/agent-status/agent-status-main-agent-fact.test.ts": 1265, "src/renderer/src/store/slices/agent-status/agent-status-manual-sleep-capture.test.ts": 1345, @@ -11732,7 +11694,6 @@ "src/renderer/src/store/terminals/terminal-sleep-layout-owner.test.ts": 66, "src/renderer/src/store/terminals/terminal-startup-queue-restart.test.ts": 1414, "src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts": 1201, - "src/renderer/src/store/terminals/terminal-tab-close-providers.test.ts": 1408, "src/renderer/src/store/terminals/terminal-tab-create-through-layout-owner.test.ts": 1364, "src/renderer/src/store/terminals/terminal-workspace-routing.scale.test.ts": 211, "src/renderer/src/store/terminals/workspace-terminal-placeholders.test.ts": 139, diff --git a/src/main/claude/claude-cli-flag-prewarm.test.ts b/src/main/claude/claude-cli-flag-prewarm.test.ts deleted file mode 100644 index f07622c5148..00000000000 --- a/src/main/claude/claude-cli-flag-prewarm.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { homedir } from 'node:os' -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionRecord } from '../../shared/agent-session-record' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host' -import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' -import { prewarmClaudeCliFlags } from './claude-cli-flag-prewarm' - -const record = ( - sessionId: string, - overrides: { - provider?: string - host?: ExecutionHostId - wslDistro?: string | null - dir?: string - } = {} -): AgentSessionRecord => - agentSessionRecordFixture({ - sessionId, - provider: overrides.provider ?? 'claude', - location: { - executionHostId: overrides.host ?? LOCAL_EXECUTION_HOST_ID, - wslDistro: overrides.wslDistro ?? null - }, - ...(overrides.dir ? { launchDirectory: overrides.dir } : {}) - }) - -function prewarmWith( - records: AgentSessionRecord[], - resolveCommand = () => ({ command: '/bin/claude', prefixArgs: [] }) -) { - const prewarm = vi.fn() - const done = prewarmClaudeCliFlags({ - cliFlags: { prewarm }, - store: { - listVisibleSessionIds: () => records.map((r) => r.sessionId), - getRecord: (id) => records.find((r) => r.sessionId === id) ?? null - }, - resolveCommand, - resolveEnv: () => ({ PATH: '/shims' }), - resolveInheritedEnv: async () => ({ PATH: '/usr/bin' }) - }) - return { prewarm, done } -} - -describe('prewarming the Claude version check at startup', () => { - it("probes the home folder and each open local Claude chat's own folder, a few at most", async () => { - const { prewarm, done } = prewarmWith([ - record('a', { dir: '/scratch/a' }), - record('codex', { provider: 'codex', dir: '/scratch/codex' }), - record('remote', { host: 'ssh:box', dir: '/scratch/remote' }), - record('wsl', { wslDistro: 'Ubuntu', dir: '/scratch/wsl' }), - record('b', { dir: '/scratch/b' }), - record('unpinned'), - record('c', { dir: '/scratch/c' }), - record('d', { dir: '/scratch/d' }) - ]) - await done - expect(prewarm.mock.calls.map(([launch]) => launch.cwd)).toEqual([ - homedir(), - '/scratch/a', - '/scratch/b', - '/scratch/c' - ]) - expect(prewarm.mock.calls[0]?.[0]).toMatchObject({ command: '/bin/claude' }) - }) - - it('never throws when the CLI cannot be resolved', async () => { - const { prewarm, done } = prewarmWith([], () => { - throw new Error('the claude Command setting is not a runnable program') - }) - await expect(done).resolves.toBeUndefined() - expect(prewarm).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/codex-accounts/codex-config-mirror-wsl-stopped.test.ts b/src/main/codex-accounts/codex-config-mirror-wsl-stopped.test.ts deleted file mode 100644 index c7e8779d693..00000000000 --- a/src/main/codex-accounts/codex-config-mirror-wsl-stopped.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - existsSync: vi.fn((_path: string) => false), - runningSettled: vi.fn((_distro: string, _options?: { maxAgeMs?: number }) => false) -})) -vi.mock('node:fs', async (importOriginal) => ({ - ...(await importOriginal()), - existsSync: mocks.existsSync -})) -vi.mock('../wsl-background-distro-gate', async (importOriginal) => ({ - ...(await importOriginal()), - wasWslDistroLastSeenRunningSettled: mocks.runningSettled -})) - -import { createGlobalSettingsFixture } from '../../shared/global-settings-test-fixture' -import { CodexConfigMirror } from './codex-config-mirror' -import { WSL_UNC_RUNNING_LEASE_MS } from '../wsl/wsl-unc-access-gate' - -const WSL_HOME = - '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-accounts\\acct\\home' - -const SETTINGS = createGlobalSettingsFixture({ - codexManagedAccounts: [ - { - id: 'acct', - email: 'wsl@example.com', - managedHomePath: WSL_HOME, - managedHomeRuntime: 'wsl', - wslDistro: 'Ubuntu', - wslLinuxHomePath: '/home/ada/.local/share/orca/codex-accounts/acct/home', - providerAccountId: null, - workspaceLabel: null, - workspaceAccountId: null, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } - ] -}) - -function mirror(): CodexConfigMirror { - return new CodexConfigMirror({ getSettings: () => SETTINGS }, (path) => path) -} - -const uncTouches = (): number => - mocks.existsSync.mock.calls.filter(([path]) => String(path).startsWith('\\\\wsl')).length - -beforeEach(() => { - mocks.existsSync.mockClear() - mocks.runningSettled.mockReset().mockReturnValue(false) -}) - -describe('Codex config mirror never boots a stopped WSL distro (E9)', () => { - it('leaves a WSL account home alone at startup when its distro is not seen running', () => { - mirror().safeSyncToManagedHomes() - expect(uncTouches()).toBe(0) - }) - - it('syncs a WSL account home whose distro was seen running after any stop', () => { - mocks.runningSettled.mockReturnValue(true) - mirror().safeSyncToManagedHomes() - expect(uncTouches()).toBe(1) - }) - - it('asks for a running list no older than the UNC lease', () => { - mirror().safeSyncToManagedHomes() - expect(mocks.runningSettled).toHaveBeenCalledWith('Ubuntu', { - maxAgeMs: WSL_UNC_RUNNING_LEASE_MS - }) - }) -}) diff --git a/src/main/codex/codex-structured-owner-identity.test.ts b/src/main/codex/codex-structured-owner-identity.test.ts deleted file mode 100644 index e5d8df1f939..00000000000 --- a/src/main/codex/codex-structured-owner-identity.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { codexProcessIdentity, codexProviderHandleLink } from './codex-structured-owner-identity' -import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' - -const IDENTITY = { - sessionId: 'session-identity', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex' as const, - providerHandle: codexProviderHandle('thread-1') -} - -describe('codex process identity', () => { - it('records the observed start time alongside the spawn token', async () => { - await expect( - codexProcessIdentity( - { identity: IDENTITY, spawnToken: 'spawn-a', pid: 4242 }, - async () => 123 - ) - ).resolves.toEqual({ - hostId: 'local', - pid: 4242, - processStartTimeMs: 123, - spawnToken: 'spawn-a' - }) - }) - - it('retries a failed start-time read before giving up', async () => { - const readStartTime = vi - .fn<(pid: number) => Promise>() - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(456) - await expect( - codexProcessIdentity({ identity: IDENTITY, spawnToken: 'spawn-a', pid: 4242 }, readStartTime) - ).resolves.toMatchObject({ processStartTimeMs: 456 }) - expect(readStartTime).toHaveBeenCalledTimes(3) - }) - - it('records an owner whose start time is unreadable instead of refusing the session', async () => { - const readStartTime = vi.fn(async () => null) - await expect( - codexProcessIdentity({ identity: IDENTITY, spawnToken: 'spawn-a', pid: 4242 }, readStartTime) - ).resolves.toEqual({ - hostId: 'local', - pid: 4242, - processStartTimeMs: null, - spawnToken: 'spawn-a' - }) - expect(readStartTime).toHaveBeenCalledTimes(3) - }) -}) - -describe('codex provider handle link', () => { - it('names the unsaved thread a creation superseded, and nothing else can', () => { - expect( - codexProviderHandleLink({ - threadId: 'thread-new', - resumed: false, - supersedesThreadId: 'thread-unsaved', - fence: 3, - observedAt: 1 - }) - ).toMatchObject({ origin: 'created', supersedesKey: 'codex:"thread-unsaved"' }) - const base = { threadId: 'thread-new', fence: 3, observedAt: 1 } - // @ts-expect-error an adopted conversation was never an unsaved creation - codexProviderHandleLink({ ...base, resumed: false, origin: 'adopted', supersedesThreadId: 't' }) - // @ts-expect-error a resume proved the thread it named, so it replaces nothing - codexProviderHandleLink({ ...base, resumed: true, supersedesThreadId: 't' }) - }) -}) diff --git a/src/main/codex/codex-trust-grant-host.test.ts b/src/main/codex/codex-trust-grant-host.test.ts deleted file mode 100644 index 2a5993b0842..00000000000 --- a/src/main/codex/codex-trust-grant-host.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { runProcessMock } = vi.hoisted(() => ({ runProcessMock: vi.fn() })) - -vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) - -import { resolveCodexTrustGrantHost } from './codex-trust-grant-host' - -beforeEach(() => { - runProcessMock.mockReset() - // exec replaces the identity shell, leaving the captured payload without an end fence. - runProcessMock.mockImplementation((spec: { args: string[] }) => { - const nonce = /__ORCA_WSL_CAPTURE_BEGIN_ ([^_]+)__/.exec(String(spec.args.at(-1)))?.[1] ?? '' - return Promise.resolve({ - code: 0, - signal: null, - timedOut: false, - stderr: '', - stdout: - 'To run a command as administrator (user "root"), use "sudo ".\n\n' + - `__ORCA_WSL_CAPTURE_BEGIN_${nonce}__/home/alice/.local/bin/codex\ncodex-cli 1.2.3\n` - }) - }) -}) - -describe('resolveCodexTrustGrantHost', () => { - it("builds WSL requests, stamped with the guest's codex path and version", async () => { - const host = await resolveCodexTrustGrantHost({ - kind: 'wsl', - distro: 'Ubuntu', - linuxRuntimeHome: '/home/alice/.codex-runtime' - }) - const request = host.buildRequest({ - runtimeHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex-runtime', - managedCommand: '/bin/sh codex-hook.sh', - expectedTrustKeys: ['managed-key'] - }) - - expect(host.binaryStamp).toEqual({ - kind: 'wsl', - distro: 'Ubuntu', - path: '/home/alice/.local/bin/codex', - version: 'codex-cli 1.2.3' - }) - expect(request.invocation.command).toBe('wsl.exe') - expect(runProcessMock).toHaveBeenCalledWith( - expect.objectContaining({ - program: 'wsl.exe', - args: expect.arrayContaining(['-d', 'Ubuntu', '--exec', 'sh', '-c']), - timeoutMs: 5_000 - }) - ) - }) - - it('drops the stamp when the guest probe fails instead of trusting partial stdout', async () => { - runProcessMock.mockResolvedValue({ - code: 127, - signal: null, - timedOut: false, - stdout: '', - stderr: 'codex not found' - }) - - const host = await resolveCodexTrustGrantHost({ - kind: 'wsl', - distro: 'Ubuntu', - linuxRuntimeHome: '/home/alice/.codex-runtime' - }) - - expect(host.binaryStamp).toBeNull() - }) -}) diff --git a/src/main/daemon/daemon-endpoint-windows.test.ts b/src/main/daemon/daemon-endpoint-windows.test.ts deleted file mode 100644 index 6e57aa4f2d1..00000000000 --- a/src/main/daemon/daemon-endpoint-windows.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Exercise named-pipe ownership branches on any host. -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { - publishDaemonEndpoint, - readDaemonEndpointOwnershipState, - readDaemonSocketIdentity -} from './daemon-endpoint-ownership' - -describe('daemon endpoint ownership on win32', () => { - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - let dir: string - - beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'daemon-endpoint-win32-')) - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - }) - - afterEach(() => { - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - rmSync(dir, { recursive: true, force: true }) - }) - - it('publishes without probing or touching the filesystem', async () => { - const boundPath = join(dir, 'bound.sock') - const canonicalPath = join(dir, 'daemon.sock') - writeFileSync(boundPath, '') - const probe = vi.fn() - - const outcome = await publishDaemonEndpoint(boundPath, canonicalPath, probe) - - expect(outcome).toEqual({ status: 'published', identity: null }) - expect(probe).not.toHaveBeenCalled() - expect(existsSync(canonicalPath)).toBe(false) - }) - - it('publishes even where the canonical name is already taken', async () => { - const boundPath = join(dir, 'bound.sock') - const canonicalPath = join(dir, 'daemon.sock') - writeFileSync(boundPath, '') - writeFileSync(canonicalPath, 'someone else') - const probe = vi.fn() - - // Windows binds the canonical pipe directly; successful listen already establishes ownership. - await expect(publishDaemonEndpoint(boundPath, canonicalPath, probe)).resolves.toEqual({ - status: 'published', - identity: null - }) - expect(probe).not.toHaveBeenCalled() - }) - - it('reports no identity, so nothing can later claim ownership was lost', () => { - const realFile = join(dir, 'daemon.sock') - writeFileSync(realFile, '') - - expect(readDaemonSocketIdentity(realFile)).toBeNull() - }) - - it('never reports lost ownership, so a daemon is never retired on Windows', () => { - const missing = join(dir, 'gone.sock') - - // Named pipes have no directory entry; absence cannot establish a takeover. - expect(readDaemonEndpointOwnershipState(missing, null)).toBe('indeterminate') - expect(readDaemonEndpointOwnershipState(missing, { dev: 1n, ino: 2n })).toBe('indeterminate') - }) -}) diff --git a/src/main/daemon/daemon-lifecycle-event.test.ts b/src/main/daemon/daemon-lifecycle-event.test.ts deleted file mode 100644 index 1cf993fd25a..00000000000 --- a/src/main/daemon/daemon-lifecycle-event.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { bucketDaemonLiveSessionCount } from '../../shared/daemon-lifecycle-telemetry' -import { validate } from '../telemetry/validator' - -const { trackMock } = vi.hoisted(() => ({ trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) - -import { trackDaemonReplaced, trackDaemonRetired } from './daemon-lifecycle-event' - -beforeEach(() => { - trackMock.mockClear() -}) - -describe('bucketDaemonLiveSessionCount', () => { - it('buckets counts and maps null to unknown', () => { - expect(bucketDaemonLiveSessionCount(null)).toBe('unknown') - expect(bucketDaemonLiveSessionCount(0)).toBe('0') - expect(bucketDaemonLiveSessionCount(1)).toBe('1') - expect(bucketDaemonLiveSessionCount(2)).toBe('2-5') - expect(bucketDaemonLiveSessionCount(5)).toBe('2-5') - expect(bucketDaemonLiveSessionCount(6)).toBe('6+') - expect(bucketDaemonLiveSessionCount(999)).toBe('6+') - }) -}) - -describe('daemon lifecycle emitters', () => { - it('emits a validator-accepted replace payload', () => { - trackDaemonReplaced('stale_bundle', 0) - expect(trackMock).toHaveBeenCalledTimes(1) - const [name, props] = trackMock.mock.calls[0] - expect(name).toBe('daemon_lifecycle') - expect(props).toEqual({ - transition: 'replaced', - reason: 'stale_bundle', - live_session_count_bucket: '0' - }) - expect(validate('daemon_lifecycle', props).ok).toBe(true) - }) - - it('maps an unverifiable session count to the unknown bucket', () => { - trackDaemonReplaced('different_app_path', null) - const [, props] = trackMock.mock.calls[0] - expect(props).toEqual({ - transition: 'replaced', - reason: 'different_app_path', - live_session_count_bucket: 'unknown' - }) - expect(validate('daemon_lifecycle', props).ok).toBe(true) - }) - - it('swallows a throwing telemetry client instead of failing the caller', () => { - trackMock.mockImplementationOnce(() => { - throw new Error('posthog exploded') - }) - expect(() => trackDaemonReplaced('failed_health_check', null)).not.toThrow() - trackMock.mockImplementationOnce(() => { - throw new Error('posthog exploded') - }) - expect(() => trackDaemonRetired('died_respawn')).not.toThrow() - }) - - it('emits a validator-accepted retirement payload', () => { - trackDaemonRetired('died_respawn') - const [name, props] = trackMock.mock.calls[0] - expect(name).toBe('daemon_lifecycle') - expect(props).toEqual({ - transition: 'retired', - reason: 'died_respawn', - live_session_count_bucket: 'unknown' - }) - expect(validate('daemon_lifecycle', props).ok).toBe(true) - }) -}) diff --git a/src/main/daemon/pty-subprocess/spawn-preflight-health-probe.test.ts b/src/main/daemon/pty-subprocess/spawn-preflight-health-probe.test.ts deleted file mode 100644 index 5f673b8abc7..00000000000 --- a/src/main/daemon/pty-subprocess/spawn-preflight-health-probe.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const nodePty = vi.hoisted(() => ({ spawn: vi.fn() })) -vi.mock('node-pty', () => nodePty) - -import { runPtySpawnHealthProbe } from './spawn-preflight' - -function exitingPty(exitCode: number) { - let listener: ((event: { exitCode: number }) => void) | undefined - const proc = { - kill: vi.fn(), - onExit: vi.fn((callback: typeof listener) => { - listener = callback - queueMicrotask(() => listener?.({ exitCode })) - return { dispose: () => (listener = undefined) } - }) - } - nodePty.spawn.mockReturnValue(proc) - return proc -} - -describe('PTY spawn health probe teardown', () => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform')! - const previousUserDataPath = process.env.ORCA_USER_DATA_PATH - let userDataPath: string - - beforeEach(() => { - nodePty.spawn.mockReset() - userDataPath = mkdtempSync(join(tmpdir(), 'orca-pty-health-probe-')) - process.env.ORCA_USER_DATA_PATH = userDataPath - }) - afterEach(() => { - Object.defineProperty(process, 'platform', platform) - if (previousUserDataPath === undefined) { - delete process.env.ORCA_USER_DATA_PATH - } else { - process.env.ORCA_USER_DATA_PATH = previousUserDataPath - } - rmSync(userDataPath, { recursive: true, force: true }) - }) - - it('kills a cleanly exited Windows probe so its conout worker cannot hold the process open', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const proc = exitingPty(0) - - await expect(runPtySpawnHealthProbe()).resolves.toBeUndefined() - - expect(nodePty.spawn.mock.calls[0]![2]).toMatchObject({ useConptyDll: true }) - expect(proc.kill).toHaveBeenCalledOnce() - }) - - it('kills a Windows probe that exits non-zero', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - const proc = exitingPty(1) - - await expect(runPtySpawnHealthProbe()).rejects.toThrow(/exited with code 1/) - expect(proc.kill).toHaveBeenCalledOnce() - }) - - it('leaves a cleanly exited POSIX probe alone', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) - const proc = exitingPty(0) - - await expect(runPtySpawnHealthProbe()).resolves.toBeUndefined() - - expect(nodePty.spawn.mock.calls[0]![2]).not.toHaveProperty('useConptyDll') - expect(proc.kill).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/github/pr-start-point-wsl-gate.test.ts b/src/main/github/pr-start-point-wsl-gate.test.ts deleted file mode 100644 index d9b532f2252..00000000000 --- a/src/main/github/pr-start-point-wsl-gate.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as DistroGateModule from '../wsl-background-distro-gate' - -const mocks = vi.hoisted(() => { - const state: { distro: 'running' | 'stopped' | 'unverifiable' } = { distro: 'stopped' } - return { state } -}) -vi.mock('../wsl-background-distro-gate', async (importOriginal) => ({ - ...(await importOriginal()), - readWslDistroRunningState: vi.fn(async () => mocks.state.distro) -})) - -import { resolvePrStartPointUnlessWslStopped } from './pr-start-point-wsl-gate' - -const WSL_REPO = { path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' } -const START_POINT = { baseBranch: 'origin/main' } -const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - -describe('PR start point for a stopped WSL distro (E9)', () => { - beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - mocks.state.distro = 'stopped' - }) - - afterEach(() => { - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - }) - - it('refuses a background push-target ensure without resolving', async () => { - const resolve = vi.fn(async () => START_POINT) - await expect(resolvePrStartPointUnlessWslStopped(WSL_REPO, {}, resolve)).resolves.toEqual({ - error: "WSL distro 'Ubuntu' is not running. Open a terminal in it to start it." - }) - expect(resolve).not.toHaveBeenCalled() - }) - - it('refuses a host path whose Git and gh run in the stopped distro', async () => { - const resolve = vi.fn(async () => START_POINT) - const result = await resolvePrStartPointUnlessWslStopped( - { path: 'C:\\src\\repo', wslDistro: 'Ubuntu' }, - {}, - resolve - ) - expect(result).toHaveProperty('error') - expect(resolve).not.toHaveBeenCalled() - }) - - it('refuses when WSL cannot say the distro runs', async () => { - mocks.state.distro = 'unverifiable' - const resolve = vi.fn(async () => START_POINT) - const result = await resolvePrStartPointUnlessWslStopped(WSL_REPO, {}, resolve) - expect(result).toHaveProperty('error', expect.stringContaining("didn't answer")) - expect(resolve).not.toHaveBeenCalled() - }) - - it('resolves for the user creating from the PR, which may start the distro', async () => { - const resolve = vi.fn(async () => START_POINT) - await expect( - resolvePrStartPointUnlessWslStopped(WSL_REPO, { wakeWslDistro: true }, resolve) - ).resolves.toEqual(START_POINT) - }) - - it('resolves host repos and running distros as before', async () => { - const resolve = vi.fn(async () => START_POINT) - await expect( - resolvePrStartPointUnlessWslStopped({ path: 'C:\\src\\repo' }, {}, resolve) - ).resolves.toEqual(START_POINT) - mocks.state.distro = 'running' - await expect(resolvePrStartPointUnlessWslStopped(WSL_REPO, {}, resolve)).resolves.toEqual( - START_POINT - ) - }) -}) diff --git a/src/main/ipc/hooks/issue-command-wsl-running-signal.test.ts b/src/main/ipc/hooks/issue-command-wsl-running-signal.test.ts deleted file mode 100644 index ab88e7e00cc..00000000000 --- a/src/main/ipc/hooks/issue-command-wsl-running-signal.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - handlers: new Map Promise>(), - read: vi.fn(), - write: vi.fn(async () => undefined), - broadcast: vi.fn() -})) -vi.mock('electron', () => ({ - ipcMain: { - handle: (channel: string, handler: (event: unknown, args: unknown) => Promise) => - mocks.handlers.set(channel, handler) - } -})) -vi.mock('../../issue-command-file', () => ({ - readIssueCommandUnlessWslStopped: mocks.read, - writeIssueCommandUnlessWslStopped: mocks.write -})) -vi.mock('../preflight-wsl-refusal-retry', () => ({ - broadcastWhenWslDistroRunning: mocks.broadcast -})) -vi.mock('../../project-runtime-git-options', () => ({ - getLocalProjectWorktreeGitOptions: () => ({}) -})) -vi.mock('../../persistence/moving-wsl-projects/wsl-move-scope-guard', () => ({ - assertWslMoveRepoWritable: () => undefined -})) - -import { registerWorktreeHookFileHandlers } from './register-worktree-hook-file-handlers' - -const REPO = { id: 'repo-1', path: '\\\\wsl.localhost\\Ubuntu\\repo', kind: 'git' } - -function call(channel: string, args: Record): Promise { - const handler = mocks.handlers.get(channel) - if (!handler) { - throw new Error(`${channel} is not registered`) - } - return handler(null, { repoId: REPO.id, ...args }) -} - -describe('hooks issue-command IPC for a stopped WSL distro (E9)', () => { - beforeEach(() => { - mocks.handlers.clear() - mocks.read.mockReset() - mocks.write.mockClear() - mocks.broadcast.mockClear() - const store = { getRepos: () => [REPO], getRepo: () => REPO } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handlers read only these store accessors. - registerWorktreeHookFileHandlers({ store } as never) - }) - - it('asks main to signal the editor once the refusing distro runs', async () => { - mocks.read.mockResolvedValue({ status: 'error', refusedWslDistro: 'Ubuntu' }) - await call('hooks:readIssueCommand', {}) - expect(mocks.broadcast).toHaveBeenCalledWith('Ubuntu', 'issue-command:repo-1') - }) - - it('does not wait on a read that answered', async () => { - mocks.read.mockResolvedValue({ localContent: 'x', source: 'local' }) - await call('hooks:readIssueCommand', {}) - expect(mocks.broadcast).not.toHaveBeenCalled() - }) - - it("passes a save's user act through to the gated write", async () => { - await call('hooks:writeIssueCommand', { content: 'mine', wakeWslDistro: true }) - expect(mocks.write).toHaveBeenCalledWith(REPO.path, 'mine', expect.any(Function), { - wakeWslDistro: true - }) - }) -}) diff --git a/src/main/ipc/hooks/worktree-hook-check-background-gate.test.ts b/src/main/ipc/hooks/worktree-hook-check-background-gate.test.ts deleted file mode 100644 index d4379bddea7..00000000000 --- a/src/main/ipc/hooks/worktree-hook-check-background-gate.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../shared/repo-types' - -const mocks = vi.hoisted(() => ({ - handlers: new Map unknown>(), - hasHooksFile: vi.fn((_path: string) => false), - blocked: - vi.fn<(path: string) => Promise<{ distro: string; state: 'stopped' | 'unverifiable' } | null>>() -})) - -vi.mock('electron', () => ({ - ipcMain: { - handle: (channel: string, handler: (event: unknown, args: unknown) => unknown) => - mocks.handlers.set(channel, handler) - } -})) -vi.mock('../../hooks', () => ({ - hasHooksFile: mocks.hasHooksFile, - loadHooks: () => null, - hasUnrecognizedOrcaYamlKeys: () => false -})) -vi.mock('../../wsl/wsl-unc-access-gate', () => ({ blockedWslDistroForPath: mocks.blocked })) - -import { registerWorktreeHookCheckHandler } from './register-worktree-hook-check-handler' - -const UNC = String.raw`\\wsl.localhost\Ubuntu\home\u\app` - -function check(args: { background?: boolean }) { - const repo: Partial = { id: 'repo', path: UNC, kind: 'git', executionHostId: 'local' } - const store = { getRepos: () => [repo], getRepo: () => repo } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The handler reads only these store accessors. - registerWorktreeHookCheckHandler({ store } as never) - return mocks.handlers.get('hooks:check')!(null, { repoId: 'repo', ...args }) -} - -describe('hooks:check on a stopped WSL distro', () => { - beforeEach(() => { - mocks.hasHooksFile.mockClear() - mocks.blocked.mockReset() - mocks.blocked.mockResolvedValue({ distro: 'Ubuntu', state: 'stopped' }) - }) - - it('refuses a background check without opening orca.yaml, so it cannot boot the distro', async () => { - await expect(check({ background: true })).resolves.toEqual({ - status: 'error', - hasHooks: false, - hooks: null, - mayNeedUpdate: false, - unavailable: 'wsl-distro-stopped' - }) - expect(mocks.blocked).toHaveBeenCalledWith(UNC) - expect(mocks.hasHooksFile).not.toHaveBeenCalled() - }) - - it('marks an unverifiable distro unread, not hook-free, so callers retry instead of storing it', async () => { - mocks.blocked.mockResolvedValue({ distro: 'Ubuntu', state: 'unverifiable' }) - - const result = await check({ background: true }) - - expect(result).toMatchObject({ status: 'error', unavailable: 'wsl-distro-unverifiable' }) - expect(mocks.hasHooksFile).not.toHaveBeenCalled() - }) - - it('still reads for a launch, which is a user act that starts the distro anyway', async () => { - await expect(check({})).resolves.toMatchObject({ status: 'ok' }) - expect(mocks.blocked).not.toHaveBeenCalled() - expect(mocks.hasHooksFile).toHaveBeenCalledWith(UNC) - }) - - it('reads a running distro for a background check as before', async () => { - mocks.blocked.mockResolvedValue(null) - - await expect(check({ background: true })).resolves.toMatchObject({ status: 'ok' }) - expect(mocks.hasHooksFile).toHaveBeenCalledWith(UNC) - }) -}) diff --git a/src/main/ipc/pty/host-env/codex-hook-reconcile-spawn.test.ts b/src/main/ipc/pty/host-env/codex-hook-reconcile-spawn.test.ts deleted file mode 100644 index c20e871310b..00000000000 --- a/src/main/ipc/pty/host-env/codex-hook-reconcile-spawn.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { BuildPtyHostEnvOptions } from './types' - -const fixture = vi.hoisted(() => ({ userData: '', scheduleCodexHookReconcile: vi.fn() })) -vi.mock('../../../../shared/app-environment', () => ({ - getAppEnvironment: () => ({ getPath: () => fixture.userData, onWillQuit: vi.fn() }) -})) -vi.mock('../../../agent-hooks/server', () => ({ - agentHookServer: { buildPtyEnv: () => ({ ORCA_AGENT_HOOK_PORT: '12345' }) } -})) -vi.mock('../../../agent-hooks/wsl-hook-relay-manager', () => ({ - wslHookRelayManager: { - ensureForDistro: vi.fn(), - getGuestEndpointFilePath: () => '/guest/endpoint.json', - getOpenCodeOverlayDir: () => join(fixture.userData, 'guest-overlay'), - getClaudeAgentView: () => null, - getGuestAgentPath: () => null - } -})) -vi.mock('../../../pi/titlebar-extension-service', () => ({ - piTitlebarExtensionService: { buildPtyEnv: () => ({}), buildFreshOmpEnv: () => ({}) } -})) -vi.mock('../../../cli/orca-cli-child-path', () => ({ prependOrcaCliDirToChildPath: () => {} })) -vi.mock('../../../cli/wsl-managed-cli', () => ({ - getManagedWslCliDir: () => undefined, - getWslCliCommandName: () => 'orca-ide' -})) -vi.mock('../../../codex/codex-hook-reconcile', () => ({ - scheduleCodexHookReconcile: fixture.scheduleCodexHookReconcile -})) - -import { buildPtyHostEnv } from './assembly' - -// Typed Codex commands use native ~/.codex; reconcile on native spawns, never Windows-side for WSL panes. - -let root: string -let options: BuildPtyHostEnvOptions - -beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'orca-codex-reconcile-spawn-')) - fixture.userData = join(root, 'user-data') - vi.stubEnv('HOME', join(root, 'home')) - vi.stubEnv('USERPROFILE', join(root, 'home')) - options = { - isPackaged: true, - userDataPath: fixture.userData, - selectedCodexHomePath: null, - agentStatusHooksEnabled: true - } - fixture.scheduleCodexHookReconcile.mockClear() -}) - -afterEach(() => { - vi.unstubAllEnvs() - rmSync(root, { recursive: true, force: true }) -}) - -describe("a pane spawn rechecks Orca's entry in ~/.codex", () => { - it('on a native spawn', () => { - buildPtyHostEnv('native-pane', {}, options) - - expect(fixture.scheduleCodexHookReconcile).toHaveBeenCalledTimes(1) - }) - - it('never on a WSL spawn', () => { - buildPtyHostEnv('wsl-pane', {}, { ...options, isWsl: true, wslDistro: 'Ubuntu' }) - - expect(fixture.scheduleCodexHookReconcile).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/pty/pty-restored-appimage-cli-shim-refresh.test.ts b/src/main/ipc/pty/pty-restored-appimage-cli-shim-refresh.test.ts deleted file mode 100644 index 568b637cde1..00000000000 --- a/src/main/ipc/pty/pty-restored-appimage-cli-shim-refresh.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { setupPtyIpcSuite } from './pty-ipc-test-harness' -import { linuxCliShimMock } from './pty-ipc-mock-registry' - -vi.mock('electron', () => import('./pty-ipc-mock-registry').then((m) => m.electronModuleMock())) -vi.mock('fs', () => import('./pty-ipc-mock-registry').then((m) => m.fsModuleMock())) -vi.mock('node-pty', () => import('./pty-ipc-mock-registry').then((m) => m.nodePtyModuleMock())) -vi.mock('node:child_process', async (importOriginal) => - (await import('./pty-ipc-mock-registry')).childProcessModuleMock(await importOriginal()) -) -vi.mock('../../opencode/hook-service', () => - import('./pty-ipc-mock-registry').then((m) => m.openCodeHookServiceModuleMock()) -) -vi.mock('../../mimo/hook-service', () => - import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) -) -vi.mock('../../agent-hooks/server', () => - import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) -) -vi.mock('../../pi/titlebar-extension-service', () => - import('./pty-ipc-mock-registry').then((m) => m.piTitlebarExtensionModuleMock()) -) -vi.mock('../../pwsh', () => import('./pty-ipc-mock-registry').then((m) => m.pwshModuleMock())) -vi.mock('../../wsl', async (importOriginal) => - (await import('./pty-ipc-mock-registry')).wslModuleMock(await importOriginal()) -) -vi.mock('../../telemetry/client', () => - import('./pty-ipc-mock-registry').then((m) => m.telemetryClientModuleMock()) -) -vi.mock('../../telemetry/classify-error', () => - import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) -) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => - import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) -) -vi.mock('../../memory/pty-registry', () => - import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) -) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => - import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) -) -vi.mock('../../codex/codex-pane-account-registry', () => - import('./pty-ipc-mock-registry').then((m) => m.codexPaneAccountRegistryModuleMock()) -) -vi.mock('../../codex/codex-state-db-backfill-recovery', () => - import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock()) -) - -import { registerPtyHandlers } from './register-handlers' - -const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! - -afterEach(() => { - Object.defineProperty(process, 'platform', originalPlatform) -}) - -describe('restored AppImage CLI shim refresh', () => { - const { mainWindow } = setupPtyIpcSuite() - - it('refreshes the live launcher before any restored pane reattaches', () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) - - registerPtyHandlers(mainWindow as never) - - expect(linuxCliShimMock).toHaveBeenCalledOnce() - expect(linuxCliShimMock).toHaveBeenCalledWith({ userDataPath: '/tmp/orca-user-data' }) - }) - - it('does not publish a host launcher on a non-Linux host', () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - - registerPtyHandlers(mainWindow as never) - - expect(linuxCliShimMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/pty/runtime/spawn-commit-response.test.ts b/src/main/ipc/pty/runtime/spawn-commit-response.test.ts deleted file mode 100644 index c3935d76ea2..00000000000 --- a/src/main/ipc/pty/runtime/spawn-commit-response.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { reportRuntimeResumeOutcome } from './spawn-commit-response' -import { createRuntimePtySpawnState, type RuntimePtySpawnArgs } from './spawn-state' -import type { PtyRuntimeControllerDeps } from './controller-deps' - -type Facts = { - resumed?: boolean - unavailable?: boolean - dropped?: boolean - isReattach?: boolean - refused?: boolean -} - -/** What a committed spawn tells its start, from a start that did or did not ask to resume. */ -function reply({ - resumed = false, - unavailable = false, - dropped = false, - isReattach, - refused -}: Facts) { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the report reads no deps. - const deps = {} as unknown as PtyRuntimeControllerDeps - const onResumeOutcome = vi.fn() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the report reads only the resume asked for and its sink. - const args = { - cols: 120, - rows: 40, - onResumeOutcome, - ...(resumed ? { resumeProviderSession: { key: 'session_id', id: 'codex-session-1' } } : {}) - } as unknown as RuntimePtySpawnArgs - const ctx = createRuntimePtySpawnState(deps, args) - ctx.result = { - id: 'pty-1', - ...(isReattach ? { isReattach } : {}), - ...(refused - ? { agentResumeRefused: 'chat-home' as const, agentResumeUnavailable: true as const } - : {}) - } - ctx.codexResumeUnavailable = unavailable - ctx.codexResumeArgvDropped = dropped || unavailable - reportRuntimeResumeOutcome(ctx) - return { - resumeOutcome: onResumeOutcome.mock.calls[0]?.[1], - ptyId: onResumeOutcome.mock.calls[0]?.[0] - } -} - -describe("a runtime spawn's resume outcome", () => { - const on = (value: T): T | undefined => (ORCA_LAYOUT_OWNER_IS_MAIN ? value : undefined) - - it('says a resumed start restored its agent, switch-on only', () => { - expect(reply({ resumed: true })).toEqual({ resumeOutcome: on('restored'), ptyId: on('pty-1') }) - }) - - it('says a start whose unverified resume was dropped runs a fresh session', () => { - expect(reply({ resumed: true, unavailable: true }).resumeOutcome).toBe(on('resume-unavailable')) - }) - - it('reports the effective refused shell after admission removed its requested resume', () => { - expect(reply({ refused: true })).toEqual({ - resumeOutcome: on('resume-unavailable'), - ptyId: on('pty-1') - }) - }) - - it('says nothing for a plain start, a silently dropped resume, or a reattach', () => { - expect(reply({}).resumeOutcome).toBeUndefined() - expect(reply({ resumed: true, dropped: true }).resumeOutcome).toBeUndefined() - expect(reply({ resumed: true, isReattach: true }).resumeOutcome).toBeUndefined() - expect(reply({ refused: true, isReattach: true }).resumeOutcome).toBeUndefined() - }) -}) diff --git a/src/main/ipc/worktrees/listing/detected-provider-listing-meta-index.test.ts b/src/main/ipc/worktrees/listing/detected-provider-listing-meta-index.test.ts deleted file mode 100644 index 37883e97ad2..00000000000 --- a/src/main/ipc/worktrees/listing/detected-provider-listing-meta-index.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { Store } from '../../../persistence/loading-store/store' -import type * as SshWorktreeFallbackModule from './ssh-worktree-fallback' - -const { indexBuildSpy } = vi.hoisted(() => ({ indexBuildSpy: vi.fn() })) - -vi.mock('./ssh-worktree-fallback', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - // Count both builders to expose a duplicate pass through either one. - createSshWorktreeMetaIndex: (...args: Parameters) => { - indexBuildSpy('all-hosts', ...args) - return actual.createSshWorktreeMetaIndex(...args) - }, - createSshWorktreeMetaIndexForRepo: ( - ...args: Parameters - ) => { - indexBuildSpy('repo-scoped', ...args) - return actual.createSshWorktreeMetaIndexForRepo(...args) - } - } -}) - -const { listDetectedWorktreesForCapturedRepo } = await import('./detected-provider-listing') - -const repo = { - id: 'repo-1', - path: '/home/user/repo', - displayName: 'repo', - connectionId: 'conn-1' -} as Repo - -const worktreeId = `${repo.id}::/home/user/feature` - -function createStore(): Store { - const rows: Record = { - [worktreeId]: { instanceId: 'instance-1' }, - // Other repos share the snapshot; index reads must remain repo-scoped. - 'repo-2::/home/user/other': { instanceId: 'instance-2' } - } - return { - getRepos: () => [repo], - getRepo: () => repo, - getSettings: () => ({}), - getProjectHostSetups: () => [], - getAllWorktreeLineage: () => ({}), - getAllWorktreeMeta: () => rows, - getWorktreeMeta: (id: string) => rows[id], - setWorktreeMeta: vi.fn() - } as unknown as Store -} - -describe('SSH worktree meta index construction', () => { - beforeEach(() => { - indexBuildSpy.mockClear() - }) - - it('builds the index once for an SSH repo', async () => { - const result = await listDetectedWorktreesForCapturedRepo(createStore(), repo, () => true) - - expect(result).toMatchObject({ authoritative: false, source: 'metadata-fallback' }) - expect(indexBuildSpy).toHaveBeenCalledTimes(1) - expect(indexBuildSpy).toHaveBeenCalledWith('all-hosts', expect.anything()) - expect( - (result as { worktrees: { id: string }[] }).worktrees.map((worktree) => worktree.id) - ).toEqual([worktreeId]) - }) -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-reconcile.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-reconcile.test.ts deleted file mode 100644 index 595fc8672f1..00000000000 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-reconcile.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AgentSessionRecord } from '../../../shared/agent-session-record' -import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' -import { createRestartReconciler } from './structured-agent-session-restart-reconcile' - -describe('createRestartReconciler', () => { - it('reruns after an external store refresh introduces unreconciled leases', async () => { - let record = { sessionId: 'session-1', lease: { unreconciled: true } } as AgentSessionRecord - const reconcileOnRestart = vi.fn(async () => { - record = { ...record, lease: { ...record.lease, unreconciled: false } } - return new Map() - }) - const store = { - listRecords: () => [record], - getRecord: () => record, - reconcileOnRestart - } as unknown as AgentSessionRecordStore - const reconcile = createRestartReconciler({ - store, - probe: async () => ({ outcome: 'pid-absent' }), - now: () => 1 - }) - - expect(await reconcile('session-1')).toBeNull() - record = { ...record, lease: { ...record.lease, unreconciled: true } } - expect(await reconcile('session-1')).toBeNull() - expect(reconcileOnRestart).toHaveBeenCalledTimes(2) - }) - - it('passes only the addressed record through the batch owner probe', async () => { - let records = [ - { sessionId: 'session-1', lease: { unreconciled: true } }, - { sessionId: 'session-2', lease: { unreconciled: true } } - ] as AgentSessionRecord[] - const probe = vi.fn(async () => ({ outcome: 'pid-absent' as const })) - const probeMany = vi.fn(async (pending: readonly AgentSessionRecord[]) => { - return new Map( - pending.map((record) => [record.sessionId, { outcome: 'pid-absent' as const }]) - ) - }) - const reconcileOnRestart = vi.fn( - async (args: { - sessionId?: string - probeMany?: ( - pending: readonly AgentSessionRecord[] - ) => Promise> - }) => { - await args.probeMany?.(records.filter((record) => record.sessionId === args.sessionId)) - records = records.map((record) => ({ - ...record, - lease: { - ...record.lease, - unreconciled: record.sessionId !== args.sessionId - } - })) - return new Map() - } - ) - const store = { - listRecords: () => records, - getRecord: (sessionId: string) => - records.find((record) => record.sessionId === sessionId) ?? null, - reconcileOnRestart - } as unknown as AgentSessionRecordStore - - await expect( - createRestartReconciler({ store, probe, probeMany, now: () => 1 })('session-1') - ).resolves.toBeNull() - - expect(probeMany).toHaveBeenCalledOnce() - expect(probeMany.mock.calls[0]?.[0].map((record) => record.sessionId)).toEqual(['session-1']) - expect(records[1]?.lease.unreconciled).toBe(true) - expect(probe).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/orcad/orcad-wsl-host-login-environment.test.ts b/src/main/orcad/orcad-wsl-host-login-environment.test.ts deleted file mode 100644 index f37c7cc411d..00000000000 --- a/src/main/orcad/orcad-wsl-host-login-environment.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const loginShell = vi.hoisted(() => ({ - resolveLoginShellEnvironment: vi.fn(async (_options?: { env?: NodeJS.ProcessEnv }) => ({})) -})) -vi.mock('../startup/login-shell-environment', () => loginShell) - -import { - adoptWslHostLoginEnvironment, - wslHostLoginEnvironmentOverlay -} from './orcad-wsl-host-login-environment' - -const shellEnv: NodeJS.ProcessEnv = { - SSH_AUTH_SOCK: '/home/u/.ssh/agent.sock', - https_proxy: 'http://proxy.internal:3128', - GNUPGHOME: '/home/u/.gnupg', - PATH: '/home/u/.local/bin:/usr/bin', - GIT_ASKPASS: '/usr/bin/ksshaskpass', - WSL_INTEROP: '/run/WSL/99_interop', - SECRET_FROM_RC: 'nope' -} - -describe('wslHostLoginEnvironmentOverlay', () => { - it('takes only allowlisted variables, leaving PATH, askpass and interop to their owners', () => { - expect(wslHostLoginEnvironmentOverlay(shellEnv, { PATH: '/usr/bin' })).toEqual({ - SSH_AUTH_SOCK: '/home/u/.ssh/agent.sock', - https_proxy: 'http://proxy.internal:3128', - GNUPGHOME: '/home/u/.gnupg' - }) - }) - - it('lets the login shell win over a different launch value, as `$SHELL -ilc` did', () => { - expect( - wslHostLoginEnvironmentOverlay( - { SSH_AUTH_SOCK: '/rc/agent.sock', GNUPGHOME: '/same' }, - { SSH_AUTH_SOCK: '/launch/agent.sock', GNUPGHOME: '/same' } - ) - ).toEqual({ SSH_AUTH_SOCK: '/rc/agent.sock' }) - }) -}) - -describe('adoptWslHostLoginEnvironment', () => { - it('applies the overlay to the env on a WSL host and reports the names', async () => { - const env: NodeJS.ProcessEnv = { PATH: '/usr/bin' } - const names = await adoptWslHostLoginEnvironment( - env, - async () => shellEnv, - () => true - ) - expect(names).toEqual(['SSH_AUTH_SOCK', 'GNUPGHOME', 'https_proxy']) - expect(env).toEqual({ - PATH: '/usr/bin', - SSH_AUTH_SOCK: '/home/u/.ssh/agent.sock', - GNUPGHOME: '/home/u/.gnupg', - https_proxy: 'http://proxy.internal:3128' - }) - }) - - it('probes with the PATH probe marker, so an rc that skips `exec tmux` for it still exports', async () => { - await adoptWslHostLoginEnvironment({ HOME: '/home/u' }, undefined, () => true) - expect(loginShell.resolveLoginShellEnvironment).toHaveBeenCalledWith({ - env: { HOME: '/home/u', ORCA_SHELL_PATH_PROBE: '1' }, - timeoutMs: 10_000 - }) - }) - - it('never probes the login shell off a WSL host', async () => { - const resolve = vi.fn(async () => shellEnv) - const env: NodeJS.ProcessEnv = {} - expect(await adoptWslHostLoginEnvironment(env, resolve, () => false)).toEqual([]) - expect(resolve).not.toHaveBeenCalled() - expect(env).toEqual({}) - }) -}) diff --git a/src/main/runtime/rpc/methods/client-events.test.ts b/src/main/runtime/rpc/methods/client-events.test.ts deleted file mode 100644 index c4a7503b1c9..00000000000 --- a/src/main/runtime/rpc/methods/client-events.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' -import type { OrcaRuntimeService } from '../../orca-runtime' -import { - eraseRpcMethods, - isStreamingMethod, - type RpcContext, - type RpcStreamingMethod -} from '../core' -// Import the registry to avoid client-events' module-init cycle through ipc/ssh. -import { ALL_RPC_METHODS } from './index' - -const subscribeMethod = eraseRpcMethods(ALL_RPC_METHODS).find( - (method) => method.name === 'runtime.clientEvents.subscribe' && isStreamingMethod(method) -) as RpcStreamingMethod - -function makeRuntime(): { - runtime: OrcaRuntimeService - onClientEvent: ReturnType - cleanups: (() => void)[] -} { - const cleanups: (() => void)[] = [] - const onClientEvent = vi.fn( - ( - _listener: (event: RuntimeClientEvent) => void, - _options?: { consumesTerminalSideEffects?: boolean } - ) => - () => {} - ) - const runtime = { - onClientEvent, - registerSubscriptionCleanup: (_id: string, cleanup: () => void) => { - cleanups.push(cleanup) - } - } as unknown as OrcaRuntimeService - return { runtime, onClientEvent, cleanups } -} - -describe('runtime.clientEvents.subscribe', () => { - it('registers mobile subscriptions as non-consumers of terminal side effects', async () => { - const { runtime, onClientEvent, cleanups } = makeRuntime() - - const done = subscribeMethod.handler( - undefined, - { runtime, connectionId: 'conn-1', clientKind: 'mobile' } as RpcContext, - () => {} - ) - - expect(onClientEvent).toHaveBeenCalledWith(expect.any(Function), { - consumesTerminalSideEffects: false - }) - cleanups.forEach((cleanup) => cleanup()) - await done - }) - - it('keeps non-mobile subscriptions consuming terminal side effects', async () => { - const { runtime, onClientEvent, cleanups } = makeRuntime() - - const done = subscribeMethod.handler( - undefined, - { runtime, connectionId: 'conn-1' } as RpcContext, - () => {} - ) - - expect(onClientEvent).toHaveBeenCalledWith(expect.any(Function), { - consumesTerminalSideEffects: true - }) - cleanups.forEach((cleanup) => cleanup()) - await done - }) -}) diff --git a/src/main/runtime/rpc/methods/files-write-disk-precondition.test.ts b/src/main/runtime/rpc/methods/files-write-disk-precondition.test.ts deleted file mode 100644 index d4f96a82f8c..00000000000 --- a/src/main/runtime/rpc/methods/files-write-disk-precondition.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import '../unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../dispatcher' -import type { RpcRequest } from '../core' -import type { OrcaRuntimeService } from '../../orca-runtime' -import { FILE_METHODS } from './files' - -function makeRequest(method: string, params?: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method, params } -} - -describe('files.writeIfUnchanged', () => { - it('forwards a save disk precondition to the runtime writer', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the dispatcher reaches only the two stubbed members. - const runtime = { - getRuntimeId: () => 'test-runtime', - writeFileExplorerFile: vi.fn().mockResolvedValue({ ok: false, diskConflict: 'changed' }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: FILE_METHODS }) - const diskPrecondition = { - expectedSignature: 'a-b-1', - allowMissing: true, - requireLosslessUtf8: true - } - - const response = await dispatcher.dispatch( - makeRequest('files.writeIfUnchanged', { - worktree: 'id:wt-1', - relativePath: 'src/index.ts', - content: 'export {}', - expectedExecutionHostId: 'local', - diskPrecondition - }) - ) - - expect(runtime.writeFileExplorerFile).toHaveBeenCalledWith( - 'id:wt-1', - 'src/index.ts', - 'export {}', - undefined, - undefined, - 'local', - diskPrecondition - ) - expect(response).toMatchObject({ ok: true, result: { ok: false, diskConflict: 'changed' } }) - }) - - it('strips an unknown write field the way an older host would', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the dispatcher reaches only the two stubbed members. - const runtime = { - getRuntimeId: () => 'test-runtime', - writeFileExplorerFile: vi.fn().mockResolvedValue({ ok: true }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: FILE_METHODS }) - - await dispatcher.dispatch( - makeRequest('files.write', { - worktree: 'id:wt-1', - relativePath: 'src/index.ts', - content: 'export {}', - futureField: true - }) - ) - - expect(runtime.writeFileExplorerFile).toHaveBeenCalledWith( - 'id:wt-1', - 'src/index.ts', - 'export {}' - ) - }) -}) diff --git a/src/main/runtime/rpc/methods/terminal-navigation.test.ts b/src/main/runtime/rpc/methods/terminal-navigation.test.ts deleted file mode 100644 index 11212e53aac..00000000000 --- a/src/main/runtime/rpc/methods/terminal-navigation.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import '../unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../../orca-runtime' -import type { RpcRequest } from '../core' -import { RpcDispatcher } from '../dispatcher' -import { TERMINAL_METHODS } from './terminal' - -function request(params: unknown): RpcRequest { - return { - id: 'focus-1', - authToken: 'token', - method: 'terminal.focus', - params - } -} - -describe('terminal focus navigation authority', () => { - it('denies implicit paired focus while preserving local and explicit host focus', async () => { - const runtime = { - getRuntimeId: () => 'runtime-1', - focusTerminal: vi.fn().mockResolvedValue({ - handle: 'term-1', - tabId: 'tab-1', - worktreeId: 'wt-1' - }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - await dispatcher.dispatchStreaming(request({ terminal: 'term-1' }), () => {}, { - clientKind: 'mobile', - pairedDeviceId: 'device-a' - }) - await dispatcher.dispatchStreaming( - request({ terminal: 'term-1', navigation: 'host' }), - () => {}, - { clientKind: 'runtime', pairedDeviceId: 'device-b' } - ) - await dispatcher.dispatchStreaming(request({ terminal: 'term-1' }), () => {}, { - clientKind: 'runtime', - pairedDeviceId: 'device-b' - }) - await dispatcher.dispatch(request({ terminal: 'term-1' })) - - expect(runtime.focusTerminal).toHaveBeenNthCalledWith(1, 'term-1', { - navigateHost: false - }) - expect(runtime.focusTerminal).toHaveBeenNthCalledWith(2, 'term-1', { - navigateHost: true - }) - expect(runtime.focusTerminal).toHaveBeenNthCalledWith(3, 'term-1', { - navigateHost: false - }) - expect(runtime.focusTerminal).toHaveBeenNthCalledWith(4, 'term-1', { - navigateHost: true - }) - }) - - it('rejects client fanout targets that terminal focus cannot honor', async () => { - const runtime = { - getRuntimeId: () => 'runtime-1', - focusTerminal: vi.fn() - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch( - request({ terminal: 'term-1', navigation: 'clients' }) - ) - - expect(response).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) - expect(runtime.focusTerminal).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/rpc/methods/updater.test.ts b/src/main/runtime/rpc/methods/updater.test.ts deleted file mode 100644 index da95d36c6bd..00000000000 --- a/src/main/runtime/rpc/methods/updater.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { eraseRpcMethods, type RpcMethodDeclaration } from '../core' -import { configureRemoteServerUpdater } from '../../remote-server-updater' -import { STATUS_METHODS } from './status' -import { UPDATER_METHODS } from './updater' - -const snapshot = { - appVersion: '1.5.0', - runtimeId: 'runtime-rpc', - support: { installMode: 'interactive', automatic: true, reason: 'available' }, - status: { state: 'available', version: '1.5.1', changelog: null } -} as const - -function handler(methods: readonly RpcMethodDeclaration[], name: string) { - const method = eraseRpcMethods(methods).find((candidate) => candidate.name === name) - if (!method) { - throw new Error(`Missing method ${name}`) - } - return method.handler -} - -describe('runtime updater RPC methods', () => { - const getSnapshot = vi.fn(() => snapshot) - const check = vi.fn(() => snapshot) - const download = vi.fn(() => snapshot) - const install = vi.fn(() => ({ - accepted: true as const, - fromVersion: '1.5.0', - targetVersion: '1.5.1', - runtimeId: 'runtime-rpc' - })) - const runtime = { - getRuntimeId: () => 'runtime-rpc', - machineNameReady: async () => undefined, - getStatus: () => ({ runtimeId: 'runtime-rpc', liveTabCount: 2, liveLeafCount: 3 }) - } - - beforeEach(() => { - vi.clearAllMocks() - configureRemoteServerUpdater({ getSnapshot, check, download, install }) - }) - - it('exposes status and each update transition', async () => { - const context = { runtime } as never - expect(await handler(UPDATER_METHODS, 'updater.getStatus')(undefined, context)).toBe(snapshot) - expect( - await handler(UPDATER_METHODS, 'updater.check')( - { includePrerelease: false, includePerfPrerelease: true }, - context - ) - ).toBe(snapshot) - expect(await handler(UPDATER_METHODS, 'updater.download')(undefined, context)).toBe(snapshot) - expect(await handler(UPDATER_METHODS, 'updater.install')(undefined, context)).toMatchObject({ - accepted: true, - runtimeId: 'runtime-rpc' - }) - expect(check).toHaveBeenCalledWith('runtime-rpc', { - includePrerelease: false, - includePerfPrerelease: true - }) - }) - - it('enriches status.get without changing the runtime status source', async () => { - const result = await handler(STATUS_METHODS, 'status.get')(undefined, { runtime } as never) - expect(result).toEqual({ - runtimeId: 'runtime-rpc', - liveTabCount: 2, - liveLeafCount: 3, - appVersion: '1.5.0', - remoteUpdateSupport: snapshot.support - }) - }) -}) diff --git a/src/main/runtime/rpc/terminal-subscribe-lease-only.test.ts b/src/main/runtime/rpc/terminal-subscribe-lease-only.test.ts deleted file mode 100644 index 3a027ae516b..00000000000 --- a/src/main/runtime/rpc/terminal-subscribe-lease-only.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import './unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcRequest } from './core' -import { RpcDispatcher } from './dispatcher' -import { TERMINAL_METHODS } from './methods/terminal' -import { createSubscriptionRegistryDouble } from './subscription-registry-test-double' - -const request: RpcRequest = { - id: 'req-1', - authToken: 'tok', - method: 'terminal.subscribe', - params: { - terminal: 'terminal-1', - client: { id: 'phone-1', type: 'mobile' }, - viewport: { cols: 40, rows: 20 }, - capabilities: { terminalBinaryStream: 1, mobileInputLeaseOnly: 1 } - } -} - -describe('terminal lease-only subscription', () => { - it('keeps mobile input ownership without viewport resize or output delivery', async () => { - const messages: string[] = [] - const registry = createSubscriptionRegistryDouble() - const unsubscribeExit = vi.fn() - const runtime = { - getRuntimeId: () => 'test-runtime', - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - handleMobileSubscribe: vi.fn().mockResolvedValue(true), - handleMobileUnsubscribe: vi.fn(), - subscribeToTerminalData: vi.fn(), - registerRemoteTerminalViewSubscriber: vi.fn(), - readTerminal: vi.fn(), - serializeTerminalBuffer: vi.fn(), - subscribeToTerminalResize: vi.fn(), - subscribeToFitOverrideChanges: vi.fn(), - registerSubscriptionCleanup: vi.fn(registry.registerSubscriptionCleanup), - registerOwnedSubscriptionCleanup: vi.fn(registry.registerOwnedSubscriptionCleanup), - cleanupSubscription: vi.fn(registry.cleanupSubscription), - subscribeToPtyExit: vi.fn(() => unsubscribeExit) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const dispatchPromise = dispatcher.dispatchStreaming( - request, - (message) => messages.push(message), - { - connectionId: 'conn-phone', - sendBinary: vi.fn(), - registerBinaryStreamHandler: vi.fn(() => vi.fn()) - } - ) - - await vi.waitFor(() => - expect(messages.some((message) => JSON.parse(message).result?.type === 'subscribed')).toBe( - true - ) - ) - expect(runtime.handleMobileSubscribe).toHaveBeenCalledWith('pty-1', 'phone-1', undefined) - expect(runtime.subscribeToTerminalData).not.toHaveBeenCalled() - expect(runtime.registerRemoteTerminalViewSubscriber).not.toHaveBeenCalled() - expect(runtime.readTerminal).not.toHaveBeenCalled() - expect(runtime.serializeTerminalBuffer).not.toHaveBeenCalled() - expect(runtime.subscribeToTerminalResize).not.toHaveBeenCalled() - expect(runtime.subscribeToFitOverrideChanges).not.toHaveBeenCalled() - - runtime.cleanupSubscription('terminal-1:phone-1') - await dispatchPromise - expect(unsubscribeExit).toHaveBeenCalledOnce() - expect(runtime.handleMobileUnsubscribe).toHaveBeenCalledWith('pty-1', 'phone-1') - }) -}) diff --git a/src/main/runtime/runtime-git-branch-compare-admission.test.ts b/src/main/runtime/runtime-git-branch-compare-admission.test.ts deleted file mode 100644 index 6420dc0e3ea..00000000000 --- a/src/main/runtime/runtime-git-branch-compare-admission.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { RuntimeGitCommandHost, RuntimeGitTarget } from './runtime-git-command-target' - -const mocks = vi.hoisted(() => ({ - getBranchCompare: vi.fn() -})) - -vi.mock('../git/status', () => ({ - getBranchCompare: mocks.getBranchCompare, - getBranchDiff: vi.fn(), - getCommitCompare: vi.fn(), - getCommitDiff: vi.fn(), - getDiff: vi.fn() -})) -vi.mock('../git/repo', () => ({ getRemoteCommitUrl: vi.fn(), getRemoteFileUrl: vi.fn() })) -vi.mock('../git/runner', () => ({ awaitWindowsHostGitEnvironmentReady: vi.fn() })) - -import { SshHostNotServedError } from '../providers/ssh-host-not-served-error' -import { RuntimeGitDiffCommands } from './runtime-git-diff-commands' - -function makeCommands(overrides: Partial = {}): RuntimeGitDiffCommands { - const target = { - worktree: { - id: 'wt-1', - repoId: 'repo-1', - path: 'C:\\repo', - git: { - path: 'C:\\repo', - branch: 'feature', - isBare: false, - isMainWorktree: false, - head: 'a'.repeat(40) - } - }, - executionHostId: 'local', - localGitOptions: { wslDistro: 'Ubuntu' }, - ...overrides - } as RuntimeGitTarget - const host = { - resolveRuntimeGitTarget: async () => target, - getRuntimeSettings: () => ({}) - } as unknown as RuntimeGitCommandHost - return new RuntimeGitDiffCommands(host) -} - -describe('RuntimeGitDiffCommands branch-compare admission', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.getBranchCompare.mockResolvedValue({ summary: {}, entries: [] }) - }) - - it('preserves a background tier with WSL routing and defaults legacy callers to interactive', async () => { - const commands = makeCommands() - - await commands.getRuntimeGitBranchCompare('id:wt-1', 'origin/main', 'background') - await commands.getRuntimeGitBranchCompare('id:wt-1', 'origin/main') - - expect(mocks.getBranchCompare).toHaveBeenNthCalledWith(1, 'C:\\repo', 'origin/main', { - wslDistro: 'Ubuntu', - admissionTier: 'background' - }) - expect(mocks.getBranchCompare).toHaveBeenNthCalledWith(2, 'C:\\repo', 'origin/main', { - wslDistro: 'Ubuntu', - admissionTier: 'interactive' - }) - }) - - it('refuses an SSH execution host without running git here', async () => { - const commands = makeCommands({ executionHostId: 'ssh:conn-1' }) - - await expect( - commands.getRuntimeGitBranchCompare('id:wt-1', 'origin/main', 'background') - ).rejects.toThrow(SshHostNotServedError) - expect(mocks.getBranchCompare).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/runtime-project-group-controller-folder-delete.test.ts b/src/main/runtime/runtime-project-group-controller-folder-delete.test.ts deleted file mode 100644 index 24c844a5f01..00000000000 --- a/src/main/runtime/runtime-project-group-controller-folder-delete.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { RuntimeProjectGroupController } from './runtime-project-group-controller' -import type { FolderWorkspace } from '../../shared/folder-workspace-types' - -const workspace = { - id: 'ws-1', - projectGroupId: 'group-1', - folderPath: '/tmp/ws' -} as FolderWorkspace - -function createController( - resolveFolderConnectionId: (workspace: FolderWorkspace) => string | null -) { - const removeFolderWorkspace = vi.fn(() => true) - const teardownFolderWorkspacePtys = vi.fn(async () => undefined) - const cleanupRemovedFolderWorkspaceState = vi.fn() - const notifyReposChanged = vi.fn() - const emitWorktreeLifecycle = vi.fn() - const controller = new RuntimeProjectGroupController({ - getStore: () => ({ getFolderWorkspaces: () => [workspace], removeFolderWorkspace }) as never, - resolveRepo: async () => { - throw new Error('unused') - }, - notifyReposChanged, - resolveFolderConnectionId, - teardownFolderWorkspacePtys, - cleanupRemovedFolderWorkspaceState, - emitWorktreeLifecycle - }) - return { - emitWorktreeLifecycle, - controller, - removeFolderWorkspace, - teardownFolderWorkspacePtys, - cleanupRemovedFolderWorkspaceState, - notifyReposChanged - } -} - -describe('RuntimeProjectGroupController.deleteFolderWorkspace', () => { - it('tears down PTYs and runtime state before removing the catalog row', async () => { - const deps = createController(() => 'ssh-1') - - await expect(deps.controller.deleteFolderWorkspace('ws-1')).resolves.toEqual({ deleted: true }) - - expect(deps.teardownFolderWorkspacePtys).toHaveBeenCalledWith('folder:ws-1', 'ssh-1') - expect(deps.cleanupRemovedFolderWorkspaceState).toHaveBeenCalledWith('folder:ws-1') - expect(deps.teardownFolderWorkspacePtys.mock.invocationCallOrder[0]).toBeLessThan( - deps.removeFolderWorkspace.mock.invocationCallOrder[0]! - ) - expect(deps.notifyReposChanged).toHaveBeenCalledTimes(1) - expect(deps.emitWorktreeLifecycle).toHaveBeenCalledWith({ - kind: 'removed', - worktreeId: 'folder:ws-1', - path: '/tmp/ws' - }) - }) - - it('still deletes when the folder host is ambiguous, skipping only the PTY sweep', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const deps = createController(() => { - throw new Error('folder_workspace_connection_ambiguous') - }) - - await expect(deps.controller.deleteFolderWorkspace('ws-1')).resolves.toEqual({ deleted: true }) - - expect(deps.teardownFolderWorkspacePtys).not.toHaveBeenCalled() - expect(deps.cleanupRemovedFolderWorkspaceState).toHaveBeenCalledWith('folder:ws-1') - expect(deps.removeFolderWorkspace).toHaveBeenCalledWith('ws-1') - expect(deps.emitWorktreeLifecycle).toHaveBeenCalledWith( - expect.objectContaining({ kind: 'removed', worktreeId: 'folder:ws-1' }) - ) - warn.mockRestore() - }) -}) diff --git a/src/main/runtime/runtime-session-search-settings.test.ts b/src/main/runtime/runtime-session-search-settings.test.ts deleted file mode 100644 index 3dda68949ab..00000000000 --- a/src/main/runtime/runtime-session-search-settings.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - RuntimeSessionSearchSettingsController, - type SessionSearchSettingsStore -} from './runtime-session-search-settings' -import type { GlobalSettings } from '../../shared/global-settings-types' - -type Settings = ReturnType - -function storeWith(aiVaultSearch: GlobalSettings['aiVaultSearch'] | undefined) { - let settings: Settings = { - workspaceDir: '/workspaces', - nestWorkspaces: false, - refreshLocalBaseRefOnWorktreeCreate: false, - branchPrefix: 'none', - branchPrefixCustom: '', - ...(aiVaultSearch ? { aiVaultSearch } : {}) - } - const updateSettings = vi.fn((updates: Partial) => { - settings = { ...settings, ...updates } - }) - const store: SessionSearchSettingsStore = { - getSettings: () => settings, - updateSettings - } - return { store, updateSettings, read: () => settings } -} - -describe('runtime session search consent', () => { - it('writes the whole policy and hands the host before/after exactly once', async () => { - const { store, updateSettings, read } = storeWith({ enabled: false, historyDays: 30 }) - const apply = vi.fn() - await new RuntimeSessionSearchSettingsController(store, apply).setEnabled(true) - - expect(updateSettings).toHaveBeenCalledExactlyOnceWith( - { aiVaultSearch: { enabled: true, historyDays: 30 } }, - { notifyListeners: true } - ) - // Retention must ride along untouched; a partial write would reset it to "all history". - expect(read().aiVaultSearch).toEqual({ enabled: true, historyDays: 30 }) - expect(apply).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ aiVaultSearch: { enabled: false, historyDays: 30 } }), - expect.objectContaining({ aiVaultSearch: { enabled: true, historyDays: 30 } }) - ) - }) - - it('normalizes an absent or malformed stored policy instead of writing it back', async () => { - const { store, updateSettings } = storeWith(undefined) - await new RuntimeSessionSearchSettingsController(store, null).setEnabled(true) - - expect(updateSettings).toHaveBeenCalledExactlyOnceWith( - { aiVaultSearch: { enabled: true, historyDays: null } }, - { notifyListeners: true } - ) - }) - - it('hands the host an unchanged pair when the value did not move', async () => { - const { store, updateSettings } = storeWith({ enabled: true, historyDays: null }) - const apply = vi.fn() - await new RuntimeSessionSearchSettingsController(store, apply).setEnabled(true) - - // The write still happens; the host hook is what refuses to restart a live index. - expect(updateSettings).toHaveBeenCalledOnce() - const [before, after] = apply.mock.calls[0] ?? [] - expect(before?.aiVaultSearch).toEqual(after?.aiVaultSearch) - }) - - it('refuses on a host with no settings store rather than reporting success', async () => { - await expect( - new RuntimeSessionSearchSettingsController(null, vi.fn()).setEnabled(true) - ).rejects.toThrow('runtime_unavailable') - }) -}) diff --git a/src/main/runtime/runtime-workspace-view-change-events.test.ts b/src/main/runtime/runtime-workspace-view-change-events.test.ts deleted file mode 100644 index ad03fff7335..00000000000 --- a/src/main/runtime/runtime-workspace-view-change-events.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { getDefaultSettings, getDefaultUIState } from '../../shared/constants' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { PersistedUIState } from '../../shared/persisted-ui-state-types' -import { publishWorkspaceViewChanges } from './runtime-workspace-view-change-events' - -function fakeStore() { - let ui: PersistedUIState = getDefaultUIState() - const listeners: ((ui: PersistedUIState) => void)[] = [] - const settingsListeners: (( - updates: Partial, - settings: GlobalSettings - ) => void)[] = [] - return { - getUI: () => ui, - onUIChanged: (listener: (ui: PersistedUIState) => void) => { - listeners.push(listener) - return () => {} - }, - onSettingsChanged: ( - listener: (updates: Partial, settings: GlobalSettings) => void - ) => { - settingsListeners.push(listener) - return () => {} - }, - updateSettings(updates: Partial) { - for (const listener of settingsListeners) { - listener(updates, { ...getDefaultSettings('/home/test'), ...updates }) - } - }, - update(updates: Partial) { - ui = { ...ui, ...updates } - for (const listener of listeners) { - listener(ui) - } - } - } -} - -describe('publishWorkspaceViewChanges', () => { - it('announces a Workspace options change once, and ignores unrelated UI edits', () => { - const store = fakeStore() - const emit = vi.fn() - publishWorkspaceViewChanges(store, emit) - - store.update({ sidebarWidth: 300 }) - expect(emit).not.toHaveBeenCalled() - - store.update({ hideWorkspacesFromOtherDevices: true }) - store.update({ hideWorkspacesFromOtherDevices: true }) - store.update({ filterRepoIds: ['repo-1'] }) - expect(emit.mock.calls).toEqual([ - [{ type: 'workspaceViewChanged' }], - [{ type: 'workspaceViewChanged' }] - ]) - }) - - it('announces a change to the card layout, card style or pinned placement, and nothing else', () => { - const store = fakeStore() - const emit = vi.fn() - publishWorkspaceViewChanges(store, emit) - - store.updateSettings({ terminalCopyTrimsGutter: false }) - expect(emit).not.toHaveBeenCalled() - store.updateSettings({ compactWorktreeCards: true }) - store.updateSettings({ experimentalNewWorktreeCardStyle: true }) - store.updateSettings({ showPinnedWorktreesInGroups: true }) - expect(emit).toHaveBeenCalledTimes(3) - }) -}) diff --git a/src/main/serve-update-handoff.app-environment.test.ts b/src/main/serve-update-handoff.app-environment.test.ts deleted file mode 100644 index 89204e4bae5..00000000000 --- a/src/main/serve-update-handoff.app-environment.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../config/scripts/vitest-host-ports-setup' -import { - SERVE_UPDATE_HANDOFF_PATH_ENV, - getServeUpdateHandoffPath -} from '../shared/serve-update-handoff' - -// Keep the real path resolver: mocking persistence hides access before app-environment setup. -vi.mock('electron', () => ({ app: { getVersion: () => '1.0.51', quit: vi.fn() } })) - -// Test setup installs a fake environment, and there is no uninstall API. -const APP_ENVIRONMENT_SLOT = Symbol.for('orca.host.appEnvironment') - -describe('serve supervisor disconnect quit', () => { - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')! - let installedEnvironment: unknown - let installedHandoffPath: string | undefined - let userDataDir: string - - beforeEach(() => { - userDataDir = mkdtempSync(join(tmpdir(), 'orca-serve-handoff-env-')) - installedHandoffPath = process.env[SERVE_UPDATE_HANDOFF_PATH_ENV] - const slot = globalThis as Record - installedEnvironment = slot[APP_ENVIRONMENT_SLOT] - delete slot[APP_ENVIRONMENT_SLOT] - // The supervisor check short-circuits on other platforms. - Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' }) - process.env[SERVE_UPDATE_HANDOFF_PATH_ENV] = getServeUpdateHandoffPath(userDataDir) - }) - - afterEach(() => { - const slot = globalThis as Record - if (installedEnvironment === undefined) { - delete slot[APP_ENVIRONMENT_SLOT] - } else { - slot[APP_ENVIRONMENT_SLOT] = installedEnvironment - } - Object.defineProperty(process, 'platform', originalPlatform) - if (installedHandoffPath === undefined) { - delete process.env[SERVE_UPDATE_HANDOFF_PATH_ENV] - } else { - process.env[SERVE_UPDATE_HANDOFF_PATH_ENV] = installedHandoffPath - } - rmSync(userDataDir, { recursive: true, force: true }) - vi.resetModules() - }) - - it('resolves a real user data path, so it cannot run before the app environment is installed', async () => { - const { installServeSupervisorDisconnectQuit } = await import('./serve-update-handoff') - - expect(() => installServeSupervisorDisconnectQuit(true)).toThrow( - /AppEnvironment not initialized/ - ) - }) - - it('installs the disconnect quit once the app environment is available', async () => { - installFakeAppEnvironment({ getPath: () => userDataDir }) - const { installServeSupervisorDisconnectQuit } = await import('./serve-update-handoff') - const listeners: (() => void)[] = [] - const parent = { - once: (_event: 'disconnect', listener: () => void) => listeners.push(listener), - off: (_event: 'disconnect', listener: () => void) => - listeners.splice(listeners.indexOf(listener), 1) - } - - const dispose = installServeSupervisorDisconnectQuit(true, parent) - - expect(listeners).toHaveLength(1) - dispose() - expect(listeners).toHaveLength(0) - }) -}) diff --git a/src/main/ssh/config/ssh-config-resolver.test.ts b/src/main/ssh/config/ssh-config-resolver.test.ts deleted file mode 100644 index c9a59c5a434..00000000000 --- a/src/main/ssh/config/ssh-config-resolver.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { resolveWithSshG } from './ssh-g-config-resolution' -import { runProcess } from '@orca/process-host' - -vi.mock('os', () => ({ - homedir: () => '/home/testuser' -})) - -// Mock process-host: it owns hidden windows, timeout and argv encoding; this suite verifies routing. -vi.mock('@orca/process-host', () => ({ - runProcess: vi.fn() -})) - -const ok = (stdout: string) => ({ code: 0, signal: null, stdout, stderr: '', timedOut: false }) - -describe('resolveWithSshG', () => { - beforeEach(() => { - vi.mocked(runProcess).mockReset() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('returns parsed config on success', async () => { - vi.mocked(runProcess).mockResolvedValue(ok('hostname 10.0.0.1\nuser admin\nport 22')) - - const result = await resolveWithSshG('myhost') - expect(result).toBeDefined() - expect(result!.hostname).toBe('10.0.0.1') - expect(result!.user).toBe('admin') - }) - - it('calls ssh -G with the given host under a bounded timeout', async () => { - vi.mocked(runProcess).mockResolvedValue(ok('hostname example.com\nport 22')) - - await resolveWithSshG('testserver') - expect(runProcess).toHaveBeenCalledWith({ - program: 'ssh', - args: ['-G', '--', 'testserver'], - timeoutMs: 5000 - }) - }) - - it('returns null when ssh -G fails', async () => { - vi.mocked(runProcess).mockResolvedValue({ - code: 255, - signal: null, - stdout: '', - stderr: 'ssh not found', - timedOut: false - }) - - expect(await resolveWithSshG('myhost')).toBeNull() - }) - - it('returns null when ssh -G could not be started', async () => { - vi.mocked(runProcess).mockRejectedValue(new Error('ENOENT')) - - expect(await resolveWithSshG('myhost')).toBeNull() - }) - - it('returns null when ssh -G never reports completion', async () => { - // process-host returns timeout data; no fake timer is needed. - vi.mocked(runProcess).mockResolvedValue({ - code: null, - signal: 'SIGTERM', - stdout: '', - stderr: '', - timedOut: true - }) - - expect(await resolveWithSshG('stuck-host')).toBeNull() - }) -}) diff --git a/src/main/window/clipboard-text-write-verify.test.ts b/src/main/window/clipboard-text-write-verify.test.ts deleted file mode 100644 index 025a8e7a929..00000000000 --- a/src/main/window/clipboard-text-write-verify.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { clipboardReadTextMock, clipboardWriteTextMock } = vi.hoisted(() => ({ - clipboardReadTextMock: vi.fn(), - clipboardWriteTextMock: vi.fn() -})) - -vi.mock('electron', () => ({ - clipboard: { - readText: clipboardReadTextMock, - writeText: clipboardWriteTextMock - } -})) - -import { - CLIPBOARD_WRITE_VERIFICATION_FAILED_ERROR, - writeClipboardTextAndVerify -} from './clipboard-text-write-verify' - -describe('writeClipboardTextAndVerify', () => { - beforeEach(() => { - clipboardReadTextMock.mockReset() - clipboardWriteTextMock.mockReset() - }) - - it('writes then accepts a matching standard clipboard read-back', () => { - clipboardWriteTextMock.mockImplementation((text: string) => { - clipboardReadTextMock.mockReturnValue(text) - }) - - expect(() => writeClipboardTextAndVerify('tui answer')).not.toThrow() - expect(clipboardWriteTextMock).toHaveBeenCalledWith('tui answer') - expect(clipboardReadTextMock).toHaveBeenCalledWith() - }) - - it('accepts multi-line TUI content when read-back is identity-preserving', () => { - const multiLine = 'line1\nline2\n indented\n' - clipboardWriteTextMock.mockImplementation((text: string) => { - clipboardReadTextMock.mockReturnValue(text) - }) - - expect(() => writeClipboardTextAndVerify(multiLine)).not.toThrow() - expect(clipboardWriteTextMock).toHaveBeenCalledWith(multiLine) - expect(clipboardReadTextMock).toHaveBeenCalledWith() - }) - - it('accepts CRLF multi-line content only when read-back matches exactly', () => { - const crlf = 'line1\r\nline2\r\n' - clipboardWriteTextMock.mockImplementation((text: string) => { - clipboardReadTextMock.mockReturnValue(text) - }) - - expect(() => writeClipboardTextAndVerify(crlf)).not.toThrow() - expect(clipboardWriteTextMock).toHaveBeenCalledWith(crlf) - }) - - it('rejects when multi-line read-back differs only by line endings', () => { - clipboardWriteTextMock.mockImplementation(() => { - // Line-ending normalization must fail strict verification rather than claim a lossless paste. - clipboardReadTextMock.mockReturnValue('line1\r\nline2') - }) - - expect(() => writeClipboardTextAndVerify('line1\nline2')).toThrow( - CLIPBOARD_WRITE_VERIFICATION_FAILED_ERROR - ) - }) - - it('rejects standard text writes when the clipboard read-back does not match', () => { - clipboardReadTextMock.mockReturnValue('old clipboard') - - expect(() => writeClipboardTextAndVerify('tui answer')).toThrow( - CLIPBOARD_WRITE_VERIFICATION_FAILED_ERROR - ) - expect(clipboardWriteTextMock).toHaveBeenCalledWith('tui answer') - }) -}) diff --git a/src/main/window/main-window-updater-headless-serve.test.ts b/src/main/window/main-window-updater-headless-serve.test.ts deleted file mode 100644 index 2ea9014d397..00000000000 --- a/src/main/window/main-window-updater-headless-serve.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import type { BrowserWindow } from 'electron' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../persistence' -import type { UpdaterSetupOptions } from '../updater' - -const { setupMock } = vi.hoisted(() => ({ - setupMock: vi.fn<(window: BrowserWindow | null, options?: UpdaterSetupOptions) => void>() -})) - -vi.mock('electron', () => ({ app: {}, ipcMain: {} })) -vi.mock('../updater', () => ({ setupAutoUpdater: setupMock })) -vi.mock('../updater/electron-updater-proxy-session', () => ({ - applyProxyToElectronUpdaterSession: vi.fn() -})) -vi.mock('../ipc/ui', () => ({ isTrustedUIRenderer: () => true })) -vi.mock('../startup/startup-diagnostics', () => ({ logStartupMilestone: vi.fn() })) - -import { setupHeadlessServeAutoUpdater } from './main-window-updater' - -function createStore() { - const store = { - getSettings: vi.fn(() => ({})), - getUI: vi.fn(() => ({ lastUpdateCheckAt: 5 })), - updateUI: vi.fn(), - flushPendingAsync: vi.fn().mockResolvedValue(undefined) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: setup only reads getSettings/getUI/updateUI/flushPendingAsync, all provided above. - return { store, persistence: store as unknown as Store } -} - -describe('setupHeadlessServeAutoUpdater', () => { - afterEach(() => { - setupMock.mockReset() - }) - - it('initializes the updater without a window, in the serve install mode, after readiness', async () => { - const { store, persistence } = createStore() - const beforeQuit = vi.fn() - setupHeadlessServeAutoUpdater(persistence, { - onBeforeUpdateQuit: beforeQuit, - onBeforeUpdateQuitFailure: 'abort', - updateInstallMode: 'supervised-headless-serve' - }) - expect(setupMock).not.toHaveBeenCalled() - await new Promise((resolve) => setImmediate(resolve)) - - expect(setupMock).toHaveBeenCalledOnce() - const [window, options] = setupMock.mock.calls[0] ?? [] - expect(window).toBeNull() - expect(options).toMatchObject({ - installMode: 'supervised-headless-serve', - onBeforeQuitFailure: 'abort' - }) - expect(options?.getLastUpdateCheckAt?.()).toBe(5) - await options?.onBeforeQuit?.() - expect(beforeQuit).toHaveBeenCalledOnce() - expect(store.flushPendingAsync).toHaveBeenCalledOnce() - }) - - it('never throws through serve startup when the updater cannot load', async () => { - const { persistence } = createStore() - setupMock.mockImplementation(() => { - throw new Error('electron-updater missing') - }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - setupHeadlessServeAutoUpdater(persistence, {}) - await new Promise((resolve) => setImmediate(resolve)) - expect(warn).toHaveBeenCalled() - warn.mockRestore() - }) -}) diff --git a/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-notebook-link.test.ts b/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-notebook-link.test.ts deleted file mode 100644 index 3b8aeced896..00000000000 --- a/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-notebook-link.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ statUserOpenedPath: vi.fn(), openFile: vi.fn() })) - -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null })) -vi.mock('@/lib/user-opened-local-path', () => ({ statUserOpenedPath: mocks.statUserOpenedPath })) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ - settings: {}, - getKnownWorktreeById: (id: string) => (id === 'wt-1' ? { id, path: '/repo' } : undefined), - setActiveTabType: vi.fn(), - ensureWorktreeRootGroup: () => 'group-1', - openFile: mocks.openFile - }) - } -})) - -import { navigateBrowserPageToUrl } from './navigate-browser-page-url' - -function ref(current: T): { current: T } { - return { current } -} - -function openNotebookUrl(url: string): void { - navigateBrowserPageToUrl({ - url, - browserTabId: 'tab-1', - worktreeId: 'wt-1', - activeLoadFailureRef: ref(null), - lastKnownWebviewUrlRef: ref(null), - recoveryNavigationValidationRef: ref(null), - webviewRef: ref(null), - onSetUrlRef: ref(vi.fn()), - onUpdatePageStateRef: ref(vi.fn()), - setAddressBarValue: vi.fn(), - setResourceNotice: vi.fn(), - focusWebviewNow: () => true - }) -} - -describe('opening a file:// notebook from the browser', () => { - beforeEach(() => { - mocks.statUserOpenedPath.mockReset() - mocks.openFile.mockReset() - }) - - it('opens a project link that leads out of the project by its absolute path', async () => { - mocks.statUserOpenedPath.mockResolvedValue({ isDirectory: false, escapesWorktree: true }) - - openNotebookUrl('file:///repo/notebooks-link/analysis.ipynb') - await vi.waitFor(() => expect(mocks.openFile).toHaveBeenCalledTimes(1)) - - expect(mocks.openFile).toHaveBeenCalledWith( - expect.objectContaining({ - filePath: '/repo/notebooks-link/analysis.ipynb', - relativePath: '/repo/notebooks-link/analysis.ipynb' - }), - expect.anything() - ) - }) - - it('keeps an ordinary project notebook project-relative', async () => { - mocks.statUserOpenedPath.mockResolvedValue({ isDirectory: false, escapesWorktree: false }) - - openNotebookUrl('file:///repo/analysis.ipynb') - await vi.waitFor(() => expect(mocks.openFile).toHaveBeenCalledTimes(1)) - - expect(mocks.openFile).toHaveBeenCalledWith( - expect.objectContaining({ filePath: '/repo/analysis.ipynb', relativePath: 'analysis.ipynb' }), - expect.anything() - ) - }) -}) diff --git a/src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.test.tsx b/src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.test.tsx deleted file mode 100644 index 4155d95c37b..00000000000 --- a/src/renderer/src/components/dashboard-popout/DashboardPopoutRoot.test.tsx +++ /dev/null @@ -1,71 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { APP_MENU_PASTE_EVENT } from '@/lib/app-menu-paste' -import { APP_MENU_SELECTION_ACTION_EVENT } from '@/lib/app-menu-selection-actions' - -const useAgentDashboardTelemetry = vi.hoisted(() => vi.fn()) -vi.mock('./use-agent-dashboard-telemetry', () => ({ useAgentDashboardTelemetry })) -vi.mock('./AgentKanbanBoard', () => ({ AgentKanbanBoard: () => null })) -vi.mock('./useDashboardSnapshot', () => ({ useDashboardSnapshot: () => null })) - -import { DashboardPopoutRoot } from './DashboardPopoutRoot' - -describe('DashboardPopoutRoot', () => { - const performNativePaste = vi.fn() - const performNativeSelectionAction = vi.fn() - let emitAppMenuPaste: (() => void) | null = null - let emitAppMenuSelectionAction: ((action: 'copy' | 'select-all') => void) | null = null - - beforeEach(() => { - vi.clearAllMocks() - emitAppMenuPaste = null - emitAppMenuSelectionAction = null - Object.assign(window, { - api: { - ui: { - readClipboardText: vi.fn(async () => ''), - performNativePaste, - performNativeSelectionAction, - onAppMenuPaste: (listener: () => void) => { - emitAppMenuPaste = listener - return vi.fn() - }, - onEditableContextPaste: () => vi.fn(), - onAppMenuSelectionAction: (listener: (action: 'copy' | 'select-all') => void) => { - emitAppMenuSelectionAction = listener - return vi.fn() - } - } - } - }) - }) - - afterEach(() => { - cleanup() - }) - - // Without an App shell, these hooks alone translate menu IPC for preview ownership listeners. - it('translates app-menu clipboard IPC into renderer ownership events', async () => { - const onPaste = vi.fn() - const onSelectionAction = vi.fn() - window.addEventListener(APP_MENU_PASTE_EVENT, onPaste) - window.addEventListener(APP_MENU_SELECTION_ACTION_EVENT, onSelectionAction) - render() - expect(useAgentDashboardTelemetry).toHaveBeenCalledWith('popout') - expect(emitAppMenuPaste).not.toBeNull() - expect(emitAppMenuSelectionAction).not.toBeNull() - - await act(async () => emitAppMenuPaste!()) - act(() => emitAppMenuSelectionAction!('select-all')) - window.removeEventListener(APP_MENU_PASTE_EVENT, onPaste) - window.removeEventListener(APP_MENU_SELECTION_ACTION_EVENT, onSelectionAction) - - expect(onPaste).toHaveBeenCalledOnce() - expect(onSelectionAction).toHaveBeenCalledOnce() - // Unclaimed here (no preview mounted), so both still reach the native path. - expect(performNativePaste).toHaveBeenCalledOnce() - expect(performNativeSelectionAction).toHaveBeenCalledWith('select-all') - }) -}) diff --git a/src/renderer/src/components/editor/editor-dropped-file-open.escaping-link.test.ts b/src/renderer/src/components/editor/editor-dropped-file-open.escaping-link.test.ts deleted file mode 100644 index 6f04f5e23ab..00000000000 --- a/src/renderer/src/components/editor/editor-dropped-file-open.escaping-link.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - statUserOpenedPath: vi.fn(), - openFile: vi.fn(), - setActiveTabType: vi.fn() -})) - -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null })) -vi.mock('@/lib/ssh-mutation-expectation', () => ({ - captureWorktreeSshMutationExpectation: () => ({}) -})) -vi.mock('@/lib/file-owner-runtime-target', () => { - const getRuntimeTargetForFileOwner = ( - _state: unknown, - _worktreeId: string | null | undefined, - _runtimeEnvironmentId: string | null | undefined - ) => ({ kind: 'local' as const }) - return { - FILE_OWNER_UNRESOLVED_MESSAGE: 'unresolved', - getRuntimeTargetForFileOwner, - requireRuntimeTargetForFileOwner: getRuntimeTargetForFileOwner, - getRuntimeTargetForWorktreeOwner: (state: unknown, worktreeId: string | null | undefined) => - getRuntimeTargetForFileOwner(state, worktreeId, undefined) - } -}) -vi.mock('@/lib/user-opened-local-path', () => ({ statUserOpenedPath: mocks.statUserOpenedPath })) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ - settings: {}, - activeWorktreeId: 'wt-1', - getKnownWorktreeById: () => ({ id: 'wt-1', path: '/repo' }), - setActiveTabType: mocks.setActiveTabType, - openFile: mocks.openFile - }) - } -})) - -import { captureEditorFileDropOpen } from './editor-dropped-file-open' - -beforeEach(() => { - mocks.statUserOpenedPath.mockReset() - mocks.openFile.mockReset() -}) - -async function dropOnTabStrip(path: string): Promise { - await captureEditorFileDropOpen({ worktreeId: 'wt-1' })([path]) - await vi.waitFor(() => expect(mocks.openFile).toHaveBeenCalledTimes(1)) -} - -describe('dropping a project file on the tab strip', () => { - it('opens a link that leads out of the project by its absolute path', async () => { - mocks.statUserOpenedPath.mockResolvedValue({ isDirectory: false, escapesWorktree: true }) - - await dropOnTabStrip('/repo/docs-link/secret.md') - - expect(mocks.openFile).toHaveBeenCalledWith( - expect.objectContaining({ - filePath: '/repo/docs-link/secret.md', - relativePath: '/repo/docs-link/secret.md' - }) - ) - }) - - it('keeps an ordinary project file project-relative', async () => { - mocks.statUserOpenedPath.mockResolvedValue({ isDirectory: false, escapesWorktree: false }) - - await dropOnTabStrip('/repo/docs/plain.md') - - expect(mocks.openFile).toHaveBeenCalledWith( - expect.objectContaining({ filePath: '/repo/docs/plain.md', relativePath: 'docs/plain.md' }) - ) - }) -}) diff --git a/src/renderer/src/components/editor/editor-save-grant.test.ts b/src/renderer/src/components/editor/editor-save-grant.test.ts deleted file mode 100644 index 591bd9d5ff8..00000000000 --- a/src/renderer/src/components/editor/editor-save-grant.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { OpenFile } from '@/store/slices/editor' -import type { RuntimeFileOperationArgs } from '@/runtime/runtime-file-client-types' - -const grantRestoredHostFile = vi.hoisted(() => vi.fn()) -vi.mock('./restored-host-file-grant', () => ({ grantRestoredHostFile })) - -import { editorSaveGrant } from './editor-save-disk-precondition' - -const PATH = '/private/tmp/handoff.md' -const hostContext: RuntimeFileOperationArgs = { - target: { kind: 'environment', environmentId: 'env-1' }, - worktreeId: 'wt-1', - worktreePath: '/srv/repo' -} - -function tab(overrides: Partial = {}): OpenFile { - return { - id: PATH, - filePath: PATH, - relativePath: PATH, - worktreeId: 'wt-1', - language: 'markdown', - isDirty: true, - mode: 'edit', - ...overrides - } -} - -describe('the grant an editor save writes through', () => { - // Why: grants are never persisted, so a restored dirty tab that never loaded must still save. - it('asks the host for a grant for a restored tab outside every workspace and keeps it', async () => { - grantRestoredHostFile.mockResolvedValue({ grantId: 'g-2', readOnly: false }) - const setTerminalArtifactGrant = vi.fn() - - const grant = await editorSaveGrant(tab(), hostContext, () => ({ setTerminalArtifactGrant })) - - expect(grant?.grantId).toBe('g-2') - expect(grantRestoredHostFile).toHaveBeenCalledWith(hostContext.target, 'wt-1', PATH, undefined) - expect(setTerminalArtifactGrant).toHaveBeenCalledWith(PATH, 'g-2') - }) - - it('leaves workspace files and this computer’s files to the ordinary save', async () => { - grantRestoredHostFile.mockClear() - const getState = () => ({ setTerminalArtifactGrant: vi.fn() }) - - // Why: synchronous, so an ordinary save gains no await before its pairing pin. - expect( - editorSaveGrant( - tab({ filePath: '/srv/repo/a.md', relativePath: '/srv/repo/a.md' }), - hostContext, - getState - ) - ).toBeUndefined() - expect( - editorSaveGrant(tab(), { ...hostContext, target: { kind: 'local' } }, getState) - ).toBeUndefined() - expect(grantRestoredHostFile).not.toHaveBeenCalled() - }) - - // Why: marking the tab read-only would drop its unsaved draft from the next session save. - it('refuses to save through a read-only restored grant without touching the tab', async () => { - grantRestoredHostFile.mockResolvedValue({ grantId: 'g-3', readOnly: true }) - const setTerminalArtifactGrant = vi.fn() - - await expect( - editorSaveGrant(tab(), hostContext, () => ({ setTerminalArtifactGrant })) - ).rejects.toThrow('read-only') - expect(setTerminalArtifactGrant).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/editor/pdf-document-loader.test.ts b/src/renderer/src/components/editor/pdf-document-loader.test.ts deleted file mode 100644 index c3bef44503c..00000000000 --- a/src/renderer/src/components/editor/pdf-document-loader.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -type PdfOptions = Record & { - range?: { requestDataRange: (begin: number, end: number) => void } -} - -const { getDocument } = vi.hoisted(() => ({ - getDocument: vi.fn((_options: PdfOptions) => ({ - promise: new Promise(() => {}), - destroy: vi.fn(async () => {}) - })) -})) -vi.mock('pdfjs-dist', () => ({ - getDocument, - PDFDataRangeTransport: class { - constructor(readonly length: number) {} - onDataRange(): void {} - } -})) - -import { createPdfDocumentLoader } from './pdf-document-loader' - -describe('PDF document loader sources', () => { - beforeEach(() => { - getDocument.mockClear() - }) - - it('reads a sized URL by range, and still decodes base64 for diffs and the web client', () => { - const loader = createPdfDocumentLoader({ display: () => () => {}, onError: vi.fn() }) - loader.load({ url: 'orca-media://file/doc?revision=r2', length: 4096 }) - expect(getDocument.mock.lastCall?.[0]).toMatchObject({ range: { length: 4096 } }) - expect(getDocument.mock.lastCall?.[0]).not.toHaveProperty('url') - - getDocument.mockClear() - const onError = vi.fn() - const unsized = createPdfDocumentLoader({ display: () => () => {}, onError }) - unsized.load({ url: 'orca-media://file/empty?revision=r3' }) - expect(getDocument).not.toHaveBeenCalled() - expect(onError).toHaveBeenLastCalledWith('Failed to load PDF preview') - - loader.load({ base64: 'JVBERg==' }) - expect(getDocument.mock.lastCall?.[0]).toMatchObject({ - data: new Uint8Array([0x25, 0x50, 0x44, 0x46]) - }) - loader.dispose() - }) - - afterEach(() => vi.unstubAllGlobals()) - - it('tears down the load whose range failed, not just its message', async () => { - vi.stubGlobal('window', { - ...window, - api: { - fs: { - readPreviewRange: vi.fn(async () => { - throw new Error('gone') - }) - } - } - }) - const onError = vi.fn() - const loader = createPdfDocumentLoader({ display: () => () => {}, onError }) - loader.load({ url: 'orca-media://file/doc?revision=r1', length: 4096 }) - const task = getDocument.mock.results.at(-1)?.value - - getDocument.mock.lastCall?.[0].range?.requestDataRange(0, 1024) - - await vi.waitFor(() => expect(onError).toHaveBeenLastCalledWith('Failed to load PDF preview')) - expect(task?.destroy).toHaveBeenCalledOnce() - loader.dispose() - }) -}) diff --git a/src/renderer/src/components/editor/use-monaco-editor-decorations.doc-link-refresh.test.tsx b/src/renderer/src/components/editor/use-monaco-editor-decorations.doc-link-refresh.test.tsx deleted file mode 100644 index 4db9315381e..00000000000 --- a/src/renderer/src/components/editor/use-monaco-editor-decorations.doc-link-refresh.test.tsx +++ /dev/null @@ -1,70 +0,0 @@ -// @vitest-environment happy-dom -import { act, useRef } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import type { editor } from 'monaco-editor' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useMonacoEditorDecorations } from './use-monaco-editor-decorations' -import type { MarkdownDocLinkDecorationController } from './monaco-markdown-doc-link-decorations' - -vi.mock('./monaco-markdown-doc-completions', () => ({ - clearMarkdownDocCompletionDocuments: () => {}, - setMarkdownDocCompletionDocuments: () => {} -})) - -const refresh = vi.fn() -const controller: MarkdownDocLinkDecorationController = { refresh, dispose: () => {} } - -function Harness({ content, language }: { content: string; language: string }): null { - const editorRef = useRef(null) - const decorations = useMonacoEditorDecorations({ - editorRef, - mountedEditor: null, - content, - language, - markdownDocuments: undefined, - conflictDecorationsEnabled: false - }) - decorations.markdownDocLinkDecorationsRef.current = controller - return null -} - -let container: HTMLDivElement -let root: Root - -describe('useMonacoEditorDecorations doc-link refresh', () => { - beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - refresh.mockClear() - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(async () => { - await act(async () => root.unmount()) - document.body.replaceChildren() - }) - - it('does not refresh doc-link decorations on content changes', async () => { - await act(async () => root.render()) - refresh.mockClear() - - for (let keystroke = 0; keystroke < 200; keystroke += 1) { - await act(async () => - root.render() - ) - } - - // The controller already subscribes to model content; a React mirror would duplicate refreshes. - expect(refresh).not.toHaveBeenCalled() - }) - - it('still refreshes when the language of a retained model changes', async () => { - await act(async () => root.render()) - refresh.mockClear() - - await act(async () => root.render()) - - expect(refresh).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/native-chat/structured-session-takeover-report.test.tsx b/src/renderer/src/components/native-chat/structured-session-takeover-report.test.tsx deleted file mode 100644 index 470dabb7762..00000000000 --- a/src/renderer/src/components/native-chat/structured-session-takeover-report.test.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// @vitest-environment happy-dom - -/** Accepted chat input must claim structured workers for the user so orchestration release cannot close their active conversation. */ - -import { describe, expect, it, vi } from 'vitest' -import { renderHook } from '@testing-library/react' - -const reportStructuredSessionUserInput = vi.hoisted(() => vi.fn()) -const dispatchStructuredComposerText = vi.hoisted(() => vi.fn()) - -vi.mock('@/lib/worker-terminal-takeover-report', () => ({ - reportStructuredSessionUserInput, - reportWorkerTerminalUserInput: vi.fn() -})) -vi.mock('@/lib/native-chat-telemetry', () => ({ emitNativeChatMessageSent: vi.fn() })) -vi.mock('./native-chat-structured-composer-dispatch', () => ({ - dispatchNativeChatStructuredComposerText: dispatchStructuredComposerText -})) - -import { useNativeChatStructuredComposerSend } from './use-native-chat-structured-composer-send' -import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types' - -function transport(): NativeChatStructuredComposerTransport { - return { - capturePresentation: () => () => true, - send: vi.fn(() => true), - dispatchCommand: vi.fn(async () => ({ handled: false, accepted: false, error: null })), - optionsSurface: { - getSnapshot: () => [], - setOption: vi.fn(), - invokeAction: vi.fn(), - subscribe: () => () => {} - }, - optionSnapshot: [], - onError: vi.fn(), - runtime: 'local', - sessionId: 'session-1', - runtimeEnvironmentId: null - } -} - -function send(structuredTransport: NativeChatStructuredComposerTransport): (text: string) => void { - const { result } = renderHook(() => - useNativeChatStructuredComposerSend({ - agent: 'claude', - draftScopeKey: 'tab-1:pane', - imageAttachments: [], - structuredTransport, - isComposing: () => false, - clearSkillOrigin: vi.fn(), - setDraft: vi.fn(), - setCaret: vi.fn() - }) - ) - return result.current -} - -describe('a real user send from a structured chat pane', () => { - it('reports the takeover, addressed by session and never by pane key', async () => { - // Use session identity; exposing main’s random pane-key credential would leak takeover authority. - reportStructuredSessionUserInput.mockClear() - dispatchStructuredComposerText.mockResolvedValue({ accepted: true, error: null }) - send(transport())('ship it') - await vi.waitFor(() => - expect(reportStructuredSessionUserInput).toHaveBeenCalledWith('session-1', null) - ) - }) - - it('reports nothing when the transport refused the send', async () => { - reportStructuredSessionUserInput.mockClear() - dispatchStructuredComposerText.mockResolvedValue({ accepted: false, error: 'nope' }) - send(transport())('ship it') - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(reportStructuredSessionUserInput).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/plugins/page/PluginContributionActionLanguage.test.tsx b/src/renderer/src/components/plugins/page/PluginContributionActionLanguage.test.tsx deleted file mode 100644 index f95265153bd..00000000000 --- a/src/renderer/src/components/plugins/page/PluginContributionActionLanguage.test.tsx +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../../shared/constants' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' -import type { PluginLanguagePackRegistration } from '../../../../../shared/plugins/artifacts/plugin-language-pack-artifact' -import { languageDisplayName } from '../presentation/plugin-contributions' -import { PluginContributionActionLanguage } from './PluginContributionActionLanguage' - -const state = vi.hoisted( - (): { settings: GlobalSettings | null; updateSettings: ReturnType } => ({ - settings: null, - updateSettings: vi.fn().mockResolvedValue(undefined) - }) -) -const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() })) -vi.mock('@/store', () => ({ - useAppStore: Object.assign((selector: (value: typeof state) => unknown) => selector(state), { - getState: () => state - }) -})) -vi.mock('sonner', () => ({ toast })) - -const pack: PluginLanguagePackRegistration = { - id: 'plugin:acme.lang/fr', - resourceLanguage: 'pluginacmelangfr', - pluginKey: 'acme.lang', - locale: 'fr', - catalog: {}, - coverage: 95 -} -const name = languageDisplayName('fr') - -afterEach(() => { - cleanup() - state.settings = null - state.updateSettings.mockReset().mockResolvedValue(undefined) - toast.error.mockClear() -}) - -it('switches to the pack only when asked and offers the way back to the previous language', () => { - state.settings = { ...getDefaultSettings('/tmp'), uiLanguage: 'en' } - const view = render() - expect(state.updateSettings).not.toHaveBeenCalled() - - fireEvent.click(screen.getByRole('button', { name: `Switch language to ${name}` })) - expect(state.updateSettings).toHaveBeenCalledExactlyOnceWith({ uiLanguage: pack.id }) - - state.settings = { ...state.settings, uiLanguage: pack.id } - view.rerender() - fireEvent.click(screen.getByRole('button', { name: `Switch back from ${name}` })) - expect(state.updateSettings).toHaveBeenLastCalledWith({ uiLanguage: 'en' }) -}) - -it('falls back to following the system language when nothing was remembered', () => { - state.settings = { ...getDefaultSettings('/tmp'), uiLanguage: pack.id } - render() - fireEvent.click(screen.getByRole('button', { name: `Switch back from ${name}` })) - expect(state.updateSettings).toHaveBeenCalledExactlyOnceWith({ uiLanguage: 'system' }) -}) - -it('says so when the switch is rejected', async () => { - state.settings = { ...getDefaultSettings('/tmp'), uiLanguage: 'en' } - state.updateSettings.mockRejectedValue(new Error('disk full')) - render() - fireEvent.click(screen.getByRole('button', { name: `Switch language to ${name}` })) - await vi.waitFor(() => - expect(toast.error).toHaveBeenCalledWith('Could not switch language', { - description: 'disk full' - }) - ) -}) diff --git a/src/renderer/src/components/sidebar/AgentDashboardSidebarHost.test.tsx b/src/renderer/src/components/sidebar/AgentDashboardSidebarHost.test.tsx deleted file mode 100644 index 1b90f264c3e..00000000000 --- a/src/renderer/src/components/sidebar/AgentDashboardSidebarHost.test.tsx +++ /dev/null @@ -1,75 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, render, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import AgentDashboardSidebarHost from './AgentDashboardSidebarHost' - -vi.mock('@/components/dashboard/AgentDashboardDrawer', () => ({ - AgentDashboardDrawer: () => null -})) - -const initialState = useAppStore.getInitialState() - -beforeEach(() => { - useAppStore.setState({ agentDashboardDrawerOpen: false }, false) -}) - -afterEach(() => { - cleanup() - useAppStore.setState(initialState, true) -}) - -describe('AgentDashboardSidebarHost', () => { - it('closes the dashboard when the workspace board opens', async () => { - useAppStore.setState({ agentDashboardDrawerOpen: true }) - render( - - ) - - await waitFor(() => expect(useAppStore.getState().agentDashboardDrawerOpen).toBe(false)) - }) - - it('closes the workspace board when the dashboard opens', async () => { - const closeWorkspaceBoard = vi.fn() - const view = render( - - ) - - act(() => useAppStore.setState({ agentDashboardDrawerOpen: true })) - view.rerender( - - ) - - await waitFor(() => expect(closeWorkspaceBoard).toHaveBeenCalledOnce()) - }) - - it('clears an open dashboard when the sidebar closes', async () => { - useAppStore.setState({ agentDashboardDrawerOpen: true }) - render( - - ) - - await waitFor(() => expect(useAppStore.getState().agentDashboardDrawerOpen).toBe(false)) - }) -}) diff --git a/src/renderer/src/components/sidebar/worktree-attachment-editing.test.ts b/src/renderer/src/components/sidebar/worktree-attachment-editing.test.ts deleted file mode 100644 index f51b8bb33df..00000000000 --- a/src/renderer/src/components/sidebar/worktree-attachment-editing.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { WorkspaceAttachment } from '../../../../shared/worktree/types' -import { - ATTACHMENT_INPUT_KINDS, - buildWorkspaceAttachmentEdits, - canUseWorkspaceReviewForChecks -} from './worktree-attachment-editing' - -const language = vi.hoisted(() => ({ prefix: '' })) -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => language.prefix + fallback -})) - -function repo(host: string): Repo { - return { - id: 'repo', - path: '/repo', - displayName: 'Repo', - badgeColor: '', - addedAt: 0, - gitRemoteIdentity: { - canonicalKey: `${host}/acme/repo`, - remoteName: 'origin', - remoteUrl: `https://${host}/acme/repo.git` - } - } -} -const review: WorkspaceAttachment = { provider: 'github', type: 'pr', number: 1 } - -describe('workspace attachment editing', () => { - it('translates reference type labels when rendered after a language change', () => { - expect(ATTACHMENT_INPUT_KINDS[0].label()).toBe('GitHub PR') - language.prefix = 'translated: ' - expect(ATTACHMENT_INPUT_KINDS[0].label()).toBe('translated: GitHub PR') - language.prefix = '' - }) - it('requires a compatible provider before a bare review can drive checks', () => { - expect(canUseWorkspaceReviewForChecks(review, repo('github.com'))).toBe(true) - expect( - canUseWorkspaceReviewForChecks( - { provider: 'gitlab', type: 'mr', number: 1 }, - repo('github.com') - ) - ).toBe(false) - expect(canUseWorkspaceReviewForChecks(review, repo('git.example.com'))).toBe(false) - expect(canUseWorkspaceReviewForChecks(review, repo('git.example.com'), 'github')).toBe(true) - expect(canUseWorkspaceReviewForChecks(review, undefined)).toBe(false) - }) - - it('submits base and draft snapshots without pre-merging concurrent changes', () => { - const initial = [{ ...review, title: 'Old' }] - const draft = [ - { ...review, title: 'New', origins: [{ kind: 'observed' as const, tabId: 'tab' }] } - ] - expect(buildWorkspaceAttachmentEdits({ initial, draft })).toEqual({ - linkedItemsBase: initial, - linkedItems: draft - }) - }) - it('removes a review through the collection without emitting a scalar selection', () => { - const mr: WorkspaceAttachment = { provider: 'gitlab', type: 'mr', number: 2 } - const initial = [review, mr] - expect(buildWorkspaceAttachmentEdits({ initial, draft: [mr] })).toEqual({ - linkedItemsBase: initial, - linkedItems: [mr] - }) - }) - it('omits untouched collections', () => { - expect(buildWorkspaceAttachmentEdits({ initial: [review], draft: [{ ...review }] })).toEqual({}) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-link-escaping-file-open.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-escaping-file-open.test.ts deleted file mode 100644 index e361f48215b..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-link-escaping-file-open.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { openDetectedFilePath } from './terminal-link-handlers' -import { createTerminalLinkTestDoubles } from './terminal-link-handlers-test-fixtures' -import { - flushAsyncWork, - installTerminalLinkTestEnvironment, - setPlatform -} from './terminal-link-handlers-test-harness' - -const doubles = createTerminalLinkTestDoubles() -const { storeState, deps, openFileMock, statMock } = doubles - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => storeState - } -})) - -vi.mock('@/lib/worktree-activation', () => ({ - activateAndRevealWorkspace: vi.fn(), - activateAndRevealWorktree: vi.fn() -})) - -vi.mock('@/lib/connection-context', () => ({ - getConnectionId: vi.fn(() => null) -})) - -installTerminalLinkTestEnvironment(doubles) - -/** Main's answer for a project link to outside: refused inside the root, readable as user-named. */ -function linkLeadsOutOfProject(): void { - statMock.mockImplementation(async ({ access }: { access?: { kind: string } }) => { - if (access?.kind !== 'user-file') { - throw new Error('Access denied: path resolves outside allowed directories') - } - return { size: 1, isDirectory: false, mtime: 1 } - }) -} - -describe('Cmd-click on a project file that links out of the project', () => { - it('opens it by its absolute path so it reads the same after a restart', async () => { - setPlatform('Macintosh') - linkLeadsOutOfProject() - - openDetectedFilePath('/tmp/docs/link.md', null, null, deps) - await flushAsyncWork() - - expect(openFileMock).toHaveBeenCalledWith( - expect.objectContaining({ - filePath: '/tmp/docs/link.md', - relativePath: '/tmp/docs/link.md', - worktreeId: 'wt-1' - }), - expect.anything() - ) - }) - - it('keeps an ordinary project file as a project tab', async () => { - setPlatform('Macintosh') - statMock.mockReset().mockResolvedValue({ size: 1, isDirectory: false, mtime: 1 }) - - openDetectedFilePath('/tmp/docs/plain.md', null, null, deps) - await flushAsyncWork() - - expect(statMock).toHaveBeenCalledExactlyOnceWith({ - filePath: '/tmp/docs/plain.md', - connectionId: undefined, - wakeWslDistro: true - }) - expect(openFileMock).toHaveBeenCalledWith( - expect.objectContaining({ filePath: '/tmp/docs/plain.md', relativePath: 'docs/plain.md' }), - expect.anything() - ) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-paste-execution.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-paste-execution.test.ts deleted file mode 100644 index 08781b06213..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-pane-paste-execution.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import type { ManagedPane } from '@/lib/pane-manager/pane-manager' -import { createTerminalPanePasteExecution } from './terminal-pane-paste-execution' -import type { TerminalPaneCloseController } from './use-terminal-pane-close-actions' - -const mocks = vi.hoisted(() => ({ - pasteTerminalClipboard: vi.fn() -})) - -vi.mock('./terminal-clipboard-paste', () => ({ - pasteTerminalClipboard: mocks.pasteTerminalClipboard -})) - -const TAB_ID = 'tab-1' -const LEAF_ID = '11111111-1111-4111-8111-111111111111' - -function createExecution( - platform: NodeJS.Platform = 'win32' -): ReturnType { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: paste execution reads only these controller fields. - const controller = { - forceBracketedMultilineTextPaste: platform === 'win32', - managerRef: { current: null }, - paneTransportsRef: { current: new Map() }, - setTerminalError: vi.fn(), - tabId: TAB_ID, - worktreeId: 'worktree-1' - } as unknown as TerminalPaneCloseController - return createTerminalPanePasteExecution(controller, platform) -} - -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: option resolution reads only the pane ids. -const pane = { id: 1, leafId: LEAF_ID } as unknown as ManagedPane - -async function pasteWithKeyboard(platform?: NodeJS.Platform): Promise { - createExecution(platform).pasteFromClipboard(pane, 'keyboard', vi.fn()) - await vi.waitFor(() => expect(mocks.pasteTerminalClipboard).toHaveBeenCalledOnce()) - return mocks.pasteTerminalClipboard.mock.calls[0][0].protectedMultilineTextPasteOptions -} - -describe('createTerminalPanePasteExecution.pasteFromClipboard', () => { - beforeEach(() => { - useAppStore.setState(useAppStore.getInitialState(), true) - mocks.pasteTerminalClipboard.mockReset().mockResolvedValue({ status: 'pasted', kind: 'text' }) - vi.stubGlobal('api', { ui: { saveClipboardImageAsTempFile: vi.fn() } }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('sends Windows Codex newlines as Alt+Enter on Ctrl+V, like right-click paste', async () => { - useAppStore.setState({ - paneForegroundAgentByPaneKey: { - [`${TAB_ID}:${LEAF_ID}`]: { agent: 'codex', shellForeground: false } - } - }) - - await expect(pasteWithKeyboard()).resolves.toEqual({ windowsInputRecordNewline: 'alt-enter' }) - }) - - it('leaves non-Windows Codex Cmd+V on xterm bracketing', async () => { - useAppStore.setState({ - paneForegroundAgentByPaneKey: { - [`${TAB_ID}:${LEAF_ID}`]: { agent: 'codex', shellForeground: false } - } - }) - - await expect(pasteWithKeyboard('darwin')).resolves.toBeUndefined() - }) -}) diff --git a/src/renderer/src/hooks/useIpcEvents-agent-dashboard-shortcut.test.ts b/src/renderer/src/hooks/useIpcEvents-agent-dashboard-shortcut.test.ts deleted file mode 100644 index d0e3b7ff6cb..00000000000 --- a/src/renderer/src/hooks/useIpcEvents-agent-dashboard-shortcut.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { toggleAgentDashboardFromShortcut } from './ipc-events/agent-dashboard-command' - -function makeState( - overrides: { - activeView?: string - experimentEnabled?: boolean - mode?: 'in-window' | 'popout' - drawerOpen?: boolean - } = {} -) { - return { - activeView: overrides.activeView ?? 'terminal', - settings: { - experimentalAgentDashboardPopout: overrides.experimentEnabled ?? true, - experimentalAgentDashboardMode: overrides.mode ?? 'in-window' - }, - agentDashboardDrawerOpen: overrides.drawerOpen ?? false, - setSidebarOpen: vi.fn(), - setAgentDashboardDrawerOpen: vi.fn() - } -} - -describe('toggleAgentDashboardFromShortcut', () => { - it('stays inert while the Agent Dashboard experiment is off', () => { - const state = makeState({ experimentEnabled: false }) - const openPopout = vi.fn() - - toggleAgentDashboardFromShortcut(state as never, openPopout) - - expect(openPopout).not.toHaveBeenCalled() - expect(state.setAgentDashboardDrawerOpen).not.toHaveBeenCalled() - expect(state.setSidebarOpen).not.toHaveBeenCalled() - }) - - it('stays inert in the Settings view', () => { - const state = makeState({ activeView: 'settings' }) - const openPopout = vi.fn() - - toggleAgentDashboardFromShortcut(state as never, openPopout) - - expect(openPopout).not.toHaveBeenCalled() - expect(state.setAgentDashboardDrawerOpen).not.toHaveBeenCalled() - }) - - it('opens the pop-out window in popout mode without touching the drawer', () => { - const state = makeState({ mode: 'popout' }) - const openPopout = vi.fn() - - toggleAgentDashboardFromShortcut(state as never, openPopout) - - expect(openPopout).toHaveBeenCalledOnce() - expect(state.setAgentDashboardDrawerOpen).not.toHaveBeenCalled() - expect(state.setSidebarOpen).not.toHaveBeenCalled() - }) - - it('reveals the sidebar when opening the in-window drawer', () => { - const state = makeState({ drawerOpen: false }) - - toggleAgentDashboardFromShortcut(state as never, vi.fn()) - - expect(state.setSidebarOpen).toHaveBeenCalledWith(true) - expect(state.setAgentDashboardDrawerOpen).toHaveBeenCalledWith(true) - }) - - it('leaves the sidebar alone when closing the in-window drawer', () => { - // Closing must not force sidebar open and re-reveal the drawer against its collapse effect. - const state = makeState({ drawerOpen: true }) - - toggleAgentDashboardFromShortcut(state as never, vi.fn()) - - expect(state.setAgentDashboardDrawerOpen).toHaveBeenCalledWith(false) - expect(state.setSidebarOpen).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/ai-vault-resume-shell.test.ts b/src/renderer/src/lib/ai-vault-resume-shell.test.ts deleted file mode 100644 index 603b05db1b4..00000000000 --- a/src/renderer/src/lib/ai-vault-resume-shell.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { getDefaultSettings } from '../../../shared/constants' -import { TEST_REPO, makeWorktree } from '../store/slices/worktrees-slice-test-fixtures' -import { describe, expect, it, vi } from 'vitest' - -vi.mock('@/lib/new-workspace', () => ({ - CLIENT_PLATFORM: 'darwin' -})) - -import { buildAiVaultResumeCopyCommandForWorktree } from './ai-vault-resume-command' - -type ResumeShellState = Parameters[0]['state'] - -function makeState(worktreeHostId?: `ssh:${string}`): ResumeShellState { - return { - activeRepoId: 'repo-1', - activeWorktreeId: 'repo-1::worktree-1', - detectedWorktreesByRepo: {}, - sshConnectionStates: new Map(), - sshStateByEnvironment: new Map(), - runtimeStatusByEnvironmentId: new Map(), - folderWorkspaces: [], - projectGroups: [], - repos: [{ ...TEST_REPO, id: 'repo-1', path: '/home/alice/repo' }], - projects: [ - { - displayName: 'repo', - badgeColor: '', - createdAt: 0, - updatedAt: 0, - id: 'repo-1', - sourceRepoIds: ['repo-1'] - } - ], - settings: { - ...getDefaultSettings('/tmp'), - agentDefaultArgs: { codex: '' }, - agentDefaultEnv: { codex: {} } - }, - worktreesByRepo: { - 'repo-1': [ - makeWorktree({ - id: 'repo-1::worktree-1', - repoId: 'repo-1', - path: '/home/alice/repo', - ...(worktreeHostId ? { hostId: worktreeHostId } : {}) - }) - ] - } - } -} - -describe('copied real-home Codex resume command', () => { - const session = { - agent: 'codex' as const, - sessionId: 'session one', - cwd: '/home/alice/repo', - codexHome: null - } - - it('clears inherited Codex homes for a worktree on an SSH host', () => { - expect( - buildAiVaultResumeCopyCommandForWorktree({ - state: makeState('ssh:target-1'), - worktreeId: 'repo-1::worktree-1', - session - }) - ).toBe( - `cd '/home/alice/repo' && env -u CODEX_HOME -u ORCA_CODEX_HOME codex '-c' 'tui.resume_cwd=current' 'resume' 'session one'` - ) - }) -}) diff --git a/src/renderer/src/lib/cmd-j-github-url-lookup.test.ts b/src/renderer/src/lib/cmd-j-github-url-lookup.test.ts deleted file mode 100644 index 790122e0d2f..00000000000 --- a/src/renderer/src/lib/cmd-j-github-url-lookup.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { GitHubWorkItem } from '../../../shared/github/work-item-types' - -const { lookupGitHubWorkItemByOwnerRepoForSource } = vi.hoisted(() => ({ - lookupGitHubWorkItemByOwnerRepoForSource: vi.fn() -})) - -vi.mock('./github-work-item-source-lookup', () => ({ - lookupGitHubWorkItemByOwnerRepoForSource -})) - -import { lookupCmdJGitHubUrlWorkItem } from './cmd-j-github-url-lookup' - -const item = { - id: 'issue-14198', - type: 'issue', - number: 14198, - title: 'Agent terminals disappearing randomly', - state: 'open', - url: 'https://github.com/stablyai/orca/issues/14198', - labels: [], - updatedAt: '2026-08-12T12:00:00.000Z', - author: 'nwparker', - repoId: 'repo-1' -} satisfies GitHubWorkItem - -describe('lookupCmdJGitHubUrlWorkItem', () => { - beforeEach(() => { - lookupGitHubWorkItemByOwnerRepoForSource.mockReset() - }) - - it('looks up by owner/repo and returns null without a repo or on failure', async () => { - const link = { - slug: { owner: 'stablyai', repo: 'orca', host: 'github.com' }, - type: 'issue' as const, - number: 14198 - } - expect( - await lookupCmdJGitHubUrlWorkItem({ - link, - repo: null, - sourceContext: null - }) - ).toBeNull() - - lookupGitHubWorkItemByOwnerRepoForSource.mockResolvedValue(item) - expect( - await lookupCmdJGitHubUrlWorkItem({ - link, - repo: { id: 'repo-1', path: '/repos/repo-1' }, - sourceContext: null - }) - ).toEqual(item) - expect(lookupGitHubWorkItemByOwnerRepoForSource).toHaveBeenCalledWith( - expect.objectContaining({ - owner: 'stablyai', - repo: 'orca', - host: 'github.com', - number: 14198, - type: 'issue' - }) - ) - - lookupGitHubWorkItemByOwnerRepoForSource.mockRejectedValue(new Error('offline')) - expect( - await lookupCmdJGitHubUrlWorkItem({ - link, - repo: { id: 'repo-1', path: '/repos/repo-1' }, - sourceContext: null - }) - ).toBeNull() - }) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-live-freshness-request.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-live-freshness-request.test.ts deleted file mode 100644 index 69d5ebd4a92..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-status-live-freshness-request.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AppState } from '../../types' -import type { AgentStatusEntry } from '../../../../../shared/agent-status-types' -import type { AgentStatusPayload } from './agent-status-contract' -import type { AgentStatusRuntime } from './agent-status-runtime' -import { createAgentStatusLiveActions } from './agent-status-live-actions' - -const NOW = new Date('2026-04-09T12:00:00.000Z').getTime() -const PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111' - -function existingEntry(overrides: Partial = {}): AgentStatusEntry { - return { - paneKey: PANE_KEY, - state: 'working', - prompt: 'parent turn', - updatedAt: NOW, - stateStartedAt: NOW, - stateHistory: [], - agentType: 'claude', - ...overrides - } -} - -function setup(existing: AgentStatusEntry) { - const state = { - agentStatusByPaneKey: { [PANE_KEY]: existing }, - recentlyRetiredAgentStatusPaneKeys: {}, - recentlyClosedAgentStatusTabIds: {} - } as unknown as AppState - const requestFreshness = vi.fn() - const runtime = { - get: () => state, - set: vi.fn((update) => { - if (typeof update === 'function') { - update(state) - } - }), - applyGeneratedTabTitleUpdate: vi.fn(), - requestFreshness, - transactAgentStatuses: vi.fn() - } as unknown as AgentStatusRuntime - return { requestFreshness, actions: createAgentStatusLiveActions(runtime) } -} - -function payload(overrides: Partial = {}): AgentStatusPayload { - return { state: 'done', prompt: 'child hook', ...overrides } as AgentStatusPayload -} - -describe('setAgentStatus freshness requests on rejected frames', () => { - it('skips the deferred freshness scan when an inherited terminal status is suppressed', () => { - // A nested child hook inherits ORCA_PANE_KEY, so its `done` is dropped while the parent works. - const { requestFreshness, actions } = setup(existingEntry()) - - actions.setAgentStatus(PANE_KEY, payload({ agentType: 'codex' }), undefined, { - updatedAt: NOW + 1 - }) - - expect(requestFreshness).not.toHaveBeenCalled() - }) - - it('still requests deferred freshness when a stale frame is rejected', () => { - const { requestFreshness, actions } = setup(existingEntry()) - - actions.setAgentStatus(PANE_KEY, payload({ agentType: 'claude' }), undefined, { - updatedAt: NOW - 1 - }) - - expect(requestFreshness).toHaveBeenCalledWith(false) - }) -}) diff --git a/src/renderer/src/store/terminals/terminal-tab-close-providers.test.ts b/src/renderer/src/store/terminals/terminal-tab-close-providers.test.ts deleted file mode 100644 index 82c778efa13..00000000000 --- a/src/renderer/src/store/terminals/terminal-tab-close-providers.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalPtyOwner } from '@/lib/terminal-worktree-route' -import { createTestStore } from '../slices/store-test-helpers' -import { startTerminalTabProviderRetirement } from './terminal-tab-close-providers' - -const mocks = vi.hoisted(() => { - const ptyOwner: { current: TerminalPtyOwner } = { current: { kind: 'non-runtime' } } - return { ptyOwner, callRuntimeRpc: vi.fn(async () => undefined) } -}) - -vi.mock('@/lib/terminal-worktree-route', () => ({ - resolveTerminalPtyOwner: () => mocks.ptyOwner.current, - resolveTerminalWorktreeRoute: () => ({ runtimeEnvironmentId: 'env-a' }) -})) - -vi.mock('@/runtime/runtime-rpc-client', () => ({ - callRuntimeRpc: mocks.callRuntimeRpc, - ensureRuntimeEnvironmentCompatible: vi.fn() -})) - -function retire(): void { - startTerminalTabProviderRetirement({ - localPtyTeardownOwnedExternally: false, - remoteCloseOwnedByHost: false, - state: createTestStore().getState(), - tabId: 'tab-1', - retirementPlan: { - tabId: 'tab-1', - worktreeId: 'repo::wt', - ptyIds: ['remote:handle-1'], - localOrSshPtyIds: [], - runtimeTerminals: [{ ptyId: 'remote:handle-1', environmentId: null, handle: 'handle-1' }], - cleanupOnlyPtyIds: [], - sharedPtyIds: [], - unroutablePtyIds: [] - } - }) -} - -describe('closing an unscoped remote terminal id', () => { - let warn: ReturnType - beforeEach(() => { - mocks.callRuntimeRpc.mockClear() - warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - afterEach(() => warn.mockRestore()) - - it('closes it where spawn started it', () => { - mocks.ptyOwner.current = { kind: 'runtime', environmentId: 'env-a' } - retire() - expect(mocks.callRuntimeRpc).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'env-a' }, - 'terminal.close', - { terminal: 'handle-1' } - ) - }) - - it('skips and logs it, never closing on this app, when the owner is ambiguous', () => { - mocks.ptyOwner.current = { kind: 'ambiguous' } - retire() - expect(mocks.callRuntimeRpc).not.toHaveBeenCalled() - expect(warn).toHaveBeenCalledWith( - '[terminal-retirement] skipped PTYs with no resolvable owner', - { - tabId: 'tab-1', - worktreeKind: expect.any(String), - count: 1 - } - ) - }) -})