From 9bccd6795593abbe47dfebc7c2df5393712ce69c Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Fri, 30 Oct 2026 12:46:07 -0700 Subject: [PATCH] test: remove 46 low-value suites (audit 845) (#36407) * test: remove 46 low-value suites (audit 845) * test: remove orphaned workflow and runtime test references --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .github/workflows/computer-e2e.yml | 1 - config/flaky-test-pattern-baseline.txt | 1 - config/reliability-gates.jsonc | 15 +--- config/scripts/ci-shard-timings.json | 33 ------- config/scripts/vitest-node-runtime-files.mjs | 1 - src/cli/cli-exit-code.test.ts | 20 ----- src/cli/handlers/plugin-runtime.test.ts | 18 ---- ...ser-manager-viewport-crashed-guest.test.ts | 79 ----------------- ...untime-home-restart-stopped-distro.test.ts | 80 ----------------- .../computer-provider-lifecycle.test.ts | 78 ---------------- .../appimage-crashpad-handler-exit.test.ts | 78 ---------------- ...on-pty-adapter-steady-state-compat.test.ts | 77 ---------------- src/main/ipc/pty/wsl-terminal-spawn.test.ts | 23 ----- .../repo-creation-git-availability.test.ts | 78 ---------------- ...t-transport-routing-tailscale-hint.test.ts | 83 ----------------- ...anaged-host-port-forward-lifecycle.test.ts | 80 ----------------- src/main/ipc/zcode-plan-credentials.test.ts | 80 ----------------- src/main/jira/jira-search-abort.test.ts | 85 ------------------ .../macos-keychain/generic-password.test.ts | 79 ----------------- ...windows-environment-path-main-loop.test.ts | 80 ----------------- ...-browser-offscreen-epoch-ownership.test.ts | 80 ----------------- .../runtime-git-command-target.test.ts | 78 ---------------- .../runtime-linear-read-commands.test.ts | 77 ---------------- ...ime-local-worktree-materialization.test.ts | 80 ----------------- ...structured-worker-terminal-refusal.test.ts | 86 ------------------ .../runtime/terminal-agent-turn-news.test.ts | 80 ----------------- src/main/update-install-exit-watchdog.test.ts | 80 ----------------- .../wsl-distro-not-running-refusal.test.ts | 21 ----- ...CrashReportDialogSurface.overflow.test.tsx | 84 ------------------ .../editor/editor-cmd-save-target.test.ts | 80 ----------------- ...red-agent-registered-agent-surface.test.ts | 79 ----------------- ...ctured-agent-session-prompt-state.test.tsx | 80 ----------------- ...tructured-agent-session-transport.test.tsx | 76 ---------------- .../list/plugin-category-label.test.ts | 14 --- ...xplorer-tree-load-effects-wsl-wake.test.ts | 78 ---------------- .../useFileExplorerWatch.catch-up.test.tsx | 78 ---------------- .../settings/RuntimeSshAccessControl.test.tsx | 78 ---------------- .../terminal-pane/WslHostStoppedCard.test.tsx | 76 ---------------- .../terminal-copy-rejection-handling.test.ts | 78 ---------------- .../terminal-pane-layout-restore.test.ts | 80 ----------------- .../terminal-pane-set-title-event.test.ts | 77 ---------------- .../wsl-move-result-undo-path.test.tsx | 88 ------------------- .../wsl-move-slept-pane-bindings.test.ts | 32 ------- .../hooks/composer-drop-failure-toast.test.ts | 76 ---------------- ...tructured-session-completion-focus.test.ts | 77 ---------------- .../viewport-size-change-listener.test.ts | 78 ---------------- ...e-terminal-creation.wsl-host-start.test.ts | 80 ----------------- .../src/startup/ssh-startup-reconnect.test.ts | 78 ---------------- .../src/store/plugin-syntax-packs.test.ts | 27 ------ ...editor-rich-markdown-size-override.test.ts | 80 ----------------- .../plugin-publisher-derivation.test.ts | 33 ------- 51 files changed, 4 insertions(+), 3254 deletions(-) delete mode 100644 src/cli/cli-exit-code.test.ts delete mode 100644 src/cli/handlers/plugin-runtime.test.ts delete mode 100644 src/main/browser/browser-manager-viewport-crashed-guest.test.ts delete mode 100644 src/main/codex-accounts/runtime-home-restart-stopped-distro.test.ts delete mode 100644 src/main/computer/computer-provider-lifecycle.test.ts delete mode 100644 src/main/crash-reporting/appimage-crashpad-handler-exit.test.ts delete mode 100644 src/main/daemon/daemon-pty-adapter-steady-state-compat.test.ts delete mode 100644 src/main/ipc/pty/wsl-terminal-spawn.test.ts delete mode 100644 src/main/ipc/repos/repo-creation-git-availability.test.ts delete mode 100644 src/main/ipc/runtime-environments/runtime-environment-transport-routing-tailscale-hint.test.ts delete mode 100644 src/main/ipc/ssh/ssh-managed-host-port-forward-lifecycle.test.ts delete mode 100644 src/main/ipc/zcode-plan-credentials.test.ts delete mode 100644 src/main/jira/jira-search-abort.test.ts delete mode 100644 src/main/macos-keychain/generic-password.test.ts delete mode 100644 src/main/pty/windows-environment-path-main-loop.test.ts delete mode 100644 src/main/runtime/renderer-browser-offscreen-epoch-ownership.test.ts delete mode 100644 src/main/runtime/runtime-git-command-target.test.ts delete mode 100644 src/main/runtime/runtime-linear-read-commands.test.ts delete mode 100644 src/main/runtime/runtime-local-worktree-materialization.test.ts delete mode 100644 src/main/runtime/structured-worker-terminal-refusal.test.ts delete mode 100644 src/main/runtime/terminal-agent-turn-news.test.ts delete mode 100644 src/main/update-install-exit-watchdog.test.ts delete mode 100644 src/main/wsl/wsl-distro-not-running-refusal.test.ts delete mode 100644 src/renderer/src/components/crash-report/CrashReportDialogSurface.overflow.test.tsx delete mode 100644 src/renderer/src/components/editor/editor-cmd-save-target.test.ts delete mode 100644 src/renderer/src/components/native-chat/structured-agent-registered-agent-surface.test.ts delete mode 100644 src/renderer/src/components/native-chat/use-structured-agent-session-prompt-state.test.tsx delete mode 100644 src/renderer/src/components/native-chat/use-structured-agent-session-transport.test.tsx delete mode 100644 src/renderer/src/components/plugins/list/plugin-category-label.test.ts delete mode 100644 src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects-wsl-wake.test.ts delete mode 100644 src/renderer/src/components/right-sidebar/useFileExplorerWatch.catch-up.test.tsx delete mode 100644 src/renderer/src/components/settings/RuntimeSshAccessControl.test.tsx delete mode 100644 src/renderer/src/components/terminal-pane/WslHostStoppedCard.test.tsx delete mode 100644 src/renderer/src/components/terminal-pane/terminal-copy-rejection-handling.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-pane-layout-restore.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-pane-set-title-event.test.ts delete mode 100644 src/renderer/src/components/wsl-move/wsl-move-result-undo-path.test.tsx delete mode 100644 src/renderer/src/components/wsl-move/wsl-move-slept-pane-bindings.test.ts delete mode 100644 src/renderer/src/hooks/composer-drop-failure-toast.test.ts delete mode 100644 src/renderer/src/hooks/structured-session-completion-focus.test.ts delete mode 100644 src/renderer/src/hooks/viewport-size-change-listener.test.ts delete mode 100644 src/renderer/src/runtime/web-runtime-terminal-creation.wsl-host-start.test.ts delete mode 100644 src/renderer/src/startup/ssh-startup-reconnect.test.ts delete mode 100644 src/renderer/src/store/plugin-syntax-packs.test.ts delete mode 100644 src/renderer/src/store/slices/editor-rich-markdown-size-override.test.ts delete mode 100644 src/shared/plugins/installation/plugin-publisher-derivation.test.ts diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index 23c7f739b15..567a45b73cb 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -94,7 +94,6 @@ jobs: config/scripts/macos-computer-helper-owner-loss-group-recovery.test.mjs config/scripts/macos-computer-helper-owner-loss-processes.test.mjs config/scripts/computer-use-smoke.test.mjs - src/main/computer/computer-provider-lifecycle.test.ts src/main/computer/sidecar-client.test.ts src/main/computer/macos-native-provider-client.test.ts src/main/computer/macos-native-provider-socket.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 9544bb028ed..2e9f35481b3 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -402,7 +402,6 @@ 2 test-no-real-time-wait:src/main/providers/startup-line-typed-length.live-shell.test.ts 1 test-no-real-time-wait:src/main/pty/node-pty-master-fd-retirement.test.ts 1 test-no-real-time-wait:src/main/pty/posix-pty-process-groups.integration.test.ts -2 test-no-real-time-wait:src/main/pty/windows-environment-path-main-loop.test.ts 1 test-no-real-time-wait:src/main/rate-limits/opencode-go-usage-fetcher.test.ts 1 test-no-real-time-wait:src/main/runtime/agent-session/ownership/structured-agent-session-spawn-token-descendants.test.ts 1 test-no-real-time-wait:src/main/runtime/claude-structured-idle-releases-unknown.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 8e736417c05..41381a2f2ef 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -13469,7 +13469,7 @@ "providers": ["ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["ssh", "remote-runtime"], - "coverageNotes": "Deterministic renderer coverage proves startup publishes the state returned by ssh.connect, retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps.", + "coverageNotes": "Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3107", "https://github.com/stablyai/orca/pull/12664", @@ -13487,7 +13487,7 @@ "oracle": "Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/startup/ssh-startup-reconnect.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-outcome-recovery.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts", @@ -13501,7 +13501,6 @@ "testFiles": [ "src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts", "src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts", - "src/renderer/src/startup/ssh-startup-reconnect.test.ts", "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", "src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts", "src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts", @@ -13562,12 +13561,6 @@ "unwritten or explicitly released pane authority still cedes deletion to the host" ] }, - { - "file": "src/renderer/src/startup/ssh-startup-reconnect.test.ts", - "assertions": [ - "the state returned by ssh.connect is published before persisted terminals reconnect" - ] - }, { "file": "src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts", "assertions": [ @@ -13832,8 +13825,8 @@ "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/startup/ssh-startup-reconnect.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts", "result": "passed", "durationSeconds": 15, - "summary": "Ten provider-contract files and 566 tests passed, including a shared 15-second polling/RPC deadline, no input-triggered re-polling after the bound, post-timeout snapshot recovery, listener cleanup, in-flight inventory deduplication, and replacement-state migration.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/startup/ssh-startup-reconnect.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts" + "summary": "Ten provider-contract files and 566 tests passed, including a shared 15-second polling/RPC deadline, no input-triggered re-polling after the bound, post-timeout snapshot recovery, listener cleanup, in-flight inventory deduplication, and replacement-state migration. Historical run: the ssh-startup-reconnect suite was later removed as mock forwarding coverage; its original command is preserved as history, not an active gate or replacement-equivalence claim.", + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts" }, { "date": "2026-07-21", diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index e648913effc..1d8506b7833 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1269,7 +1269,6 @@ "src/main/browser/browser-manager-popup-openerless-tab.test.ts": 219, "src/main/browser/browser-manager-popup-routing.test.ts": 353, "src/main/browser/browser-manager-tab-identity.test.ts": 322, - "src/main/browser/browser-manager-viewport-crashed-guest.test.ts": 602, "src/main/browser/browser-manager-viewport-override.test.ts": 449, "src/main/browser/browser-manager-viewport-ownership.test.ts": 254, "src/main/browser/browser-manager-viewport-partial-failure.test.ts": 267, @@ -1680,7 +1679,6 @@ "src/main/codex-accounts/runtime-home-per-account-homes.test.ts": 587, "src/main/codex-accounts/runtime-home-read-only-launch-resolution.test.ts": 921, "src/main/codex-accounts/runtime-home-real-home-lane-routing.test.ts": 457, - "src/main/codex-accounts/runtime-home-restart-stopped-distro.test.ts": 309, "src/main/codex-accounts/runtime-home-resume-selection-gate.test.ts": 535, "src/main/codex-accounts/runtime-home-retained-auth-provenance.test.ts": 907, "src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts": 676, @@ -1947,7 +1945,6 @@ "src/main/codex/wsl-codex-session-bridge.test.ts": 170, "src/main/command-code/hook-service.test.ts": 368, "src/main/computer/computer-action-verification-normalization.test.ts": 33, - "src/main/computer/computer-provider-lifecycle.test.ts": 260, "src/main/computer/computer-provider-unavailable-message.test.ts": 55, "src/main/computer/computer-sidecar-diagnostics.test.ts": 39, "src/main/computer/desktop-script-provider-action-errors.test.ts": 96, @@ -1977,7 +1974,6 @@ "src/main/computer/sidecar-provider-reaping.integration.test.ts": 295, "src/main/computer/windows-powershell-execution-policy.test.ts": 54, "src/main/copilot/hook-service.test.ts": 126, - "src/main/crash-reporting/appimage-crashpad-handler-exit.test.ts": 35, "src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts": 55, "src/main/crash-reporting/crash-breadcrumb-store-leak.test.ts": 93, "src/main/crash-reporting/crash-breadcrumb-store-orphan-cleanup.test.ts": 43, @@ -2117,7 +2113,6 @@ "src/main/daemon/daemon-pty-adapter-replacement-exit-race.test.ts": 4927, "src/main/daemon/daemon-pty-adapter-session-adoption.test.ts": 1357, "src/main/daemon/daemon-pty-adapter-spawn-intent.test.ts": 431, - "src/main/daemon/daemon-pty-adapter-steady-state-compat.test.ts": 436, "src/main/daemon/daemon-pty-adapter-subscription-fanout.test.ts": 41, "src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts": 839, "src/main/daemon/daemon-pty-adapter.test.ts": 1737, @@ -3106,7 +3101,6 @@ "src/main/ipc/repos/folder-workspace-attachment-handlers.test.ts": 2054, "src/main/ipc/repos/local-repo-registration.test.ts": 266, "src/main/ipc/repos/project-host-setup-wsl-move-fence.test.ts": 3075, - "src/main/ipc/repos/repo-creation-git-availability.test.ts": 124, "src/main/ipc/repos/repo-ipc-wsl-move-fence.test.ts": 2855, "src/main/ipc/runtime-environments/orcad-delta-move-handlers.test.ts": 949, "src/main/ipc/runtime-environments/orcad-runtime-maintenance-handlers.test.ts": 622, @@ -3141,7 +3135,6 @@ "src/main/ipc/runtime-environments/runtime-environment-subscription-layout-recording.test.ts": 3532, "src/main/ipc/runtime-environments/runtime-environment-support-routing.test.ts": 716, "src/main/ipc/runtime-environments/runtime-environment-transport-generation.test.ts": 24, - "src/main/ipc/runtime-environments/runtime-environment-transport-routing-tailscale-hint.test.ts": 3619, "src/main/ipc/runtime-environments/runtime-environment-unreachable-hint.test.ts": 51, "src/main/ipc/runtime-environments/runtime-environments-call-routing.test.ts": 2749, "src/main/ipc/runtime-environments/runtime-environments-capability-cache.test.ts": 2904, @@ -3193,7 +3186,6 @@ "src/main/ipc/ssh/ssh-host-server-on-connect-wiring.test.ts": 5366, "src/main/ipc/ssh/ssh-host-sleep-reconnect.test.ts": 41, "src/main/ipc/ssh/ssh-host-user-disconnect.test.ts": 2819, - "src/main/ipc/ssh/ssh-managed-host-port-forward-lifecycle.test.ts": 3030, "src/main/ipc/ssh/ssh-passphrase.test.ts": 76, "src/main/ipc/ssh/ssh-port-forward-handlers.test.ts": 159, "src/main/ipc/ssh/ssh-port-forward-restore.test.ts": 246, @@ -3299,7 +3291,6 @@ "src/main/ipc/wsl-guest-windows-drive-path.test.ts": 58, "src/main/ipc/wsl-host-gate-off.test.ts": 3774, "src/main/ipc/wsl-move-handlers.test.ts": 399, - "src/main/ipc/zcode-plan-credentials.test.ts": 50, "src/main/issue-command-ignore.test.ts": 724, "src/main/jcode/hook-config.test.ts": 64, "src/main/jcode/hook-gate-script.test.ts": 134, @@ -3326,7 +3317,6 @@ "src/main/jira/jira-issue-mutations.test.ts": 110, "src/main/jira/jira-issue-summary-timeout.test.ts": 172, "src/main/jira/jira-preset-filters.test.ts": 132, - "src/main/jira/jira-search-abort.test.ts": 74, "src/main/jira/jira-transition-required-fields.test.ts": 54, "src/main/jsonl-rpc/agent-connection.test.ts": 260, "src/main/jsonl-rpc/peer.test.ts": 224, @@ -3382,7 +3372,6 @@ "src/main/local-worktree-removal-recovery.test.ts": 189, "src/main/localhost-worktree-label-proxy.test.ts": 97, "src/main/macos-full-disk-access-status.test.ts": 69, - "src/main/macos-keychain/generic-password.test.ts": 37, "src/main/macos-press-and-hold-default.defaults-domain.test.ts": 60, "src/main/macos-press-and-hold-default.test.ts": 72, "src/main/macos-system-sleep-assertion.test.ts": 53, @@ -4582,7 +4571,6 @@ "src/main/pty/powershell-profile-env.test.ts": 69, "src/main/pty/shell-startup-env.test.ts": 93, "src/main/pty/terminal-color-env.test.ts": 44, - "src/main/pty/windows-environment-path-main-loop.test.ts": 442, "src/main/pty/windows-environment-path.test.ts": 107, "src/main/pty/windows-path-registry-change.test.ts": 59, "src/main/pty/windows-path-registry-fallback.test.ts": 53, @@ -5624,7 +5612,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-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, "src/main/runtime/runtime-git-generation-admission.test.ts": 560, @@ -5645,10 +5632,8 @@ "src/main/runtime/runtime-legacy-worker-terminal-recovery-persistence.test.ts": 361, "src/main/runtime/runtime-legacy-worker-terminal-recovery-retry.test.ts": 93, "src/main/runtime/runtime-linear-comment-edit.test.ts": 372, - "src/main/runtime/runtime-linear-read-commands.test.ts": 245, "src/main/runtime/runtime-local-create-rearm-ordering.test.ts": 3031, "src/main/runtime/runtime-local-worktree-create.test.ts": 575, - "src/main/runtime/runtime-local-worktree-materialization.test.ts": 152, "src/main/runtime/runtime-local-worktree-terminal-startup-layout-owner.test.ts": 51, "src/main/runtime/runtime-local-worktree-terminal-startup.test.ts": 71, "src/main/runtime/runtime-machine-name.test.ts": 62, @@ -5892,12 +5877,10 @@ "src/main/runtime/structured-worker-identity.test.ts": 282, "src/main/runtime/structured-worker-mail-routing.test.ts": 1759, "src/main/runtime/structured-worker-terminal-read.test.ts": 2127, - "src/main/runtime/structured-worker-terminal-refusal.test.ts": 308, "src/main/runtime/terminal-agent-fenced-keys.test.ts": 86, "src/main/runtime/terminal-agent-interrupt.test.ts": 39, "src/main/runtime/terminal-agent-phone-push.test.ts": 80, "src/main/runtime/terminal-agent-prompt-answer.test.ts": 79, - "src/main/runtime/terminal-agent-turn-news.test.ts": 103, "src/main/runtime/terminal-ansi-pending-retention.test.ts": 228, "src/main/runtime/terminal-chat-owner-persistence.test.ts": 1757, "src/main/runtime/terminal-close-observed-exit.test.ts": 3812, @@ -6517,7 +6500,6 @@ "src/main/tray/system-tray.test.ts": 212, "src/main/tray/tray-attention-icon.test.ts": 41, "src/main/tray/tray-dev-badge.test.ts": 36, - "src/main/update-install-exit-watchdog.test.ts": 45, "src/main/updater-agent-state-rules-release.test.ts": 58, "src/main/updater-changelog.test.ts": 46, "src/main/updater-events.test.ts": 231, @@ -7191,7 +7173,6 @@ "src/renderer/src/components/contextual-tours/request-contextual-tour-when-ready.test.ts": 1380, "src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts": 1525, "src/renderer/src/components/contextual-tours/workspace-creation-tour-handoff.test.ts": 1390, - "src/renderer/src/components/crash-report/CrashReportDialogSurface.overflow.test.tsx": 412, "src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts": 124, "src/renderer/src/components/crash-report/use-crash-report-copy.test.tsx": 358, "src/renderer/src/components/dashboard-popout/AgentKanbanBoard.test.tsx": 740, @@ -7381,7 +7362,6 @@ "src/renderer/src/components/editor/editor-buffer-entry-points.parity.test.ts": 1507, "src/renderer/src/components/editor/editor-buffer-sharing.test.ts": 1880, "src/renderer/src/components/editor/editor-clean-tab-draft-invariant.test.ts": 1600, - "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.test.ts": 380, @@ -7992,7 +7972,6 @@ "src/renderer/src/components/native-chat/native-chat-working-suppression.test.ts": 42, "src/renderer/src/components/native-chat/omp-model-switch-capability.test.ts": 266, "src/renderer/src/components/native-chat/serialized-screen-background-rows.test.ts": 112, - "src/renderer/src/components/native-chat/structured-agent-registered-agent-surface.test.ts": 373, "src/renderer/src/components/native-chat/structured-agent-session-delivery-notices.kept-card.test.ts": 427, "src/renderer/src/components/native-chat/structured-agent-session-delivery-notices.test.ts": 234, "src/renderer/src/components/native-chat/structured-agent-session-legacy-outbox.test.ts": 383, @@ -8093,7 +8072,6 @@ "src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx": 2898, "src/renderer/src/components/native-chat/use-structured-agent-session-paired-runtime.test.tsx": 1884, "src/renderer/src/components/native-chat/use-structured-agent-session-prompt-cancel.test.tsx": 1856, - "src/renderer/src/components/native-chat/use-structured-agent-session-prompt-state.test.tsx": 2275, "src/renderer/src/components/native-chat/use-structured-agent-session-provisional.test.tsx": 1924, "src/renderer/src/components/native-chat/use-structured-agent-session-question-answers.test.tsx": 2181, "src/renderer/src/components/native-chat/use-structured-agent-session-queued-edit.test.tsx": 1928, @@ -8108,7 +8086,6 @@ "src/renderer/src/components/native-chat/use-structured-agent-session-stop.test.tsx": 2896, "src/renderer/src/components/native-chat/use-structured-agent-session-thread-goal.test.tsx": 187, "src/renderer/src/components/native-chat/use-structured-agent-session-transport-state.working.test.tsx": 395, - "src/renderer/src/components/native-chat/use-structured-agent-session-transport.test.tsx": 1524, "src/renderer/src/components/native-chat/use-structured-agent-session-write-refusal.test.tsx": 2087, "src/renderer/src/components/native-chat/use-structured-agent-session.clear-send.test.tsx": 2827, "src/renderer/src/components/native-chat/use-structured-agent-session.cut-turn-notice.test.tsx": 1855, @@ -8470,7 +8447,6 @@ "src/renderer/src/components/right-sidebar/useFileExplorerVisibleRowProjection.debounce.test.tsx": 2595, "src/renderer/src/components/right-sidebar/useFileExplorerVisibleRowProjection.test.ts": 1888, "src/renderer/src/components/right-sidebar/useFileExplorerWatch.broker.test.tsx": 501, - "src/renderer/src/components/right-sidebar/useFileExplorerWatch.catch-up.test.tsx": 271, "src/renderer/src/components/right-sidebar/useFileExplorerWatch.host-root.test.tsx": 555, "src/renderer/src/components/right-sidebar/useFileExplorerWatch.pending-refresh.test.tsx": 300, "src/renderer/src/components/right-sidebar/useFileExplorerWatch.test.ts": 1601, @@ -8567,7 +8543,6 @@ "src/renderer/src/components/settings/RuntimeHostAccessForm.test.tsx": 307, "src/renderer/src/components/settings/RuntimePairingGeneratorForm.test.tsx": 306, "src/renderer/src/components/settings/RuntimePairingUrlGenerator.test.tsx": 414, - "src/renderer/src/components/settings/RuntimeSshAccessControl.test.tsx": 441, "src/renderer/src/components/settings/SessionHistoryComputerRow.test.tsx": 642, "src/renderer/src/components/settings/SessionHistorySettingsPane.test.tsx": 903, "src/renderer/src/components/settings/SettingsConstants.test.ts": 97, @@ -9650,7 +9625,6 @@ "src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx": 694, "src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts": 48, "src/renderer/src/components/terminal-pane/terminal-command-lifecycle.test.ts": 46, - "src/renderer/src/components/terminal-pane/terminal-copy-rejection-handling.test.ts": 38, "src/renderer/src/components/terminal-pane/terminal-copy-shortcut.test.ts": 1636, "src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts": 115, "src/renderer/src/components/terminal-pane/terminal-cursor-appearance-precedence.test.ts": 303, @@ -9777,14 +9751,12 @@ "src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts": 1272, "src/renderer/src/components/terminal-pane/terminal-pane-layout-owner-commands.test.ts": 222, "src/renderer/src/components/terminal-pane/terminal-pane-layout-owner-gestures.test.ts": 43, - "src/renderer/src/components/terminal-pane/terminal-pane-layout-restore.test.ts": 277, "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-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, - "src/renderer/src/components/terminal-pane/terminal-pane-set-title-event.test.ts": 1546, "src/renderer/src/components/terminal-pane/terminal-pane-spawn-placement.test.ts": 473, "src/renderer/src/components/terminal-pane/terminal-pane-split-in-main.test.ts": 367, "src/renderer/src/components/terminal-pane/terminal-pane-split-request-routing.test.ts": 1631, @@ -10013,7 +9985,6 @@ "src/renderer/src/hooks/automations-changed-event-attribution.test.ts": 2238, "src/renderer/src/hooks/client-workspace-view-report.test.ts": 42, "src/renderer/src/hooks/composer-branch-selection.test.ts": 50, - "src/renderer/src/hooks/composer-drop-failure-toast.test.ts": 111, "src/renderer/src/hooks/composer-drop-result.test.ts": 25, "src/renderer/src/hooks/composer-native-file-drop.test.ts": 62, "src/renderer/src/hooks/composer-state/attachment-drop-failure.test.tsx": 547, @@ -10100,7 +10071,6 @@ "src/renderer/src/hooks/runtime-client-events-sync.test.ts": 93, "src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts": 56, "src/renderer/src/hooks/shortcut-label-cache.test.tsx": 1690, - "src/renderer/src/hooks/structured-session-completion-focus.test.ts": 1955, "src/renderer/src/hooks/unpaired-device-auth-notification.test.ts": 28, "src/renderer/src/hooks/use-audio-capture.capture-loss.test.ts": 258, "src/renderer/src/hooks/use-bundled-skill-install.test.tsx": 322, @@ -10194,7 +10164,6 @@ "src/renderer/src/hooks/useVirtualizedScrollAnchor.test.ts": 47, "src/renderer/src/hooks/useVirtualizedScrollAnchor.test.tsx": 326, "src/renderer/src/hooks/useWindowsTerminalCapabilityOwnerKey.test.tsx": 363, - "src/renderer/src/hooks/viewport-size-change-listener.test.ts": 26, "src/renderer/src/hooks/virtualized-hidden-row-measurement.test.ts": 139, "src/renderer/src/hooks/worktree-change-refresh-queue.test.ts": 38, "src/renderer/src/hooks/worktree-head-identity-apply.test.ts": 50, @@ -11212,7 +11181,6 @@ "src/renderer/src/ssh/ssh-connect-verb.test.ts": 44, "src/renderer/src/ssh/ssh-host-node-download-copy.test.ts": 1426, "src/renderer/src/startup/active-workspace-ssh-targets.test.ts": 58, - "src/renderer/src/startup/ssh-startup-reconnect.test.ts": 29, "src/renderer/src/startup/startup-degraded-recovery.test.ts": 427, "src/renderer/src/startup/startup-ssh-connection-restore.test.ts": 74, "src/renderer/src/startup/startup-web-host-unreachable.test.ts": 97, @@ -11337,7 +11305,6 @@ "src/renderer/src/store/slices/editor-recently-closed-tabs.test.ts": 1318, "src/renderer/src/store/slices/editor-rekey-open-files.test.ts": 1484, "src/renderer/src/store/slices/editor-remote-branch-actions.test.ts": 782, - "src/renderer/src/store/slices/editor-rich-markdown-size-override.test.ts": 674, "src/renderer/src/store/slices/editor-right-sidebar-state.test.ts": 1595, "src/renderer/src/store/slices/editor-session-duplicate-restore.test.ts": 1596, "src/renderer/src/store/slices/editor-set-active-file-guard.test.ts": 611, diff --git a/config/scripts/vitest-node-runtime-files.mjs b/config/scripts/vitest-node-runtime-files.mjs index 94103e0dd7f..d1b8aba1b10 100644 --- a/config/scripts/vitest-node-runtime-files.mjs +++ b/config/scripts/vitest-node-runtime-files.mjs @@ -206,7 +206,6 @@ const NODE_RUNTIME_INCLUDE = [ // Real fs.watch file bindings; Bun's watcher is not the one Electron runs. 'src/main/ipc/rebinding-file-watch.test.ts', 'src/main/ipc/parcel-watcher-shallow-file-subscription.test.ts', - 'src/main/ipc/runtime-environments/runtime-environment-transport-routing-tailscale-hint.test.ts', 'src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx', 'src/main/claude/claude-agent-sdk-contract-pins.test.ts', 'config/scripts/profile-state-worker-smoke.test.mjs', diff --git a/src/cli/cli-exit-code.test.ts b/src/cli/cli-exit-code.test.ts deleted file mode 100644 index 48fab1ed31a..00000000000 --- a/src/cli/cli-exit-code.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { cliErrorExitCode } from './cli-exit-code' -import { RuntimeClientError } from './runtime/types' - -describe('cliErrorExitCode', () => { - it('gives plugin commands distinct exit codes for invalid plugins and pending approval', () => { - const plugin = ['plugin', 'dev', 'load'] - expect(cliErrorExitCode(new RuntimeClientError('plugin_invalid', 'x'), plugin)).toBe(2) - expect(cliErrorExitCode(new RuntimeClientError('approval_required', 'x'), plugin)).toBe(3) - expect(cliErrorExitCode(new RuntimeClientError('approval_stale', 'x'), plugin)).toBe(3) - expect(cliErrorExitCode(new RuntimeClientError('runtime_unavailable', 'x'), plugin)).toBe(1) - expect(cliErrorExitCode(new Error('boom'), plugin)).toBe(1) - }) - - it('keeps every other command on exit code 1', () => { - expect( - cliErrorExitCode(new RuntimeClientError('approval_required', 'x'), ['worktree', 'list']) - ).toBe(1) - }) -}) diff --git a/src/cli/handlers/plugin-runtime.test.ts b/src/cli/handlers/plugin-runtime.test.ts deleted file mode 100644 index bfd2643f790..00000000000 --- a/src/cli/handlers/plugin-runtime.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { approvalRerunCommand } from './plugin-runtime' - -describe('approvalRerunCommand', () => { - it('re-runs the exact command with only the approve flag replaced', () => { - expect( - approvalRerunCommand( - ['plugin', 'dev', 'load', '/tmp/my plugin', '--approve', 'ap1-old', '--json'], - 'ap1-new' - ) - ).toBe( - `orca plugin dev load ${process.platform === 'win32' ? '"/tmp/my plugin"' : "'/tmp/my plugin'"} --json --approve ap1-new` - ) - expect(approvalRerunCommand(['plugin', 'enable', 'acme.x', '--approve=ap1-a'], 'ap1-b')).toBe( - 'orca plugin enable acme.x --approve ap1-b' - ) - }) -}) diff --git a/src/main/browser/browser-manager-viewport-crashed-guest.test.ts b/src/main/browser/browser-manager-viewport-crashed-guest.test.ts deleted file mode 100644 index 54942862590..00000000000 --- a/src/main/browser/browser-manager-viewport-crashed-guest.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - appGetPathMock: vi.fn(() => '/downloads'), - shellOpenExternalMock: vi.fn(), - browserWindowFromWebContentsMock: vi.fn(), - menuBuildFromTemplateMock: vi.fn(), - guestOffMock: vi.fn(), - guestOnMock: vi.fn(), - guestSetBackgroundThrottlingMock: vi.fn(), - guestSetWindowOpenHandlerMock: vi.fn(), - guestOpenDevToolsMock: vi.fn(), - webContentsFromIdMock: vi.fn(), - screenGetCursorScreenPointMock: vi.fn(() => ({ x: 0, y: 0 })), - openPopupWithOriginBarMock: vi.fn(), - processUserAgent: - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36' -})) - -vi.mock('electron', () => ({ - app: { getPath: mocks.appGetPathMock }, - BrowserWindow: { fromWebContents: mocks.browserWindowFromWebContentsMock }, - clipboard: { writeText: vi.fn() }, - shell: { openExternal: mocks.shellOpenExternalMock }, - Menu: { buildFromTemplate: mocks.menuBuildFromTemplateMock }, - screen: { getCursorScreenPoint: mocks.screenGetCursorScreenPointMock }, - webContents: { fromId: mocks.webContentsFromIdMock } -})) -vi.mock('./popup-origin-bar-window', () => ({ - openPopupWithOriginBar: mocks.openPopupWithOriginBarMock -})) -vi.mock('./browser-process-user-agent', () => ({ - getBrowserProcessUserAgentIdentity: () => ({ mode: 'clean', userAgent: mocks.processUserAgent }) -})) - -import { browserManager } from './browser-manager' -import { - rendererWebContentsId, - resetBrowserManagerMocks, - resetBrowserManagerState -} from './browser-manager-test-harness' -import { createViewportGuestFactory } from './browser-manager-viewport-test-fixtures' - -const makeGuest = createViewportGuestFactory(mocks) -const PHONE = { width: 375, height: 667, deviceScaleFactor: 2, mobile: true } as const - -const metricsWrites = (sendCommand: ReturnType): unknown[][] => - sendCommand.mock.calls.filter(([method]) => method === 'Emulation.setDeviceMetricsOverride') - -describe('browserManager viewport on a guest whose renderer crashed', () => { - beforeEach(() => { - resetBrowserManagerMocks(mocks) - resetBrowserManagerState() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - - it('never resizes the dead guest, and applies the preset once the page reloads', async () => { - const { guest, debuggerSendCommand, setRendererCrashed } = makeGuest(42501) - mocks.webContentsFromIdMock.mockReturnValue(guest) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the viewport fixture implements every WebContents member these paths touch. - browserManager.attachGuestPolicies(guest as never) - browserManager.registerGuest({ - browserPageId: 'tab-crashed', - webContentsId: 42501, - rendererWebContentsId - }) - - // Device-metrics writes against a crashed renderer can crash main. - setRendererCrashed(true) - await expect(browserManager.setViewportOverride('tab-crashed', PHONE)).resolves.toBe(false) - expect(metricsWrites(debuggerSendCommand)).toEqual([]) - - setRendererCrashed(false) - await expect(browserManager.setViewportOverride('tab-crashed', PHONE)).resolves.toBe(true) - expect(metricsWrites(debuggerSendCommand)).toEqual([ - ['Emulation.setDeviceMetricsOverride', PHONE] - ]) - }) -}) diff --git a/src/main/codex-accounts/runtime-home-restart-stopped-distro.test.ts b/src/main/codex-accounts/runtime-home-restart-stopped-distro.test.ts deleted file mode 100644 index ee44ae2ffee..00000000000 --- a/src/main/codex-accounts/runtime-home-restart-stopped-distro.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { CodexManagedAccount } from '../../shared/managed-account-types' -import type { CodexAccountSelectionTarget } from './runtime-selection' -import { createSettings } from './runtime-home-settings-test-fixtures' -import { - createStore, - setupRuntimeHomeTest, - teardownRuntimeHomeTest, - testState -} from './runtime-home-service-test-harness' - -const { isWslDistroRunningMock } = vi.hoisted(() => ({ - isWslDistroRunningMock: vi.fn<(distro: string) => Promise>() -})) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -vi.mock('../wsl-background-distro-gate', () => ({ - isWslDistroRunning: isWslDistroRunningMock -})) - -function wslAccount(id: string, distro: string): CodexManagedAccount { - return { - id, - email: `${id}@example.com`, - managedHomePath: `\\\\wsl.localhost\\${distro}\\home\\user\\.codex-${id}`, - managedHomeRuntime: 'wsl', - wslDistro: distro, - createdAt: 1, - updatedAt: 1, - lastAuthenticatedAt: 1 - } -} - -describe('Codex WSL auth preservation before restart', () => { - const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') - - beforeEach(() => { - setupRuntimeHomeTest() - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - isWslDistroRunningMock.mockImplementation(async (distro) => distro === 'Ubuntu') - }) - - afterEach(() => { - if (originalPlatform) { - Object.defineProperty(process, 'platform', originalPlatform) - } - teardownRuntimeHomeTest() - }) - - it('drains only running distros so a restart never boots a stopped one', async () => { - const { CodexRuntimeHomeService } = await import('./runtime-home-service') - const drained: (string | null | undefined)[] = [] - class DrainRecorder extends CodexRuntimeHomeService { - protected override startLegacyWslAuthDrain( - target: CodexAccountSelectionTarget - ): Promise { - drained.push(target.wslDistro) - return Promise.resolve() - } - } - const store = createStore( - createSettings({ - codexManagedAccounts: [wslAccount('a', 'Ubuntu'), wslAccount('b', 'Debian')], - activeCodexManagedAccountId: null, - activeCodexManagedAccountIdsByRuntime: { host: null, wsl: { Ubuntu: 'a', Debian: 'b' } } - }) - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the harness store implements the subset the service reads. - const service = new DrainRecorder(store as never) - - await service.syncActiveWslSelectionsBeforeRestart() - - expect(drained).toEqual(['Ubuntu']) - expect(isWslDistroRunningMock).toHaveBeenCalledWith('Debian') - }) -}) diff --git a/src/main/computer/computer-provider-lifecycle.test.ts b/src/main/computer/computer-provider-lifecycle.test.ts deleted file mode 100644 index 9ee5fbf70b7..00000000000 --- a/src/main/computer/computer-provider-lifecycle.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { ComputerProviderLifecycle } from './computer-provider-lifecycle' - -function provider(name: string) { - return { - name, - capabilities: vi.fn(), - listApps: vi.fn(), - listWindows: vi.fn(), - snapshot: vi.fn(), - action: vi.fn(), - shutdown: vi.fn() - } -} - -describe('ComputerProviderLifecycle', () => { - it('rechecks macOS provider availability after an initial miss', () => { - const macProvider = provider('mac') - const shouldUseMacOSNativeProvider = vi.fn().mockReturnValueOnce(false).mockReturnValue(true) - const lifecycle = new ComputerProviderLifecycle({ - shouldUseMacOSNativeProvider, - createMacOSNativeProvider: vi.fn(() => macProvider as never), - shouldUseDesktopScriptProvider: vi.fn(() => false), - createDesktopScriptProvider: vi.fn() - }) - - expect(lifecycle.current('darwin')).toBeNull() - expect(lifecycle.current('darwin')).toBe(macProvider) - expect(shouldUseMacOSNativeProvider).toHaveBeenCalledTimes(2) - }) - - it('caches an available provider and shuts it down', () => { - const macProvider = provider('mac') - const createMacOSNativeProvider = vi.fn(() => macProvider as never) - const lifecycle = new ComputerProviderLifecycle({ - shouldUseMacOSNativeProvider: vi.fn(() => true), - createMacOSNativeProvider, - shouldUseDesktopScriptProvider: vi.fn(() => false), - createDesktopScriptProvider: vi.fn() - }) - - expect(lifecycle.current('darwin')).toBe(macProvider) - expect(lifecycle.current('darwin')).toBe(macProvider) - expect(createMacOSNativeProvider).toHaveBeenCalledTimes(1) - - lifecycle.shutdown() - - expect(macProvider.shutdown).toHaveBeenCalledTimes(1) - }) - - it('uses the desktop script provider on Linux when available', () => { - const desktopProvider = provider('desktop') - const lifecycle = new ComputerProviderLifecycle({ - shouldUseMacOSNativeProvider: vi.fn(() => false), - createMacOSNativeProvider: vi.fn(), - shouldUseDesktopScriptProvider: vi.fn(() => true), - createDesktopScriptProvider: vi.fn(() => desktopProvider as never) - }) - - expect(lifecycle.current('linux')).toBe(desktopProvider) - }) - - it('shuts down the desktop script provider', () => { - const desktopProvider = provider('desktop') - const lifecycle = new ComputerProviderLifecycle({ - shouldUseMacOSNativeProvider: vi.fn(() => false), - createMacOSNativeProvider: vi.fn(), - shouldUseDesktopScriptProvider: vi.fn(() => true), - createDesktopScriptProvider: vi.fn(() => desktopProvider as never) - }) - - expect(lifecycle.current('linux')).toBe(desktopProvider) - - lifecycle.shutdown() - - expect(desktopProvider.shutdown).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/crash-reporting/appimage-crashpad-handler-exit.test.ts b/src/main/crash-reporting/appimage-crashpad-handler-exit.test.ts deleted file mode 100644 index ff866ac6b22..00000000000 --- a/src/main/crash-reporting/appimage-crashpad-handler-exit.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import type * as fs from 'node:fs' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { resolveAppImageRuntimeIdentity } from '../appimage-runtime-identity' -import { installAppImageCrashpadHandlerExit } from './appimage-crashpad-handler-exit' - -vi.mock('../appimage-runtime-identity', () => ({ - resolveAppImageRuntimeIdentity: vi.fn() -})) - -const MOUNT = '/tmp/.mount_Orca-abc123' -const PROC_EXECUTABLES: Record = { - '40': `${MOUNT}/chrome_crashpad_handler`, - '41': `${MOUNT}/chrome_crashpad_handler`, - '42': `${MOUNT}/orca-ide`, - '43': '/tmp/.mount_Orca-zzz999/chrome_crashpad_handler', - '44': '/chrome_crashpad_handler' -} - -vi.mock('node:fs', async (importOriginal) => ({ - ...(await importOriginal()), - readdirSync: vi.fn(() => [...Object.keys(PROC_EXECUTABLES), '45', 'self']), - readlinkSync: vi.fn((path: string) => { - const executable = PROC_EXECUTABLES[path.split('/')[2]] - if (!executable) { - throw Object.assign(new Error('EACCES'), { code: 'EACCES' }) - } - return executable - }), - // Only the FUSE mount root sits on its own device. - statSync: vi.fn((path: string) => ({ dev: path === MOUNT ? 2 : 1 })) -})) - -describe('installAppImageCrashpadHandlerExit', () => { - const originalExecPath = process.execPath - - afterEach(() => { - process.execPath = originalExecPath - vi.restoreAllMocks() - }) - - function installExitHook( - isAppImage: boolean, - execPath = `${MOUNT}/orca-ide` - ): (() => void) | undefined { - process.execPath = execPath - vi.mocked(resolveAppImageRuntimeIdentity).mockReturnValue( - isAppImage ? { appImagePath: '/home/u/orca-linux.AppImage' } : null - ) - const once = vi.spyOn(process, 'once').mockReturnValue(process) - installAppImageCrashpadHandlerExit() - return once.mock.calls.find(([event]) => event === 'exit')?.[1] - } - - it('SIGKILLs only this launch handler, surviving one that already exited', () => { - const kill = vi.spyOn(process, 'kill').mockImplementation((pid) => { - if (pid === 40) { - throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' }) - } - return true - }) - - installExitHook(true)?.() - - expect(kill.mock.calls).toEqual([ - [40, 'SIGKILL'], - [41, 'SIGKILL'] - ]) - }) - - // Installed deb/rpm handler binaries are shared across launches and must never match. - it('does not hook exit outside a validated AppImage', () => { - expect(installExitHook(false)).toBeUndefined() - }) - - it('does not hook exit under extract-and-run, whose dir is shared across launches', () => { - expect(installExitHook(true, '/tmp/appimage_extracted_0123abcd/orca-ide')).toBeUndefined() - }) -}) diff --git a/src/main/daemon/daemon-pty-adapter-steady-state-compat.test.ts b/src/main/daemon/daemon-pty-adapter-steady-state-compat.test.ts deleted file mode 100644 index 3c3847ea0ad..00000000000 --- a/src/main/daemon/daemon-pty-adapter-steady-state-compat.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { DaemonPtyAdapter } from './daemon-pty-adapter' -import { COMPLETION_PROCESS_INSPECTION_PROTOCOL_VERSION, PROTOCOL_VERSION } from './types' - -type ClientInternals = { - client: { request: ReturnType; disconnect: ReturnType } -} - -function createAdapter( - protocolVersion: number, - request: ReturnType -): DaemonPtyAdapter { - const adapter = new DaemonPtyAdapter({ - socketPath: '/tmp/orca-steady-state-compat.sock', - tokenPath: '/tmp/orca-steady-state-compat.token', - protocolVersion - }) - ;(adapter as unknown as ClientInternals).client = { request, disconnect: vi.fn() } - return adapter -} - -describe('steadyState across daemon versions', () => { - it('sends steadyState as an additive optional field on the existing inspectProcess request', async () => { - const request = vi.fn(async () => ({ foregroundProcess: 'claude', hasChildProcesses: true })) - const adapter = createAdapter(PROTOCOL_VERSION, request) - await adapter.inspectProcess('sess-a', { steadyState: true }) - expect(request).toHaveBeenCalledWith('inspectProcess', { - sessionId: 'sess-a', - steadyState: true - }) - adapter.dispose() - }) - - it('omits the field entirely when not requested, so the wire is byte-identical to before', async () => { - const request = vi.fn(async () => ({ foregroundProcess: null, hasChildProcesses: false })) - const adapter = createAdapter(PROTOCOL_VERSION, request) - await adapter.inspectProcess('sess-a', { expectedIncarnationId: 'inc-1', steadyState: false }) - expect(request).toHaveBeenCalledWith('inspectProcess', { - sessionId: 'sess-a', - expectedIncarnationId: 'inc-1' - }) - adapter.dispose() - }) - - it('an old daemon that ignores steadyState still answers with the full-capture shape, and the client accepts it', async () => { - const oldDaemonAnswer = { - foregroundProcess: 'claude', - hasChildProcesses: true, - foregroundProcessEvidence: { - verdict: 'live', - processName: 'claude', - authorityGeneration: 'gen', - observationEpoch: 1, - capturedAgeMs: 0, - ptyId: 'sess-a', - ptyIncarnationId: 'inc-1' - } - } - const request = vi.fn(async () => oldDaemonAnswer) - const adapter = createAdapter(COMPLETION_PROCESS_INSPECTION_PROTOCOL_VERSION, request) - await expect(adapter.inspectProcess('sess-a', { steadyState: true })).resolves.toEqual( - oldDaemonAnswer - ) - adapter.dispose() - }) - - it('a pre-inspection daemon never sees the field: the client composes from getForegroundProcess as before', async () => { - const request = vi.fn(async () => ({ foregroundProcess: 'codex' })) - const adapter = createAdapter(COMPLETION_PROCESS_INSPECTION_PROTOCOL_VERSION - 1, request) - await expect(adapter.inspectProcess('sess-a', { steadyState: true })).resolves.toEqual({ - foregroundProcess: 'codex', - hasChildProcesses: true - }) - expect(request).toHaveBeenCalledWith('getForegroundProcess', { sessionId: 'sess-a' }) - adapter.dispose() - }) -}) diff --git a/src/main/ipc/pty/wsl-terminal-spawn.test.ts b/src/main/ipc/pty/wsl-terminal-spawn.test.ts deleted file mode 100644 index d801bfaf487..00000000000 --- a/src/main/ipc/pty/wsl-terminal-spawn.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { isWslTerminalSpawn } from './wsl-terminal-spawn' - -const platform = process.platform -afterEach(() => { - Object.defineProperty(process, 'platform', { value: platform }) -}) - -describe('isWslTerminalSpawn', () => { - it('is a WSL shell, or (on Windows) a folder under a WSL share', () => { - expect(isWslTerminalSpawn('wsl.exe', 'C:\\repo')).toBe(true) - Object.defineProperty(process, 'platform', { value: 'win32' }) - expect(isWslTerminalSpawn(undefined, '\\\\wsl.localhost\\Ubuntu\\home\\u')).toBe(true) - expect(isWslTerminalSpawn(undefined, '\\\\wsl$\\Ubuntu\\home\\u')).toBe(true) - }) - - it('is not a native shell in a Windows folder, or a spawn with no folder', () => { - Object.defineProperty(process, 'platform', { value: 'win32' }) - expect(isWslTerminalSpawn('powershell.exe', 'C:\\repo')).toBe(false) - expect(isWslTerminalSpawn(undefined, null)).toBe(false) - expect(isWslTerminalSpawn(undefined, undefined)).toBe(false) - }) -}) diff --git a/src/main/ipc/repos/repo-creation-git-availability.test.ts b/src/main/ipc/repos/repo-creation-git-availability.test.ts deleted file mode 100644 index ffb4e0db43a..00000000000 --- a/src/main/ipc/repos/repo-creation-git-availability.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** Only failure to start proves Git absent; other failures must reach the renderer as unknown. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() })) - -vi.mock('electron', () => ({ ipcMain: { handle: vi.fn() } })) -vi.mock('../../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../../repo-icon-autodetect', () => ({ - detectRepoIconAndUpstream: vi.fn(async () => ({})) -})) -vi.mock('../../worktree-root-preparation', () => ({ - prepareLocalWorktreeRootForRepo: vi.fn(async () => {}) -})) -vi.mock('../registered-worktree-roots-cache', () => ({ - invalidateAuthorizedRootsCache: vi.fn(), - invalidateAuthorizedRootsCacheForRepo: vi.fn() -})) -vi.mock('./repo-added-telemetry', () => ({ emitRepoAdded: vi.fn() })) -vi.mock('./repos-changed-notification', () => ({ notifyReposChanged: vi.fn() })) -vi.mock('./local-repo-registration', () => ({ addLocalRepoFromPath: vi.fn() })) - -import { probeLocalGitAvailability } from './repo-creation-handlers' - -describe('repos:isGitAvailable', () => { - beforeEach(() => { - gitExecFileAsyncMock.mockReset() - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('answers true when git reports its version', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git version 2.25.1\n', stderr: '' }) - await expect(probeLocalGitAvailability()).resolves.toBe(true) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['--version'], { - cwd: process.cwd(), - timeout: 1500 - }) - }) - - it('answers false only when the spawn itself found no binary', async () => { - gitExecFileAsyncMock.mockRejectedValue( - Object.assign(new Error('spawn git ENOENT'), { code: 'ENOENT', syscall: 'spawn git' }) - ) - await expect(probeLocalGitAvailability()).resolves.toBe(false) - }) - - it('rejects an ENOENT when the working directory disappeared', async () => { - const missingCwd = `${process.cwd()}-missing` - vi.spyOn(process, 'cwd').mockReturnValue(missingCwd) - gitExecFileAsyncMock.mockRejectedValue( - Object.assign(new Error('spawn git ENOENT'), { code: 'ENOENT', syscall: 'spawn git' }) - ) - - await expect(probeLocalGitAvailability()).rejects.toThrow('spawn git ENOENT') - }) - - it('rejects a non-spawn ENOENT rather than reporting no Git', async () => { - gitExecFileAsyncMock.mockRejectedValue( - Object.assign(new Error('open config ENOENT'), { code: 'ENOENT', syscall: 'open' }) - ) - - await expect(probeLocalGitAvailability()).rejects.toThrow('open config ENOENT') - }) - - it('rejects on the timeout rather than reporting no git', async () => { - gitExecFileAsyncMock.mockRejectedValue(new Error('git --version timed out after 1500ms')) - await expect(probeLocalGitAvailability()).rejects.toThrow('timed out') - }) - - it('rejects when git runs and fails', async () => { - gitExecFileAsyncMock.mockRejectedValue( - Object.assign(new Error('fatal: detected dubious ownership'), { code: 128 }) - ) - await expect(probeLocalGitAvailability()).rejects.toThrow('dubious ownership') - }) -}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-transport-routing-tailscale-hint.test.ts b/src/main/ipc/runtime-environments/runtime-environment-transport-routing-tailscale-hint.test.ts deleted file mode 100644 index 7fa7de63945..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-transport-routing-tailscale-hint.test.ts +++ /dev/null @@ -1,83 +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 { generateKeyPair, publicKeyToBase64 } from '../../../shared/e2ee-crypto' -import { encodePairingOffer, type PairingOffer } from '../../../shared/pairing' -import { addEnvironmentFromPairingCode } from '../../../shared/runtime-environment-store' -import { - callRuntimeEnvironment, - subscribeRuntimeEnvironment -} from './runtime-environment-transport-routing' -import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe' -import { resetSharedControlSupport } from './runtime-environment-shared-control-support' - -// Exercise real WebSocket failure paths: status returns ok:false while in-use calls reject. - -vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) - -let userDataPath: string - -function seedEnvironment(name: string, endpoint: string): string { - // Use a valid key so failure occurs at socket connection, not key parsing. - const keyPair = generateKeyPair() - const offer: PairingOffer = { - v: 2, - endpoint, - deviceToken: 'a'.repeat(48), - publicKeyB64: publicKeyToBase64(keyPair.publicKey) - } - const environment = addEnvironmentFromPairingCode(userDataPath, { - name, - pairingCode: encodePairingOffer(offer) - }) - return environment.id -} - -beforeEach(() => { - userDataPath = mkdtempSync(join(tmpdir(), 'orca-tailscale-hint-')) -}) - -afterEach(() => { - resetSharedControlSupport() - rmSync(userDataPath, { recursive: true, force: true }) -}) - -describe('Tailscale hint on remote runtime connection failure', () => { - it('recommends Tailscale on the settings status probe for a non-tailnet endpoint', async () => { - const id = seedEnvironment('lan-host', 'ws://127.0.0.1:9') - const response = await getRuntimeEnvironmentStatus(userDataPath, id, 1000) - expect(response.ok).toBe(false) - if (response.ok === false) { - expect(response.error.message).toContain('connect both devices to Tailscale') - expect(response.error.message).toContain('https://tailscale.com/download') - } - }) - - it('gives tailnet-specific guidance on the status probe for a Tailscale endpoint', async () => { - const id = seedEnvironment('ts-host', 'ws://100.64.0.1:9') - const response = await getRuntimeEnvironmentStatus(userDataPath, id, 800) - expect(response.ok).toBe(false) - if (response.ok === false) { - expect(response.error.message).toContain('Funnel reverted to tailnet-only') - expect(response.error.message).not.toContain('https://tailscale.com/download') - } - }) - - it('augments the thrown error for in-use calls (the toast path)', async () => { - const id = seedEnvironment('lan-host', 'ws://127.0.0.1:9') - await expect(callRuntimeEnvironment(userDataPath, id, 'files.read', {}, 1000)).rejects.toThrow( - /connect both devices to Tailscale/ - ) - }) - - it('augments a subscription that fails to connect initially', async () => { - const id = seedEnvironment('lan-host', 'ws://127.0.0.1:9') - await expect( - subscribeRuntimeEnvironment(userDataPath, id, 'files.watch', {}, 1000, { - onEvent: () => {}, - onClose: () => {} - }) - ).rejects.toThrow(/connect both devices to Tailscale/) - }) -}) diff --git a/src/main/ipc/ssh/ssh-managed-host-port-forward-lifecycle.test.ts b/src/main/ipc/ssh/ssh-managed-host-port-forward-lifecycle.test.ts deleted file mode 100644 index 6642fd2ada3..00000000000 --- a/src/main/ipc/ssh/ssh-managed-host-port-forward-lifecycle.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const h = vi.hoisted(() => ({ - restore: vi.fn(async (_targetId: string) => {}), - forgetRestoreState: vi.fn(), - removeAllForwards: vi.fn(async () => {}), - closeManagedTunnels: vi.fn(async () => {}), - disconnect: vi.fn(async () => {}), - getState: vi.fn(() => ({ targetId: 't1', status: 'connected', error: null, reconnectAttempt: 0 })) -})) - -vi.mock('../../managed-server/lifecycle/orcad-managed-tunnel', () => ({ - closeOrcadManagedTunnel: vi.fn(async () => {}), - closeOrcadManagedTunnelsForTarget: h.closeManagedTunnels -})) -vi.mock('./ssh-managed-port-forward-restore', () => ({ - restoreManagedHostPortForwards: h.restore, - forgetPortForwardRestoreState: h.forgetRestoreState -})) -vi.mock('./ssh-ipc-context', () => ({ - connectionManager: { getState: h.getState, disconnect: h.disconnect, getConnection: vi.fn() }, - currentRuntime: null, - getCurrentMainWindow: () => null, - persistedStore: null, - portForwardManager: { removeAllForwards: h.removeAllForwards } -})) -vi.mock('../../ssh/targets/ssh-target-registry', async (importOriginal) => ({ - ...(await importOriginal>()), - getSshTargetRegistryStore: () => null -})) - -const { handleSshConnectionStateChange } = await import('./ssh-connection-state-callbacks') -const { disconnectRegisteredSshTarget } = await import('./ssh-session-teardown') -const { connectInFlight } = await import('./ssh-connect-attempt-registry') -const { getSshProviderAuthority } = await import('../../ssh/ssh-provider-authority') -const { clearSshHostServerStatus, setSshHostServerStatus } = - await import('../../ssh/ssh-host-server-status') - -const connected = { targetId: 't1', status: 'connected', error: null, reconnectAttempt: 0 } as const - -describe('saved port forwards on a managed host', () => { - beforeEach(() => { - vi.clearAllMocks() - clearSshHostServerStatus('t1') - }) - - it('restores them when the managed host transport reconnects on its own', () => { - setSshHostServerStatus('t1', { kind: 'managed', environmentId: 'env-1' }) - handleSshConnectionStateChange('t1', { ...connected, status: 'reconnecting' }) - expect(h.restore).not.toHaveBeenCalled() - handleSshConnectionStateChange('t1', connected) - expect(h.restore).toHaveBeenCalledWith('t1') - }) - - it('leaves an explicit connect to restore through its own publish', () => { - connectInFlight.set('t1', { - authority: getSshProviderAuthority('t1'), - promise: new Promise(() => {}) - }) - try { - handleSshConnectionStateChange('t1', connected) - expect(h.restore).not.toHaveBeenCalled() - } finally { - connectInFlight.delete('t1') - } - }) - - it('closes the local listeners on disconnect even though no relay session exists', async () => { - await disconnectRegisteredSshTarget('t1') - expect(h.removeAllForwards).toHaveBeenCalledWith('t1') - // A later connect is a fresh transport: no stale pacing or failures carry over. - expect(h.forgetRestoreState).toHaveBeenCalledWith('t1') - }) - - // Managed system-SSH tunnels run separate ssh -L processes; session disconnect alone leaves them alive. - it('closes the managed server tunnels the session carried', async () => { - await disconnectRegisteredSshTarget('t1') - expect(h.closeManagedTunnels).toHaveBeenCalledWith('t1') - }) -}) diff --git a/src/main/ipc/zcode-plan-credentials.test.ts b/src/main/ipc/zcode-plan-credentials.test.ts deleted file mode 100644 index 65d65f8a30a..00000000000 --- a/src/main/ipc/zcode-plan-credentials.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { registerZcodePlanCredentialsHandlers } from './zcode-plan-credentials' - -const mocks = vi.hoisted(() => ({ - handle: vi.fn(), - hasKey: vi.fn(() => false), - protection: vi.fn<() => 'sealed' | 'plaintext' | null>(() => null), - hasCli: vi.fn(() => false), - save: vi.fn(), - clear: vi.fn() -})) -vi.mock('electron', () => ({ ipcMain: { handle: mocks.handle } })) -vi.mock('../zcode/zcode-plan-api-key-store', () => ({ - hasZcodePlanApiKey: mocks.hasKey, - getZcodePlanApiKeyProtection: mocks.protection, - saveZcodePlanApiKey: mocks.save, - clearZcodePlanApiKey: mocks.clear, - API_KEY_ENVELOPE_PREFIX: 'zcode:', - getZcodePlanApiKeyPath: () => 'zcode-key-path' -})) -// Mocked files have no real readability; RPC tests cover that check. -vi.mock('../credentials/saved-credential-readability', () => ({ - savedCredentialUnreadable: () => undefined, - refuseCredentialSealedElsewhere: () => { - throw new Error('unused') - } -})) -vi.mock('../rate-limits/zcode-usage-fetcher', () => ({ hasZcodeCliPlanCredentials: mocks.hasCli })) - -function handler(channel: string) { - const registration = mocks.handle.mock.calls.find(([name]) => name === channel) - if (!registration) { - throw new Error('Handler missing') - } - return registration[1] -} - -describe('GLM credential IPC', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.hasKey.mockReturnValue(false) - mocks.hasCli.mockReturnValue(false) - mocks.protection.mockReturnValue(null) - registerZcodePlanCredentialsHandlers(null) - }) - - it('returns only presence and protection without exposing the key', () => { - mocks.hasKey.mockReturnValue(true) - mocks.hasCli.mockReturnValue(true) - mocks.protection.mockReturnValue('sealed') - expect(handler('zcodePlanCredentials:getStatus')()).toEqual({ - apiKeyConfigured: true, - zcodeCliConfigured: true, - apiKeyProtection: 'sealed', - apiKeyUnreadable: undefined - }) - }) - - it('validates an untyped IPC key before persistence', () => { - expect(() => handler('zcodePlanCredentials:saveApiKey')(null, 42)).toThrow('must be a string') - expect(mocks.save).not.toHaveBeenCalled() - }) - - it('saves and removes keys while returning status only', () => { - mocks.save.mockImplementationOnce(() => mocks.hasKey.mockReturnValue(true)) - mocks.clear.mockImplementationOnce(() => mocks.hasKey.mockReturnValue(false)) - expect(handler('zcodePlanCredentials:saveApiKey')(null, 'synthetic-key')).toEqual({ - apiKeyConfigured: true, - zcodeCliConfigured: false, - apiKeyProtection: null, - apiKeyUnreadable: undefined - }) - expect(handler('zcodePlanCredentials:clearApiKey')()).toEqual({ - apiKeyConfigured: false, - zcodeCliConfigured: false, - apiKeyProtection: null, - apiKeyUnreadable: undefined - }) - }) -}) diff --git a/src/main/jira/jira-search-abort.test.ts b/src/main/jira/jira-search-abort.test.ts deleted file mode 100644 index 52801aaf3a0..00000000000 --- a/src/main/jira/jira-search-abort.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { JiraClientForSite } from './authenticated-request' - -const { acquireMock, clearTokenMock, getClientsMock, isAuthErrorMock, jiraRequestMock } = - vi.hoisted(() => ({ - acquireMock: vi.fn().mockResolvedValue(undefined), - clearTokenMock: vi.fn(), - getClientsMock: vi.fn(), - isAuthErrorMock: vi.fn().mockReturnValue(false), - jiraRequestMock: vi.fn() - })) - -vi.mock('./jira-agile-fields', () => ({ - getAgileFieldIds: async () => ({}), - agileFieldIdList: () => [] -})) - -vi.mock('./request-queue', () => ({ - acquire: (...args: unknown[]) => acquireMock(...args), - release: vi.fn() -})) - -vi.mock('./authenticated-request', () => ({ - apiBasePath: () => '/rest/api/3', - jiraRequest: (...args: unknown[]) => jiraRequestMock(...args), - jiraRequestBinary: vi.fn(), - JiraApiError: class JiraApiError extends Error {} -})) - -vi.mock('./client', () => ({ - clearToken: (...args: unknown[]) => clearTokenMock(...args), - getClients: (...args: unknown[]) => getClientsMock(...args), - isAuthError: (...args: unknown[]) => isAuthErrorMock(...args) -})) - -function makeEntry(id: string): JiraClientForSite { - return { - site: { - id, - siteUrl: 'https://example.atlassian.net', - email: 'ada@example.com', - displayName: 'Example Jira', - accountId: 'account-1' - }, - authorization: 'Basic token' - } -} - -describe('Jira search abort', () => { - beforeEach(() => { - vi.clearAllMocks() - isAuthErrorMock.mockReturnValue(false) - acquireMock.mockResolvedValue(undefined) - }) - - it('threads the abort signal through the request pool to every site', async () => { - const controller = new AbortController() - getClientsMock.mockReturnValue([makeEntry('site-1'), makeEntry('site-2')]) - jiraRequestMock.mockResolvedValue({ issues: [] }) - const { searchIssues } = await import('./issues') - - await searchIssues('project = ALP', 20, 'all', controller.signal) - - expect(acquireMock).toHaveBeenCalledTimes(2) - expect(acquireMock.mock.calls[0]?.[0]).toBeInstanceOf(AbortSignal) - for (const call of jiraRequestMock.mock.calls) { - expect(call[2]?.signal).toBeInstanceOf(AbortSignal) - expect(JSON.parse(call[2].body).fields).not.toContain('description') - } - }) - - it('does not clear tokens when an abandoned search is aborted', async () => { - const controller = new AbortController() - controller.abort() - isAuthErrorMock.mockReturnValue(true) - getClientsMock.mockReturnValue([makeEntry('site-1')]) - jiraRequestMock.mockRejectedValueOnce(new Error('The operation was aborted')) - const { searchIssues } = await import('./issues') - - await expect(searchIssues('project = ALP', 20, 'site-1', controller.signal)).rejects.toThrow( - 'aborted' - ) - expect(clearTokenMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/macos-keychain/generic-password.test.ts b/src/main/macos-keychain/generic-password.test.ts deleted file mode 100644 index 604fd8b00bd..00000000000 --- a/src/main/macos-keychain/generic-password.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const execFileMock = vi.hoisted(() => vi.fn()) - -vi.mock('node:child_process', () => ({ execFile: execFileMock })) - -import { isKeychainNotFoundError, readKeychainPassword } from './generic-password' - -const originalPlatform = process.platform - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) -} - -function respond(stdout: string): void { - execFileMock.mockImplementation((_file, _args, _options, callback) => { - callback(null, stdout, '') - return { kill: vi.fn() } - }) -} - -function fail(error: unknown): void { - execFileMock.mockImplementation((_file, _args, _options, callback) => { - callback(error, '', '') - return { kill: vi.fn() } - }) -} - -beforeEach(() => { - execFileMock.mockReset() - setPlatform('darwin') -}) - -afterEach(() => { - setPlatform(originalPlatform) -}) - -describe('readKeychainPassword', () => { - it('returns the trimmed secret for a stored item', async () => { - respond(' secret-value\n') - await expect(readKeychainPassword('cursor-access-token', 'cursor-user')).resolves.toBe( - 'secret-value' - ) - expect(execFileMock.mock.calls[0]?.[1]).toEqual([ - 'find-generic-password', - '-s', - 'cursor-access-token', - '-a', - 'cursor-user', - '-w' - ]) - }) - - it('returns null rather than throwing when the item does not exist', async () => { - fail(Object.assign(new Error('The specified item could not be found'), { code: 44 })) - await expect(readKeychainPassword('svc', 'acct')).resolves.toBeNull() - }) - - it('rethrows a denied or locked keychain so callers can report it', async () => { - fail(new Error('User interaction is not allowed')) - await expect(readKeychainPassword('svc', 'acct')).rejects.toThrow( - 'User interaction is not allowed' - ) - }) - - it('never shells out off macOS', async () => { - setPlatform('win32') - await expect(readKeychainPassword('svc', 'acct')).resolves.toBeNull() - expect(execFileMock).not.toHaveBeenCalled() - }) -}) - -describe('isKeychainNotFoundError', () => { - it('recognizes the security(1) not-found signals', () => { - expect(isKeychainNotFoundError({ code: 44 })).toBe(true) - expect(isKeychainNotFoundError(new Error('The specified item could not be found'))).toBe(true) - expect(isKeychainNotFoundError(new Error('User interaction is not allowed'))).toBe(false) - }) -}) diff --git a/src/main/pty/windows-environment-path-main-loop.test.ts b/src/main/pty/windows-environment-path-main-loop.test.ts deleted file mode 100644 index fbe185479cc..00000000000 --- a/src/main/pty/windows-environment-path-main-loop.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - __resetPersistedWindowsPathCacheForTests, - readPersistedWindowsPathSegments -} from './windows-environment-path' -import { __setWindowsPathRegistryLoaderForTests } from './windows-path-registry-reader' - -const CREATE_PROCESS_DELAY_MS = 160 -const delayedExecFileSync = vi.hoisted(() => - vi.fn(() => { - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, CREATE_PROCESS_DELAY_MS) - return ' Path REG_EXPAND_SZ C:\\Delayed' - }) -) - -vi.mock('node:child_process', () => ({ - execFile: vi.fn(), - execFileSync: delayedExecFileSync -})) - -describe('persisted Windows PATH process creation', () => { - afterEach(() => { - __resetPersistedWindowsPathCacheForTests() - __setWindowsPathRegistryLoaderForTests() - delayedExecFileSync.mockClear() - }) - - async function measureMainLoopGap(run: () => T): Promise<{ - callMs: number - maxGapMs: number - result: T - }> { - let lastTick = performance.now() - let maxGapMs = 0 - const timer = setInterval(() => { - const now = performance.now() - maxGapMs = Math.max(maxGapMs, now - lastTick - 5) - lastTick = now - }, 5) - await new Promise((resolve) => setTimeout(resolve, 20)) - - const startedAt = performance.now() - const result = run() - const callMs = performance.now() - startedAt - await new Promise((resolve) => setTimeout(resolve, 20)) - clearInterval(timer) - return { callMs, maxGapMs, result } - } - - it('proves delayed process creation blocks while native registry reads create no process', async () => { - const legacy = await measureMainLoopGap(() => - readPersistedWindowsPathSegments({ - platform: 'win32', - env: { SystemRoot: 'C:\\Windows' }, - execFileSync: delayedExecFileSync as never - }) - ) - - expect(legacy.result).toEqual(['C:\\Delayed', 'C:\\Delayed']) - expect(delayedExecFileSync).toHaveBeenCalledTimes(2) - expect(legacy.callMs).toBeGreaterThanOrEqual(CREATE_PROCESS_DELAY_MS * 2) - expect(legacy.maxGapMs).toBeGreaterThanOrEqual(CREATE_PROCESS_DELAY_MS) - - __resetPersistedWindowsPathCacheForTests() - delayedExecFileSync.mockClear() - __setWindowsPathRegistryLoaderForTests(() => ({ - HK: { LM: 1, CU: 2 }, - getRegistryKey: (root) => ({ - Path: { type: 1, value: root === 1 ? 'C:\\Machine' : 'C:\\User' } - }) - })) - const native = readPersistedWindowsPathSegments({ - platform: 'win32', - env: { SystemRoot: 'C:\\Windows' } - }) - - expect(native).toEqual(['C:\\Machine', 'C:\\User']) - expect(delayedExecFileSync).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/renderer-browser-offscreen-epoch-ownership.test.ts b/src/main/runtime/renderer-browser-offscreen-epoch-ownership.test.ts deleted file mode 100644 index 25caeaf98ae..00000000000 --- a/src/main/runtime/renderer-browser-offscreen-epoch-ownership.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import './orca-runtime-test-lifecycle.spec' -import { expect, it, vi } from 'vitest' -import { OrcaRuntimeService, electronMocks } from './orca-runtime-test-mocks.spec' -import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' -import type { RuntimeMobileSessionTabsSnapshot } from '../../shared/runtime-types' - -it('does not publish unknown-owner offscreen rows into an unaccepted renderer epoch', () => { - const runtime = new OrcaRuntimeService(store) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Test harness mocks partial OffscreenBrowserBackend. - runtime.setOffscreenBrowserBackend({ closeTab: vi.fn(), ownsTab: () => true } as never) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Test harness mocks partial AgentBrowserBridge. - runtime.setAgentBrowserBridge({ - tabList: () => ({ - tabs: [ - { - browserPageId: 'offscreen-new', - title: 'Headless', - url: 'https://example.com/', - active: false - } - ] - }) - } as never) - const snapshot: RuntimeMobileSessionTabsSnapshot = { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-unaccepted', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - electronMocks.BrowserWindow.fromId.mockImplementation((id: number) => - id === 1 ? { isDestroyed: () => false } : null - ) - runtime.attachWindow(1) - runtime['mobileSessionTabsByWorktree'].set(TEST_WORKTREE_ID, snapshot) - runtime['acceptedRendererMobileSnapshotByWorktree'].delete(TEST_WORKTREE_ID) - runtime['reconcileHeadlessMobileSessionBrowserTabs'](TEST_WORKTREE_ID, snapshot) - expect(runtime['mobileSessionTabsByWorktree'].get(TEST_WORKTREE_ID)).toEqual(snapshot) -}) - -it('classifies headless rows added under the current unchanged renderer epoch', () => { - const runtime = new OrcaRuntimeService(store) - const tab = { - type: 'browser' as const, - id: 'offscreen-new', - browserWorkspaceId: 'offscreen-new', - browserPageId: 'offscreen-new', - title: 'Headless', - url: 'https://example.com/', - loading: false, - canGoBack: false, - canGoForward: false, - isActive: false - } - const snapshot: RuntimeMobileSessionTabsSnapshot = { - worktree: TEST_WORKTREE_ID, - publicationEpoch: 'renderer-accepted', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: null, - activeTabType: null, - tabs: [] - } - runtime['acceptedRendererMobileSnapshotByWorktree'].set(TEST_WORKTREE_ID, { - publicationEpoch: snapshot.publicationEpoch, - rendererVersion: 1, - rendererTabCount: 0, - rendererTabIdentityKeys: new Set() - }) - const epoch = runtime['getMobileSessionPublicationEpochAfterHeadlessBrowserClose'](snapshot) - expect(epoch).toBe(snapshot.publicationEpoch) - expect( - runtime['isHeadlessOwnedMobileBrowserTab']( - { ...snapshot, publicationEpoch: epoch, tabs: [tab] }, - tab - ) - ).toBe(true) -}) diff --git a/src/main/runtime/runtime-git-command-target.test.ts b/src/main/runtime/runtime-git-command-target.test.ts deleted file mode 100644 index 20faf452ada..00000000000 --- a/src/main/runtime/runtime-git-command-target.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -const { getStatus } = vi.hoisted(() => ({ getStatus: vi.fn() })) -vi.mock('../git/status', () => ({ getStatus })) - -import { ExecutionHostNotDispatchableError } from '../providers/execution-host-provider-dispatch' -import { createLocalGitProvider } from '../providers/local-git-provider' -import { SshHostNotServedError } from '../providers/ssh-host-not-served-error' -import { - localGitOptionsForTarget, - requireRuntimeGitProvider, - runtimeGitRouteForTarget, - type RuntimeGitTarget -} from './runtime-git-command-target' - -const worktree = { - id: 'wt-1', - repoId: 'repo-1', - path: '/srv/app', - git: { path: '/srv/app', branch: 'main', isBare: false, isMainWorktree: false } -} as unknown as RuntimeGitTarget['worktree'] - -function target(overrides: Partial): RuntimeGitTarget { - return { worktree, executionHostId: 'local', ...overrides } -} - -describe('runtime Git target routing', () => { - afterEach(() => { - getStatus.mockReset() - }) - - it('answers `local` with a provider bound to this worktree, built per call', async () => { - expect(runtimeGitRouteForTarget(target({}))).toEqual({ - kind: 'local', - createProvider: createLocalGitProvider - }) - const localTarget = target({ localGitOptions: { wslDistro: 'Ubuntu' } }) - expect(requireRuntimeGitProvider(localTarget)).not.toBe(requireRuntimeGitProvider(localTarget)) - - await requireRuntimeGitProvider(localTarget).getStatus('/srv/app') - expect(getStatus).toHaveBeenCalledWith('/srv/app', { - wslDistro: 'Ubuntu', - admissionTier: 'status' - }) - }) - - // Loss of contact is never evidence of locality (docs/reference/ssh-execution-boundary.md). - it('keeps an ssh host remote instead of degrading it to local', () => { - const route = runtimeGitRouteForTarget(target({ executionHostId: 'ssh:gone' })) - - expect(route).toEqual({ kind: 'ssh', connectionId: 'gone' }) - expect(() => requireRuntimeGitProvider(target({ executionHostId: 'ssh:gone' }))).toThrow( - SshHostNotServedError - ) - expect(getStatus).not.toHaveBeenCalled() - }) - - it('refuses a runtime host instead of routing it', () => { - expect(() => runtimeGitRouteForTarget(target({ executionHostId: 'runtime:env-a' }))).toThrow( - ExecutionHostNotDispatchableError - ) - expect(() => requireRuntimeGitProvider(target({ executionHostId: 'runtime:env-a' }))).toThrow( - ExecutionHostNotDispatchableError - ) - }) - - it('keeps WSL routing on the local host and off every other one', () => { - const localGitOptions = { wslDistro: 'Ubuntu' } - - expect(localGitOptionsForTarget(target({ localGitOptions }))).toEqual(localGitOptions) - expect( - localGitOptionsForTarget(target({ executionHostId: 'ssh:m4air', localGitOptions })) - ).toEqual({}) - expect( - localGitOptionsForTarget(target({ executionHostId: 'runtime:env-a', localGitOptions })) - ).toEqual({}) - }) -}) diff --git a/src/main/runtime/runtime-linear-read-commands.test.ts b/src/main/runtime/runtime-linear-read-commands.test.ts deleted file mode 100644 index c64e5888e97..00000000000 --- a/src/main/runtime/runtime-linear-read-commands.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type * as RuntimeLinearCommandDependencies from './runtime-linear-command-dependencies' - -const mocks = vi.hoisted(() => ({ listLinearIssues: vi.fn() })) - -vi.mock('./runtime-linear-command-dependencies', async (importOriginal) => ({ - ...(await importOriginal()), - listLinearIssues: mocks.listLinearIssues -})) - -import { RuntimeLinearReadCommands } from './runtime-linear-read-commands' - -function createCommands(): RuntimeLinearReadCommands { - return new RuntimeLinearReadCommands({ - runtimeAvailable: () => true, - showTerminal: async () => { - throw new Error('unused') - }, - resolveWorkspaceSelector: async () => { - throw new Error('unused') - }, - listResolvedWorktrees: async () => [], - setWorktreeMeta: () => {}, - emitClientEvent: () => {} - }) -} - -describe('RuntimeLinearReadCommands', () => { - it('reports truncated project results at the top level', async () => { - const commands = createCommands() - vi.spyOn(commands, 'linearListProjects').mockResolvedValue({ - items: [ - { id: 'project-1', name: 'One' }, - { id: 'project-2', name: 'Two' } - ], - hasMore: false, - errors: [] - } as never) - - await expect(commands.linearProjectListForAgents({ limit: 1 })).resolves.toMatchObject({ - projects: [{ id: 'project-1', name: 'One' }], - truncated: true, - meta: { hasMore: true, returned: 1 } - }) - }) - - it('reports issue truncation and priority labels at the top level', async () => { - mocks.listLinearIssues.mockResolvedValue({ - items: [ - { - id: 'issue-1', - identifier: 'ORCA-1', - title: 'Preserve result fields', - url: 'https://linear.app/orca/issue/ORCA-1', - state: null, - team: null, - project: null, - assignee: null, - priority: 2, - estimate: null, - dueDate: null, - updatedAt: '2026-08-29T00:00:00.000Z', - workspaceId: 'workspace-1', - workspaceName: 'Orca' - } - ], - hasMore: true, - errors: [] - }) - - await expect(createCommands().linearIssueListForAgents({ limit: 1 })).resolves.toMatchObject({ - issues: [{ identifier: 'ORCA-1', priority: 2, priorityLabel: 'high' }], - truncated: true, - meta: { hasMore: true, returned: 1 } - }) - }) -}) diff --git a/src/main/runtime/runtime-local-worktree-materialization.test.ts b/src/main/runtime/runtime-local-worktree-materialization.test.ts deleted file mode 100644 index c2c15196c42..00000000000 --- a/src/main/runtime/runtime-local-worktree-materialization.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ - createWorktreeCopiedPaths: vi.fn(), - createWorktreeLinkedPaths: vi.fn(), - createWorktreeSharedPaths: vi.fn(), - resolveWorktreeIncludePaths: vi.fn(async () => []), - resolveWorktreeSharedDirectories: vi.fn(async () => []) -})) - -vi.mock('../ipc/worktree-symlinks', () => ({ - createWorktreeCopiedPaths: mocks.createWorktreeCopiedPaths, - createWorktreeLinkedPaths: mocks.createWorktreeLinkedPaths, - createWorktreeSharedPaths: mocks.createWorktreeSharedPaths -})) -vi.mock('../git/worktree-include-file', () => ({ - resolveWorktreeIncludePaths: mocks.resolveWorktreeIncludePaths -})) -vi.mock('../git/worktree-shared-directories', () => ({ - resolveWorktreeSharedDirectories: mocks.resolveWorktreeSharedDirectories -})) - -import { materializeRuntimeLocalWorktree } from './runtime-local-worktree-materialization' -import { createWorktreeCreateTimingRecorder } from '../worktree-create-timing' -import type { HostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' - -describe('materializeRuntimeLocalWorktree', () => { - it('records lineage immediately after metadata and before filesystem setup', async () => { - const order: string[] = [] - mocks.createWorktreeLinkedPaths.mockImplementationOnce(async () => { - order.push('filesystem') - throw new Error('link failed') - }) - const store = { - getProjectHostSetups: () => [], - setWorktreeMeta: vi.fn((_target: HostWorktreeTarget, updates) => ({ - ...updates, - hostId: 'local' - })) - } - - await expect( - materializeRuntimeLocalWorktree({ - request: {}, - repo: { - id: 'repo-1', - path: '/repo', - displayName: 'Repo', - badgeColor: '#000000', - addedAt: 1, - symlinkPaths: ['node_modules'] - }, - store, - settings: { workspaceDir: '/worktrees', nestWorkspaces: true }, - created: { - path: '/worktrees/app', - head: 'abc123', - branch: 'feature/app', - isBare: false, - isMainWorktree: false - }, - remoteTrackingBase: null, - sparseDirectories: [], - checkoutExistingBranch: false, - baseBranch: 'main', - branchName: 'feature/app', - effectiveRequestedName: 'app', - effectiveSanitizedName: 'app', - localWorktreeGitOptions: {}, - onMetadataPersisted: () => { - order.push('metadata') - return null - }, - timing: createWorktreeCreateTimingRecorder() - } as never) - ).rejects.toThrow('link failed') - - expect(order).toEqual(['metadata', 'filesystem']) - }) -}) diff --git a/src/main/runtime/structured-worker-terminal-refusal.test.ts b/src/main/runtime/structured-worker-terminal-refusal.test.ts deleted file mode 100644 index 0368cde5bcc..00000000000 --- a/src/main/runtime/structured-worker-terminal-refusal.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../shared/agent-session-record.test-fixture' -import { agentSessionConversationView } from '../../shared/agent-session-conversation-view' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const hostRef: { current: unknown } = { current: null } - -vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => hostRef.current -})) - -const { structuredWorkerTerminalRefusal } = await import('./structured-worker-terminal-refusal') -const { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerIdentities, - structuredWorkerProcessIncarnation -} = await import('./structured-worker-identity') - -const SESSION_ID = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d' - -function installRecord(): void { - hostRef.current = { - deps: { - store: { - getConversation: (sessionId: string) => - agentSessionConversationView( - agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId, runtimeFence: 1 })) - ) - } - }, - hasSession: () => true - } -} - -function registerWorker(): string { - const handle = mintStructuredWorkerHandle() - structuredWorkerIdentities.register({ - handle, - sessionId: SESSION_ID, - agent: 'claude', - paneKey: mintStructuredWorkerPaneKey(SESSION_ID), - processIncarnation: structuredWorkerProcessIncarnation(SESSION_ID), - worktreeId: 'wt_1', - hostScope: { kind: 'local', hostId: 'local' } - }) - return handle -} - -describe('the refusal a terminal verb gives a structured worker handle', () => { - beforeEach(() => { - structuredWorkerIdentities.clear() - hostRef.current = null - }) - - it('says the handle is an agent session, not that it went stale', () => { - // A live structured handle has no terminal; stale would falsely suggest reminting it. - const handle = registerWorker() - installRecord() - const error = structuredWorkerTerminalRefusal(handle, null) - expect(error.message).not.toContain('terminal_handle_stale') - expect((error as { code?: string }).code).toBe('terminal_unsupported_for_agent_session') - }) - - it('points at the structured equivalents rather than just failing', () => { - const handle = registerWorker() - installRecord() - const message = structuredWorkerTerminalRefusal(handle, null).message - expect(message).toContain('orca terminal read') - expect(message).toContain('worker-read --source transcript') - expect(message).toContain('orca orchestration send') - }) - - it('keeps the stale error for a PTY handle, which really can go stale', () => { - expect(structuredWorkerTerminalRefusal('term_gone', null).message).toBe('terminal_handle_stale') - }) - - it('keeps the stale error for a session this runtime no longer owns', () => { - // Once the lease moves or the session is released the handle IS dead, and saying so is right. - registerWorker() - hostRef.current = null - expect(structuredWorkerTerminalRefusal('term_gone', null).message).toBe('terminal_handle_stale') - }) -}) diff --git a/src/main/runtime/terminal-agent-turn-news.test.ts b/src/main/runtime/terminal-agent-turn-news.test.ts deleted file mode 100644 index 89e990e449b..00000000000 --- a/src/main/runtime/terminal-agent-turn-news.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' -import type { AgentStatusIpcPayload } from '../../shared/agent-status-ipc-payload' -import type { AgentPhase, AgentTransition } from '../../shared/agent-transitions' -import { TerminalAgentTurnNews, type TerminalAgentTurnNewsDeps } from './terminal-agent-turn-news' - -const PANE = 'tab-1:11111111-1111-4111-8111-111111111111' -const WT = 'repo-1::/tmp/wt' - -function row(overrides: Partial): AgentStatusIpcPayload { - return { - state: 'working', - prompt: '', - agentType: 'claude', - paneKey: PANE, - connectionId: null, - receivedAt: 1, - stateStartedAt: 100, - ...overrides - } -} - -function moved( - from: AgentPhase, - to: AgentPhase, - transition: AgentTransition | null -): AgentPaneChange { - return { - kind: 'moved', - paneKey: PANE, - workspace: { worktreeId: WT, sshHostId: null }, - from, - to, - at: 1, - transition - } -} - -function news(current: { row: AgentStatusIpcPayload | null }, optIn: boolean) { - const readHookRow = vi.fn(() => current.row) - const deps: TerminalAgentTurnNewsDeps = { - readHookRow, - prepare: ({ row }) => row.state, - deliver: vi.fn(), - setTimer: () => ({ cancel: () => {} }), - ...(optIn ? { started: vi.fn(), stopped: vi.fn() } : {}) - } - return { turnNews: new TerminalAgentTurnNews(deps), deps, readHookRow } -} - -describe('TerminalAgentTurnNews opt-ins', () => { - it('tells a turn start, and a turn its user stopped, only to a listener that opted in', () => { - const current: { row: AgentStatusIpcPayload | null } = { row: row({ state: 'working' }) } - const { turnNews, deps } = news(current, true) - turnNews.observe(moved('rest', 'working', 'prompt-submitted')) - expect(deps.started).toHaveBeenCalledWith({ paneKey: PANE, worktreeId: WT, row: current.row }) - current.row = row({ state: 'done', interrupted: true }) - turnNews.observe(moved('working', 'rest', null)) - expect(deps.stopped).toHaveBeenCalledWith({ paneKey: PANE, worktreeId: WT, row: current.row }) - expect(deps.deliver).not.toHaveBeenCalled() - }) - - it('tells no stop for a pane that rested without a stopped turn', () => { - const current: { row: AgentStatusIpcPayload | null } = { row: null } - const { turnNews, deps } = news(current, true) - turnNews.observe(moved('working', 'rest', null)) - current.row = row({ state: 'done' }) - turnNews.observe(moved('done', 'rest', null)) - expect(deps.stopped).not.toHaveBeenCalled() - }) - - it('reads no extra row for a listener that did not opt in', () => { - const current: { row: AgentStatusIpcPayload | null } = { row: row({ state: 'working' }) } - const { turnNews, readHookRow } = news(current, false) - turnNews.observe(moved('rest', 'working', 'prompt-submitted')) - current.row = row({ state: 'done', interrupted: true }) - turnNews.observe(moved('working', 'rest', null)) - expect(readHookRow).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/update-install-exit-watchdog.test.ts b/src/main/update-install-exit-watchdog.test.ts deleted file mode 100644 index ff6e00f7c0c..00000000000 --- a/src/main/update-install-exit-watchdog.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { appMock, recordUpdaterLifecycleMock, recordAgentSessionRuntimeEndMock } = vi.hoisted( - () => ({ - appMock: { exit: vi.fn() }, - recordUpdaterLifecycleMock: vi.fn(), - recordAgentSessionRuntimeEndMock: vi.fn() - }) -) - -vi.mock('electron', () => ({ app: appMock })) -vi.mock('./updater-lifecycle-diagnostics', () => ({ - recordUpdaterLifecycle: recordUpdaterLifecycleMock -})) -vi.mock('./runtime/agent-session-runtime-end-record', () => ({ - recordAgentSessionRuntimeEnd: recordAgentSessionRuntimeEndMock -})) - -import { - armUpdateInstallExitWatchdog, - disarmUpdateInstallExitWatchdog, - UPDATE_INSTALL_EXIT_TIMEOUT_MS -} from './update-install-exit-watchdog' - -describe('update install exit watchdog', () => { - beforeEach(() => { - vi.useFakeTimers() - appMock.exit.mockClear() - recordUpdaterLifecycleMock.mockClear() - recordAgentSessionRuntimeEndMock.mockClear() - }) - - afterEach(() => { - disarmUpdateInstallExitWatchdog() - vi.useRealTimers() - }) - - it('force-exits with code 0 when the deadline passes', () => { - armUpdateInstallExitWatchdog() - - vi.advanceTimersByTime(UPDATE_INSTALL_EXIT_TIMEOUT_MS - 1) - expect(appMock.exit).not.toHaveBeenCalled() - - vi.advanceTimersByTime(1) - expect(appMock.exit).toHaveBeenCalledExactlyOnceWith(0) - expect(recordAgentSessionRuntimeEndMock).toHaveBeenCalledExactlyOnceWith('update') - expect(recordUpdaterLifecycleMock).toHaveBeenCalledWith( - 'install_exit_watchdog_fired', - { timeoutMs: UPDATE_INSTALL_EXIT_TIMEOUT_MS }, - expect.objectContaining({ level: 'warn' }) - ) - }) - - it('re-arming does not extend the original deadline', () => { - armUpdateInstallExitWatchdog() - vi.advanceTimersByTime(UPDATE_INSTALL_EXIT_TIMEOUT_MS - 1) - - armUpdateInstallExitWatchdog() - vi.advanceTimersByTime(1) - - expect(appMock.exit).toHaveBeenCalledExactlyOnceWith(0) - }) - - it('disarm cancels the forced exit', () => { - armUpdateInstallExitWatchdog() - disarmUpdateInstallExitWatchdog() - - vi.advanceTimersByTime(UPDATE_INSTALL_EXIT_TIMEOUT_MS * 2) - expect(appMock.exit).not.toHaveBeenCalled() - }) - - it('can be armed again after a disarm (install recovery then retry)', () => { - armUpdateInstallExitWatchdog() - disarmUpdateInstallExitWatchdog() - armUpdateInstallExitWatchdog() - - vi.advanceTimersByTime(UPDATE_INSTALL_EXIT_TIMEOUT_MS) - expect(appMock.exit).toHaveBeenCalledExactlyOnceWith(0) - }) -}) diff --git a/src/main/wsl/wsl-distro-not-running-refusal.test.ts b/src/main/wsl/wsl-distro-not-running-refusal.test.ts deleted file mode 100644 index 7707b9c1b67..00000000000 --- a/src/main/wsl/wsl-distro-not-running-refusal.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { expect, it } from 'vitest' -import { isWslDistroNotRunningRefusal } from '../../shared/wsl-distro-not-running-refusal' -import { WslDistroStoppedError, WslDistroUnverifiableError } from './wsl-unc-access-gate' - -it('recognizes both gate refusals as they arrive over IPC, and nothing else', () => { - const overIpc = (error: Error): Error => - new Error( - `Error invoking remote method 'preflight:detectAgents': ${error.name}: ${error.message}` - ) - expect(isWslDistroNotRunningRefusal(overIpc(new WslDistroStoppedError('Ubuntu')))).toBe(true) - expect(isWslDistroNotRunningRefusal(overIpc(new WslDistroUnverifiableError('Ubuntu')))).toBe(true) - expect(isWslDistroNotRunningRefusal(new Error('wsl.exe timed out'))).toBe(false) -}) - -it('does not depend on how the refusal words its remedy', () => { - expect( - isWslDistroNotRunningRefusal("WSL distro 'Ubuntu' is not running. Open a terminal to start it.") - ).toBe(true) - expect(isWslDistroNotRunningRefusal("WSL didn't answer whether 'Ubuntu' is running.")).toBe(true) - expect(isWslDistroNotRunningRefusal('Orca is not running.')).toBe(false) -}) diff --git a/src/renderer/src/components/crash-report/CrashReportDialogSurface.overflow.test.tsx b/src/renderer/src/components/crash-report/CrashReportDialogSurface.overflow.test.tsx deleted file mode 100644 index a26ff7b8942..00000000000 --- a/src/renderer/src/components/crash-report/CrashReportDialogSurface.overflow.test.tsx +++ /dev/null @@ -1,84 +0,0 @@ -// @vitest-environment happy-dom - -import type { ReactNode } from 'react' -import { cleanup, render, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { CrashReportRecord } from '../../../../shared/crash-reporting' -import { CrashReportDialogSurface } from './CrashReportDialogSurface' - -const viewer = vi.fn(async () => null) - -vi.mock('./use-crash-report-copy', () => ({ - useCrashReportCopy: () => vi.fn(async () => {}) -})) - -vi.mock('@/components/ui/dialog', () => ({ - Dialog: ({ open, children }: { open: boolean; children?: ReactNode }) => - open ?
{children}
: null, - DialogContent: ({ className, children }: { className?: string; children?: ReactNode }) => ( -
- {children} -
- ), - DialogDescription: ({ children }: { children?: ReactNode }) =>

{children}

, - DialogFooter: ({ children }: { children?: ReactNode }) =>
{children}
, - DialogHeader: ({ children }: { children?: ReactNode }) =>
{children}
, - DialogTitle: ({ children }: { children?: ReactNode }) =>

{children}

-})) - -function crashReport(error: string): CrashReportRecord { - return { - id: 'crash-1', - createdAt: '2026-08-10T00:00:00.000Z', - status: 'pending', - source: 'renderer', - processType: 'renderer', - reason: 'crashed', - exitCode: 5, - appVersion: '1.0.0', - platform: 'darwin', - osRelease: 'test', - arch: 'arm64', - electronVersion: '41', - chromeVersion: '141', - details: { error } - } -} - -beforeEach(() => { - viewer.mockClear() - Object.defineProperty(window, 'api', { - configurable: true, - value: { gh: { viewer } } - }) -}) - -afterEach(() => cleanup()) - -describe('CrashReportDialogSurface overflow containment', () => { - it('keeps unbroken diagnostic output inside the dialog grid', async () => { - const unbrokenError = 'A'.repeat(1000) - const { container } = render( - {}} - onReportChange={() => {}} - /> - ) - await waitFor(() => expect(viewer).toHaveBeenCalledOnce()) - - const dialog = container.querySelector('[role="dialog"]') - const output = dialog?.querySelector('pre') - expect(output?.textContent).toContain(unbrokenError) - expect(output?.className).toContain('[overflow-wrap:anywhere]') - expect(output?.className).not.toContain('break-words') - - const gridChild = Array.from(dialog?.children ?? []).find((child) => - child.contains(output ?? null) - ) - expect(gridChild?.className).toContain('min-w-0') - expect(output?.parentElement?.className).toContain('min-w-0') - }) -}) diff --git a/src/renderer/src/components/editor/editor-cmd-save-target.test.ts b/src/renderer/src/components/editor/editor-cmd-save-target.test.ts deleted file mode 100644 index f53e6c5f1f8..00000000000 --- a/src/renderer/src/components/editor/editor-cmd-save-target.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' -import type { Tab } from '../../../../shared/tab-types' -import { getEditorCmdSaveFileId } from './editor-cmd-save-target' - -function makeTab(contentType: Tab['contentType'], entityId: string): Tab { - return { - id: `tab-${entityId}`, - entityId, - contentType, - label: entityId, - groupId: 'group-1', - worktreeId: FLOATING_TERMINAL_WORKTREE_ID, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - } -} - -describe('getEditorCmdSaveFileId', () => { - it('targets the main active editor when the floating panel does not own the event', () => { - const getActiveTab = vi.fn(() => makeTab('editor', 'floating-file')) - - expect( - getEditorCmdSaveFileId( - { - activeFileId: 'main-file', - activeTabType: 'editor', - activeView: 'terminal', - getActiveTab - }, - false - ) - ).toBe('main-file') - expect(getActiveTab).not.toHaveBeenCalled() - }) - - it('claims nothing on a non-workspace view so the shortcut is not swallowed', () => { - const getActiveTab = vi.fn(() => null) - - for (const activeView of ['tasks', 'settings', 'activity'] as const) { - expect( - getEditorCmdSaveFileId( - { activeFileId: 'main-file', activeTabType: 'editor', activeView, getActiveTab }, - false - ) - ).toBeNull() - } - }) - - it('targets only an active floating editor and never falls through to main', () => { - const getActiveTab = vi - .fn<(worktreeId: string) => Tab | null>() - .mockReturnValueOnce(makeTab('editor', 'floating-file')) - .mockReturnValueOnce(makeTab('browser', 'floating-browser')) - const state = { - activeFileId: 'main-file', - activeTabType: 'editor', - activeView: 'terminal' as const, - getActiveTab - } - - expect(getEditorCmdSaveFileId(state, true)).toBe('floating-file') - expect(getEditorCmdSaveFileId(state, true)).toBeNull() - expect(getActiveTab).toHaveBeenNthCalledWith(1, FLOATING_TERMINAL_WORKTREE_ID) - expect(getActiveTab).toHaveBeenNthCalledWith(2, FLOATING_TERMINAL_WORKTREE_ID) - }) - - it('still targets the floating editor from a non-workspace view', () => { - const getActiveTab = vi.fn(() => makeTab('editor', 'floating-file')) - - expect( - getEditorCmdSaveFileId( - { activeFileId: 'main-file', activeTabType: 'editor', activeView: 'tasks', getActiveTab }, - true - ) - ).toBe('floating-file') - }) -}) diff --git a/src/renderer/src/components/native-chat/structured-agent-registered-agent-surface.test.ts b/src/renderer/src/components/native-chat/structured-agent-registered-agent-surface.test.ts deleted file mode 100644 index d22d18a170a..00000000000 --- a/src/renderer/src/components/native-chat/structured-agent-registered-agent-surface.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { getAgentSessionOptionCatalog } from '../../../../shared/agent-session-option-catalog' -import type { AgentSessionCapabilities } from '../../../../shared/agent-session-capabilities' -import type { Tab } from '../../../../shared/tab-types' -import { parseWorkspaceSession } from '../../../../shared/workspace-session-schema' - -vi.mock('@/store', () => ({ useAppStore: { getState: () => ({}), subscribe: () => () => {} } })) - -import { structuredAgentAcceptsImages } from '@/runtime/use-host-structured-agent' -import { isStructuredTab } from '../../../../shared/structured-agent-session-tab' -import { structuredAgentSessionSeedCatalog } from '../../../../shared/structured-agent-session-seed-catalog' - -const chatTab = (agentSessionAgent: unknown) => ({ - id: 'agent-session:grok_1', - entityId: 'grok_1', - groupId: 'group-1', - worktreeId: 'wt', - contentType: 'agent-session', - agentSessionAgent, - label: 'Grok Chat', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0 -}) - -function reloadedTab(agentSessionAgent: unknown): Tab { - const parsed = parseWorkspaceSession({ - activeRepoId: null, - activeWorktreeId: 'wt', - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - unifiedTabs: { wt: [chatTab(agentSessionAgent)] } - }) - if (!parsed.ok || !parsed.value.unifiedTabs?.wt[0]) { - throw new Error('session did not parse') - } - return parsed.value.unifiedTabs.wt[0] -} - -describe('a host-registered agent on the structured chat surface', () => { - it("renders a registered agent's chat tab, including after a reload", () => { - expect(isStructuredTab(reloadedTab('grok'))).toBe(true) - expect(isStructuredTab(reloadedTab('claude'))).toBe(true) - expect(isStructuredTab(reloadedTab('not an agent!'))).toBe(false) - }) - - it("starts an unshipped agent's picker from no built-in list, so the host catalog or session fills it", () => { - expect(structuredAgentSessionSeedCatalog('grok').models).toEqual([]) - expect(structuredAgentSessionSeedCatalog('claude')).toBe(getAgentSessionOptionCatalog('claude')) - expect(structuredAgentSessionSeedCatalog('codex')).toBe(getAgentSessionOptionCatalog('codex')) - }) - - it("attaches images only when the host's record for the agent takes them", () => { - const capabilities = (imagePrompts: boolean): AgentSessionCapabilities => ({ - rewind: false, - compact: false, - threadGoal: false, - contextUsage: false, - imagePrompts, - steering: 'queue', - approvalEnforcement: 'orca' - }) - const record = (imagePrompts: boolean) => ({ - agent: 'grok', - capabilities: capabilities(imagePrompts) - }) - expect(structuredAgentAcceptsImages(record(false), 'grok')).toBe(false) - expect(structuredAgentAcceptsImages(record(true), 'grok')).toBe(true) - // Unlisted: an older host's built-ins keep images; any other agent claims none. - expect(structuredAgentAcceptsImages(undefined, 'claude')).toBe(true) - expect(structuredAgentAcceptsImages(undefined, 'grok')).toBe(false) - // The session's options report outranks both, either way. - expect(structuredAgentAcceptsImages(record(true), 'grok', false)).toBe(false) - expect(structuredAgentAcceptsImages(undefined, 'claude', false)).toBe(false) - expect(structuredAgentAcceptsImages(undefined, 'grok', true)).toBe(true) - }) -}) diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-prompt-state.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-prompt-state.test.tsx deleted file mode 100644 index 95138be7f9f..00000000000 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-prompt-state.test.tsx +++ /dev/null @@ -1,80 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { AgentJournalRenderItem } from '../../../../shared/agent-session-journal-types' -import { useStructuredAgentSession } from './use-structured-agent-session' - -afterEach(cleanup) - -const items: AgentJournalRenderItem[] = [ - { - itemId: 'turn-1', - revision: 1, - sequence: 1, - observedAt: 1, - body: { kind: 'turn', turnId: 'provider-turn', state: 'running' } - }, - { - itemId: 'question-1', - revision: 1, - sequence: 2, - observedAt: 2, - body: { - kind: 'question', - question: 'Which approach?', - options: [{ id: 'focused', label: 'Focused' }], - resolution: { - state: 'pending', - selectedOptionId: null, - resolvedBy: null, - resolvedAt: null - } - } - } -] - -vi.mock('@/runtime/structured-agent-session-client', () => ({ - subscribeStructuredAgentSessionStatus: vi.fn(async () => ({ unsubscribe: vi.fn() })), - callStructuredAgentSession: vi.fn().mockResolvedValue(null) -})) - -vi.mock('./use-structured-agent-session-read', () => ({ - useStructuredAgentSessionRead: () => ({ - state: { - fence: 3, - items, - submissions: [], - status: 'ready', - error: null, - hasOlder: false, - handoff: null - }, - loadingOlder: false, - loadOlder: vi.fn() - }) -})) - -vi.mock('./use-structured-agent-session-sends', () => ({ - useStructuredAgentSessionSends: () => ({ - pending: [], - error: null, - send: vi.fn(), - stopSends: vi.fn() - }) -})) - -it('keeps a prompted provider turn working and cancellable beneath presentation policy', () => { - const { result } = renderHook(() => - useStructuredAgentSession({ - sessionId: 'session-1', - agent: 'codex', - target: { kind: 'local' }, - isVisible: true - }) - ) - - expect(result.current.isWorking).toBe(true) - expect(result.current.turnId).toBe('provider-turn') - expect(result.current.prompts).toHaveLength(1) -}) diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-transport.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-transport.test.tsx deleted file mode 100644 index f82e775103e..00000000000 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-transport.test.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// Hidden panes do no journal reads; their send replies must settle messages independently. - -// @vitest-environment happy-dom - -import { act, cleanup, renderHook, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentJournalCursor } from '../../../../shared/agent-session-journal-types' -import type { AgentSessionHistoryPage } from '../../../../shared/agent-session-wire' - -const mocks = vi.hoisted(() => ({ call: vi.fn(), subscribe: vi.fn() })) - -vi.mock('@/runtime/structured-agent-session-client', () => ({ - callStructuredAgentSession: mocks.call, - subscribeStructuredAgentSession: mocks.subscribe, - supportsStructuredAgentSessionPromptCancel: vi.fn().mockResolvedValue(false) -})) - -import { useStructuredAgentSessionTransport } from './use-structured-agent-session-transport' -import { resetStructuredAgentSessionReadOwnersForTests } from './structured-agent-session-read-owner' - -const LOCAL_TARGET = { kind: 'local' } as const - -function emptyPage(): AgentSessionHistoryPage { - const cursor = (sequence: number): AgentJournalCursor => ({ epoch: 'epoch-a', sequence }) - return { - sessionId: 'session-a', - epoch: 'epoch-a', - direction: 'tail', - items: [], - removedItemIds: [], - submissions: [], - window: { oldest: null, newest: null, nextCursor: cursor(0) }, - liveCursor: cursor(0), - hasOlder: false, - hasNewer: false - } -} - -function renderTransport(sessionId: string, isVisible: boolean) { - return renderHook(() => - useStructuredAgentSessionTransport({ - sessionId, - target: LOCAL_TARGET, - isVisible, - enabled: true - }) - ) -} - -describe('useStructuredAgentSessionTransport reads', () => { - afterEach(cleanup) - - beforeEach(() => { - vi.clearAllMocks() - resetStructuredAgentSessionReadOwnersForTests() - mocks.call.mockResolvedValue({ ok: true, page: emptyPage() }) - mocks.subscribe.mockResolvedValue({ unsubscribe: vi.fn() }) - }) - - it('reads a visible session', async () => { - const view = renderTransport('session-visible', true) - - await waitFor(() => expect(mocks.subscribe).toHaveBeenCalledTimes(1)) - view.unmount() - }) - - it('leaves a hidden session unread', async () => { - const view = renderTransport('session-hidden', false) - - await act(async () => { - await Promise.resolve() - }) - expect(mocks.subscribe).not.toHaveBeenCalled() - view.unmount() - }) -}) diff --git a/src/renderer/src/components/plugins/list/plugin-category-label.test.ts b/src/renderer/src/components/plugins/list/plugin-category-label.test.ts deleted file mode 100644 index b2dfe97d919..00000000000 --- a/src/renderer/src/components/plugins/list/plugin-category-label.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { pluginCategoryLabel } from './plugin-category-label' - -describe('pluginCategoryLabel', () => { - it('names folded kinds and known standalone categories through the catalog', () => { - expect(pluginCategoryLabel('vm-recipes')).toBe('Remote/VMs') - expect(pluginCategoryLabel('games')).toBe('Games') - expect(pluginCategoryLabel('integrations')).toBe('Integrations') - }) - - it('turns unknown slugs into words', () => { - expect(pluginCategoryLabel('music-tools')).toBe('Music Tools') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects-wsl-wake.test.ts b/src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects-wsl-wake.test.ts deleted file mode 100644 index 99a552583d4..00000000000 --- a/src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects-wsl-wake.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -// @vitest-environment happy-dom - -import { renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: { settings: null }) => T): T => selector({ settings: null }) -})) -vi.mock('./fileExplorerUndoRedo', () => ({ clearFileExplorerUndoHistory: vi.fn() })) - -import { useFileExplorerTreeLoadEffects } from './use-file-explorer-tree-load-effects' - -const ROOT = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' -const SRC = `${ROOT}\\src` -const DOCS = `${ROOT}\\docs` - -const loadDir = vi.fn( - async (_path: string, _depth: number, _options?: { force?: boolean; wakeWslDistro?: boolean }) => - true -) -const resetAndLoad = vi.fn() - -function render(expanded: Set) { - return renderHook( - ({ dirs }: { dirs: Set }) => - useFileExplorerTreeLoadEffects({ - workspaceKey: 'repo-1::wsl', - visibleFilesWorktreePath: ROOT, - expanded: dirs, - dirCache: {}, - loadingDirPaths: new Set(), - rootError: null, - isDirStale: () => false, - loadDir, - refreshTree: async () => undefined, - resetAndLoad, - resetSelection: vi.fn(), - setNameFilterQuery: vi.fn() - }), - { initialProps: { dirs: expanded } } - ) -} - -const wokeFor = (dirPath: string): boolean => - loadDir.mock.calls.some( - ([path, , options]) => path === dirPath && options?.wakeWslDistro === true - ) - -beforeEach(() => { - loadDir.mockClear() - resetAndLoad.mockClear() -}) - -describe('file explorer folder loads wake a stopped WSL distro only for a folder the user expands (E9)', () => { - it('a mount re-reading folders that were already open wakes nothing', () => { - render(new Set([SRC])) - expect(loadDir).toHaveBeenCalledWith(SRC, 0, {}) - expect(wokeFor(SRC)).toBe(false) - }) - - it('a folder expanded after the mount wakes; the ones already open do not', () => { - const view = render(new Set([SRC])) - loadDir.mockClear() - view.rerender({ dirs: new Set([SRC, DOCS]) }) - expect(wokeFor(DOCS)).toBe(true) - expect(wokeFor(SRC)).toBe(false) - }) - - it('a remount after host loss, with the same folders open, wakes nothing', () => { - const first = render(new Set([SRC])) - first.rerender({ dirs: new Set([SRC, DOCS]) }) - first.unmount() - loadDir.mockClear() - render(new Set([SRC, DOCS])) - expect(wokeFor(SRC)).toBe(false) - expect(wokeFor(DOCS)).toBe(false) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/useFileExplorerWatch.catch-up.test.tsx b/src/renderer/src/components/right-sidebar/useFileExplorerWatch.catch-up.test.tsx deleted file mode 100644 index 7fb77b72c2f..00000000000 --- a/src/renderer/src/components/right-sidebar/useFileExplorerWatch.catch-up.test.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { - markWorktreeCatchUpPayload, - ORCA_WORKTREE_FILE_CHANGE_EVENT -} from '@/hooks/worktree-file-change-event' -import type { FsChangedPayload } from '../../../../shared/filesystem-entry-types' -import { useFileExplorerWatch } from './useFileExplorerWatch' - -vi.mock('@/store', () => ({ - useAppStore: Object.assign((selector: (state: unknown) => unknown) => selector({}), { - getState: () => ({ openFiles: [] }) - }) -})) -vi.mock('./file-explorer-operation-owner', () => { - const owner = { kind: 'local', executionHostId: 'local' } - return { - getFileExplorerOperationOwner: () => owner, - getFileExplorerOperationOwnerFromState: () => owner - } -}) - -const refreshDir = vi.fn(async () => {}) -const refreshTree = vi.fn(async () => 'refreshed' as const) -const ROOT = '/repo' - -function dispatch(payload: FsChangedPayload, runtimeEnvironmentId: string | null = null): void { - window.dispatchEvent( - new CustomEvent(ORCA_WORKTREE_FILE_CHANGE_EVENT, { detail: { payload, runtimeEnvironmentId } }) - ) -} - -const overflow = (): FsChangedPayload => ({ - worktreePath: ROOT, - events: [{ kind: 'overflow', absolutePath: ROOT }] -}) - -beforeEach(() => { - vi.useFakeTimers() - vi.clearAllMocks() - Object.defineProperty(window, 'api', { - configurable: true, - value: { fs: { onFsChanged: vi.fn(() => vi.fn()) } } - }) - renderHook(() => - useFileExplorerWatch({ - worktreePath: ROOT, - activeWorktreeId: 'wt', - dirCache: { [ROOT]: { children: [] } }, - setDirCache: vi.fn(), - expanded: new Set(), - setSelectedPath: vi.fn(), - refreshDir, - refreshTree, - inlineInput: null, - dragSourcePath: null, - isNativeDragOver: false - }) - ) -}) -afterEach(() => { - cleanup() - vi.useRealTimers() -}) - -it('refreshes a local Files tree on the catch-up sent when its workspace is watched again', async () => { - act(() => dispatch(markWorktreeCatchUpPayload(overflow()))) - await act(async () => vi.advanceTimersByTimeAsync(0)) - expect(refreshTree).toHaveBeenCalledTimes(1) -}) - -it('leaves ordinary bus events to the IPC listener so nothing is processed twice', async () => { - act(() => dispatch(overflow())) - act(() => dispatch(markWorktreeCatchUpPayload(overflow()), 'env-1')) - await act(async () => vi.advanceTimersByTimeAsync(0)) - expect(refreshTree).not.toHaveBeenCalled() -}) diff --git a/src/renderer/src/components/settings/RuntimeSshAccessControl.test.tsx b/src/renderer/src/components/settings/RuntimeSshAccessControl.test.tsx deleted file mode 100644 index 8d64d77640f..00000000000 --- a/src/renderer/src/components/settings/RuntimeSshAccessControl.test.tsx +++ /dev/null @@ -1,78 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' -import type { ManagedOrcadPreloadApi } from '../../../../preload/api/managed-orcad-api' -import { RuntimeSshAccessControl } from './RuntimeSshAccessControl' - -function environment( - pendingSshAccessOperation: PublicKnownRuntimeEnvironment['pendingSshAccessOperation'] -): PublicKnownRuntimeEnvironment { - return { - id: 'env-a', - name: 'fight PC', - createdAt: 1, - updatedAt: 1, - lastUsedAt: null, - runtimeId: 'runtime-a', - endpoints: [{ id: 'ws', kind: 'websocket', label: 'Tailscale', endpoint: 'ws://a:6768' }], - preferredEndpointId: 'ws', - pendingSshAccessOperation - } -} - -const pendingLink = { - requestId: 'request-1', - operation: 'link' as const, - sshTargetId: 'ssh-weknora', - sshTargetGeneration: 3, - remotePort: 6768, - targetFingerprint: 'fingerprint' -} - -function renderControl(env: PublicKnownRuntimeEnvironment) { - const linkSshAccess = vi.fn(async () => env) - const unlinkSshAccess = vi.fn(async () => env) - const onChanged = vi.fn() - const api: Pick = { - linkSshAccess, - unlinkSshAccess - } - render() - return { linkSshAccess, unlinkSshAccess, onChanged } -} - -afterEach(cleanup) - -// #27765: an unfinished link blocked removing the server and offered no way out. -describe('an unfinished SSH access link', () => { - it('cancels the recorded operation by its own request id', async () => { - const { unlinkSshAccess, onChanged } = renderControl(environment(pendingLink)) - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) - await waitFor(() => expect(onChanged).toHaveBeenCalled()) - expect(unlinkSshAccess).toHaveBeenCalledWith({ selector: 'env-a', requestId: 'request-1' }) - }) - - it('retries the recorded link rather than starting another', async () => { - const { linkSshAccess, onChanged } = renderControl(environment(pendingLink)) - fireEvent.click(screen.getByRole('button', { name: 'Retry' })) - await waitFor(() => expect(onChanged).toHaveBeenCalled()) - expect(linkSshAccess).toHaveBeenCalledWith({ - selector: 'env-a', - requestId: 'request-1', - sshTargetId: 'ssh-weknora', - remotePort: 6768 - }) - }) - - it('finishes an unfinished unlink by its own request id', async () => { - const { unlinkSshAccess, onChanged } = renderControl( - environment({ ...pendingLink, operation: 'unlink' }) - ) - expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'Retry' })) - await waitFor(() => expect(onChanged).toHaveBeenCalled()) - expect(unlinkSshAccess).toHaveBeenCalledWith({ selector: 'env-a', requestId: 'request-1' }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/WslHostStoppedCard.test.tsx b/src/renderer/src/components/terminal-pane/WslHostStoppedCard.test.tsx deleted file mode 100644 index 7d8a225cd17..00000000000 --- a/src/renderer/src/components/terminal-pane/WslHostStoppedCard.test.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' -import { cleanup, render, screen, waitFor } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { WslHostStoppedCard } from './WslHostStoppedCard' - -const { reloadProjects } = vi.hoisted(() => ({ reloadProjects: vi.fn() })) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, options?: Record) => - fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? ''), - getIntlLocale: () => 'en-US' -})) -vi.mock('@/components/status-bar/runtime-environment-explicit-connect', () => ({ - connectRuntimeHostAndReloadProjects: reloadProjects -})) -function renderStoppedPane(onStarted = vi.fn()) { - render() - return onStarted -} - -beforeEach(() => { - reloadProjects.mockReset().mockResolvedValue(true) -}) - -afterEach(() => { - cleanup() -}) - -describe('a terminal on a stopped WSL distro', () => { - it('says the distro is stopped and offers Start, never "retrying automatically"', () => { - renderStoppedPane() - - expect(screen.getByText('Ubuntu is stopped')).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument() - expect(screen.queryByText(/retrying/i)).not.toBeInTheDocument() - // Showing the card is not a start: only the click may boot the distro. - expect(reloadProjects).not.toHaveBeenCalled() - }) - - it('boots the distro on Start, then resumes the pane', async () => { - const onStarted = renderStoppedPane() - await userEvent.setup().click(screen.getByRole('button', { name: 'Start' })) - - await waitFor(() => expect(onStarted).toHaveBeenCalledOnce()) - expect(reloadProjects).toHaveBeenCalledOnce() - }) - - it('leaves the pane as it is when the start fails', async () => { - reloadProjects.mockResolvedValueOnce(false) - const onStarted = renderStoppedPane() - await userEvent.setup().click(screen.getByRole('button', { name: 'Start' })) - - await waitFor(() => expect(reloadProjects).toHaveBeenCalledOnce()) - expect(onStarted).not.toHaveBeenCalled() - }) - - it('starts the distro once for repeated clicks while it boots', async () => { - let finish!: (started: boolean) => void - reloadProjects.mockReturnValueOnce( - new Promise((resolve) => { - finish = resolve - }) - ) - const onStarted = renderStoppedPane() - const user = userEvent.setup() - await user.click(screen.getByRole('button', { name: 'Start' })) - await user.click(screen.getByRole('button', { name: 'Start' })) - finish(true) - - await waitFor(() => expect(onStarted).toHaveBeenCalledTimes(2)) - expect(reloadProjects).toHaveBeenCalledOnce() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-copy-rejection-handling.test.ts b/src/renderer/src/components/terminal-pane/terminal-copy-rejection-handling.test.ts deleted file mode 100644 index d768a59d2ca..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-copy-rejection-handling.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { runTerminalCopy, runTerminalIdentityCopy } from './terminal-copy-rejection-guards' - -// Insecure-context clipboard rejection must neither escape as a crash breadcrumb nor show a false copy-success toast. - -const REJECTION = new Error('Clipboard write is unavailable in this browser context') - -describe('runTerminalCopy', () => { - it('resolves and still refocuses the pane when the clipboard write rejects', async () => { - const focus = vi.fn() - const writeClipboardText = vi.fn().mockRejectedValue(REJECTION) - - await expect( - runTerminalCopy({ selection: 'terminal text', writeClipboardText, focus }) - ).resolves.toBeUndefined() - expect(writeClipboardText).toHaveBeenCalledWith('terminal text') - expect(focus).toHaveBeenCalledTimes(1) - }) - - it('refocuses the pane after a successful copy', async () => { - const focus = vi.fn() - const writeClipboardText = vi.fn().mockResolvedValue(undefined) - - await runTerminalCopy({ selection: 'terminal text', writeClipboardText, focus }) - - expect(focus).toHaveBeenCalledTimes(1) - }) - - it('skips the write but still refocuses when there is no selection', async () => { - const focus = vi.fn() - const writeClipboardText = vi.fn() - - await runTerminalCopy({ selection: '', writeClipboardText, focus }) - - expect(writeClipboardText).not.toHaveBeenCalled() - expect(focus).toHaveBeenCalledTimes(1) - }) -}) - -describe('runTerminalIdentityCopy', () => { - it('reports failure instead of claiming success when the write rejects', async () => { - const onSuccess = vi.fn() - const onError = vi.fn() - const focus = vi.fn() - - await expect( - runTerminalIdentityCopy({ - text: 'tab:leaf', - writeClipboardText: vi.fn().mockRejectedValue(REJECTION), - onSuccess, - onError, - focus - }) - ).resolves.toBeUndefined() - - expect(onSuccess).not.toHaveBeenCalled() - expect(onError).toHaveBeenCalledTimes(1) - expect(focus).toHaveBeenCalledTimes(1) - }) - - it('reports success and refocuses when the write lands', async () => { - const onSuccess = vi.fn() - const onError = vi.fn() - const focus = vi.fn() - - await runTerminalIdentityCopy({ - text: 'tab:leaf', - writeClipboardText: vi.fn().mockResolvedValue(undefined), - onSuccess, - onError, - focus - }) - - expect(onSuccess).toHaveBeenCalledTimes(1) - expect(onError).not.toHaveBeenCalled() - expect(focus).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-layout-restore.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-layout-restore.test.ts deleted file mode 100644 index 21d8fdcbeae..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-pane-layout-restore.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Layout-owner builds restore history from the terminal host; only switch-off uses the window’s saved copy (L236). -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const restoreScrollbackBuffers = vi.fn() -const setTabLayout = vi.fn() -const setTabLocalOnlyScrollback = vi.fn() -const TAB = 'tab-1' -const LEAF = 'leaf-1' - -vi.mock('./layout-serialization', () => ({ - replayTerminalLayout: () => new Map([[LEAF, 1]]), - restoreScrollbackBuffers: (...args: unknown[]) => restoreScrollbackBuffers(...args) -})) -vi.mock('./expand-collapse', () => ({ applyExpandedLayoutTo: vi.fn() })) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ - localOnlyScrollbackByTabId: { [TAB]: { [LEAF]: 'local-only history' } }, - repos: [{ id: 'repo', connectionId: 'ssh-1' }], - setTabLayout, - setTabLocalOnlyScrollback - }) - } -})) - -async function restoreWithSwitch(on: boolean): Promise { - vi.resetModules() - vi.doMock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: on })) - const { restoreTerminalPaneLayout } = await import('./terminal-pane-layout-restore') - const manager = { - getActivePane: () => ({ id: 1 }), - getPanes: () => [{ id: 1 }], - setActivePane: vi.fn() - } - const initialLayoutRef = { - current: { - root: { type: 'leaf' as const, leafId: LEAF }, - activeLeafId: LEAF, - expandedLeafId: null, - buffersByLeafId: { [LEAF]: 'shared history' } - } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the restore reads only the members this fixture supplies. - const args = { - manager, - deps: { - initialLayoutRef, - tabId: TAB, - worktreeId: 'repo::/wt', - isActive: false, - managerRef: { current: manager }, - replayingPanesRef: { current: new Map() }, - setPaneTitles: vi.fn(), - paneTitlesRef: { current: {} }, - setExpandedPane: vi.fn() - }, - refs: { restoredViewportBlankingPanesRef: { current: new Set() } }, - ptyDeps: { mountFollowsTerminalPark: false }, - initialLayoutHadBuffers: true - } as unknown as Parameters[0] - restoreTerminalPaneLayout(args) -} - -describe('restoreTerminalPaneLayout history source', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('paints the window copy with the switch off', async () => { - await restoreWithSwitch(false) - expect(restoreScrollbackBuffers.mock.calls[0]?.[1]).toEqual({ [LEAF]: 'local-only history' }) - }) - - it('paints no window copy in the layout-owner build, and keeps the copy untouched', async () => { - await restoreWithSwitch(true) - expect(restoreScrollbackBuffers.mock.calls[0]?.[1]).toBeUndefined() - expect(setTabLayout).not.toHaveBeenCalled() - expect(setTabLocalOnlyScrollback).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-set-title-event.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-set-title-event.test.ts deleted file mode 100644 index 02b030d0ef5..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-pane-set-title-event.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { SET_TERMINAL_PANE_TITLE_EVENT } from '@/constants/terminal' -import type { PaneManager } from '@/lib/pane-manager/pane-manager' -import type { PtyConnectionDeps } from './pty-connection-types' -import { installTerminalPaneMountEvents } from './terminal-pane-mount-events' - -const LEAF_ID = '11111111-1111-4111-8111-111111111111' -const SIBLING_ID = '22222222-2222-4222-8222-222222222222' - -function createHarness() { - const listeners = new Map void>() - vi.stubGlobal('window', { - addEventListener: (type: string, listener: (event: Event) => void) => - listeners.set(type, listener), - removeEventListener: (type: string) => listeners.delete(type) - }) - const panes = [ - { id: 7, leafId: LEAF_ID }, - { id: 8, leafId: SIBLING_ID } - ] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: title events only read the two identity methods; other mount event listeners are not invoked. - const manager = { - getNumericIdForLeaf: (id: string) => (id === LEAF_ID ? 7 : id === SIBLING_ID ? 8 : null), - getPanes: () => panes - } as unknown as PaneManager - const showPaneTitle = vi.fn() - const uninstall = installTerminalPaneMountEvents({ - manager, - deps: { - tabId: 'tab-1', - worktreeId: 'wt-1', - isActive: true, - managerRef: { current: manager }, - showPaneTitle, - persistLayoutSnapshot: vi.fn(), - syncCanExpandState: vi.fn(), - queueResizeAll: vi.fn() - }, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: title and listener cleanup never use PTY connection dependencies. - ptyDeps: {} as PtyConnectionDeps - }) - const dispatch = (tabId: string, leafId: string, title: string | null) => - listeners.get(SET_TERMINAL_PANE_TITLE_EVENT)?.( - new CustomEvent(SET_TERMINAL_PANE_TITLE_EVENT, { detail: { tabId, leafId, title } }) - ) - return { panes, showPaneTitle, dispatch, uninstall, listeners } -} - -afterEach(() => vi.unstubAllGlobals()) - -describe('pane title event identity', () => { - it('routes set and clear to the GUI setter for the addressed leaf only', () => { - const { dispatch, showPaneTitle } = createHarness() - dispatch('tab-1', LEAF_ID, 'REVIEWER') - dispatch('tab-1', LEAF_ID, null) - expect(showPaneTitle.mock.calls).toEqual([ - [7, 'REVIEWER'], - [7, null] - ]) - }) - - it('rejects a stale leaf after the numeric pane id is reused, and another tab', () => { - const { dispatch, showPaneTitle, panes } = createHarness() - panes[0].leafId = SIBLING_ID - dispatch('tab-1', LEAF_ID, 'WRONG') - dispatch('other-tab', SIBLING_ID, 'WRONG') - dispatch('tab-1', 'pane:7', 'WRONG') - expect(showPaneTitle).not.toHaveBeenCalled() - }) - - it('removes its subscription on teardown', () => { - const { uninstall, listeners } = createHarness() - expect(listeners.has(SET_TERMINAL_PANE_TITLE_EVENT)).toBe(true) - uninstall() - expect(listeners.has(SET_TERMINAL_PANE_TITLE_EVENT)).toBe(false) - }) -}) diff --git a/src/renderer/src/components/wsl-move/wsl-move-result-undo-path.test.tsx b/src/renderer/src/components/wsl-move/wsl-move-result-undo-path.test.tsx deleted file mode 100644 index 9b7b372c0e9..00000000000 --- a/src/renderer/src/components/wsl-move/wsl-move-result-undo-path.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { renderToStaticMarkup } from 'react-dom/server' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { WslMovedProject } from '../../../../shared/wsl-move/wsl-moved-project' -import { WslMoveResultBody } from './WslMoveResultBody' - -const movedProject: WslMovedProject = { - kind: 'folder', - id: 'notes', - displayName: 'notes', - path: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\notes', - distro: 'Ubuntu' -} -// No chats stayed here: the entry must still list, or the result's promise leads nowhere. -const mockState = { - wslMovedProjects: [movedProject], - worktreesByRepo: {}, - folderWorkspaces: [], - unifiedTabsByWorktree: {}, - activeWorktreeId: null, - activeGroupIdByWorktree: {}, - groupsByWorktree: {}, - // No unsaved file, so the release is not refused before it reaches main. - openFiles: [] -} -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector: (state: typeof mockState) => unknown) => selector(mockState), - { getState: () => mockState } - ) -})) -vi.mock('@/components/confirmation-dialog-context', () => ({ - useConfirmationDialog: () => async () => true -})) - -const { default: WslMovedProjectsSection } = await import('../sidebar/WslMovedProjectsSection') -const { TooltipProvider } = await import('@/components/ui/tooltip') - -afterEach(() => { - cleanup() - vi.unstubAllGlobals() -}) - -/** The sidebar labels the moved result's undo hint quotes, in order. */ -function quotedInResult(): string[] { - const markup = renderToStaticMarkup( - {}} - onReview={() => {}} - onClose={() => {}} - /> - ) - return [...markup.matchAll(/“([^”]+)”/g)].map((match) => match[1] ?? '') -} - -describe('the moved result\'s "Use on this computer again"', () => { - it('names a sidebar entry and action that exist, and the action asks main to bring it back', async () => { - const useProjectHereAgain = vi.fn(async () => ({ released: false, reason: 'not-moved' })) - vi.stubGlobal('api', { wslMove: { useProjectHereAgain } }) - const [entryLabel, actionLabel] = quotedInResult() - expect([entryLabel, actionLabel]).toEqual([ - 'Moved to Ubuntu host', - 'Use on this computer again' - ]) - - render( - - - - ) - expect(screen.getByTestId('wsl-moved-project').textContent).toContain(entryLabel) - fireEvent.click(screen.getByRole('button', { name: actionLabel })) - - await waitFor(() => - expect(useProjectHereAgain).toHaveBeenCalledWith({ - kind: 'folder', - id: 'notes', - unsavedWorkspaceIds: [] - }) - ) - }) -}) diff --git a/src/renderer/src/components/wsl-move/wsl-move-slept-pane-bindings.test.ts b/src/renderer/src/components/wsl-move/wsl-move-slept-pane-bindings.test.ts deleted file mode 100644 index 9ad87742363..00000000000 --- a/src/renderer/src/components/wsl-move/wsl-move-slept-pane-bindings.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { collectWslMoveSleptPaneBindings } from './wsl-move-slept-pane-bindings' - -const LEAF_A = '11111111-1111-4111-8111-111111111111' -const LEAF_B = '22222222-2222-4222-8222-222222222222' - -function layout(ptyIdsByLeafId: Record) { - return { - root: { - type: 'split' as const, - direction: 'vertical' as const, - first: { type: 'leaf' as const, leafId: LEAF_A }, - second: { type: 'leaf' as const, leafId: LEAF_B } - }, - activeLeafId: LEAF_A, - expandedLeafId: null, - ptyIdsByLeafId - } -} - -describe('collectWslMoveSleptPaneBindings', () => { - it('reports bound panes with no live terminal, never a live one', () => { - const tab = { id: 'tab-1', ptyId: 'w@@slept', worktreeId: 'w' } - const state = { - tabsByWorktree: { w: [tab] }, - terminalLayoutsByTabId: { 'tab-1': layout({ [LEAF_A]: 'w@@slept', [LEAF_B]: 'w@@live' }) }, - ptyIdsByTabId: { 'tab-1': ['w@@live'] } - } - const bindings = collectWslMoveSleptPaneBindings(state) - expect(bindings).toEqual([{ paneKey: `tab-1:${LEAF_A}`, sessionId: 'w@@slept' }]) - }) -}) diff --git a/src/renderer/src/hooks/composer-drop-failure-toast.test.ts b/src/renderer/src/hooks/composer-drop-failure-toast.test.ts deleted file mode 100644 index 5bc2aebbe4f..00000000000 --- a/src/renderer/src/hooks/composer-drop-failure-toast.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { toastError } = vi.hoisted(() => ({ - toastError: vi.fn<(title: string, options?: { id?: string; description?: string }) => void>() -})) -vi.mock('sonner', () => ({ toast: { error: toastError } })) - -import { showComposerDropFailureToast } from './composer-drop-failure-toast' -import type { ImportSkipReason } from '../../../shared/filesystem-import-result-types' - -const SKIP_REASON_COPY = [ - ['missing', 'No longer at its original path.'], - ['symlink', 'Symbolic links cannot be attached.'], - ['permission-denied', 'Permission denied.'], - ['unsupported', 'Unsupported file type.'] -] as const satisfies readonly (readonly [ImportSkipReason, string])[] - -function lastToast(): { title: string; id?: string; description?: string } { - const call = toastError.mock.calls.at(-1) - return { - title: String(call?.[0]), - id: call?.[1]?.id, - description: call?.[1]?.description - } -} - -describe('showComposerDropFailureToast', () => { - beforeEach(() => { - toastError.mockClear() - }) - - it('stays neutral about the gesture, and pluralises like its namespace siblings', () => { - showComposerDropFailureToast({ failureCount: 1, total: 1 }) - expect(lastToast().title).toBe('1 of 1 item could not be attached.') - - showComposerDropFailureToast({ failureCount: 2, total: 5 }) - expect(lastToast().title).toBe('2 of 5 items could not be attached.') - }) - - it("turns the import client's skip enum into copy instead of leaking the token", () => { - for (const [reason, expected] of SKIP_REASON_COPY) { - showComposerDropFailureToast({ - failureCount: 1, - total: 3, - commonFailure: { status: 'skipped', reason } - }) - expect(lastToast().description).toBe(expected) - } - }) - - it('shows no description when nothing explained the failure', () => { - showComposerDropFailureToast({ failureCount: 1, total: 2 }) - expect(lastToast().description).toBeUndefined() - }) - - it('unwraps and clamps a host-minted failure reason before it reaches the row', () => { - showComposerDropFailureToast({ - failureCount: 1, - total: 2, - commonFailure: { - status: 'failed', - reason: - "Error invoking remote method 'runtime:call': Error: EACCES: permission denied\nat Object.upload" - } - }) - expect(lastToast().description).toBe('EACCES: permission denied') - }) - - it('reuses one slot so a second failed drop replaces the first instead of stacking', () => { - showComposerDropFailureToast({ failureCount: 1, total: 2 }) - const first = lastToast().id - showComposerDropFailureToast({ failureCount: 2, total: 3 }) - expect(first).toBeDefined() - expect(lastToast().id).toBe(first) - }) -}) diff --git a/src/renderer/src/hooks/structured-session-completion-focus.test.ts b/src/renderer/src/hooks/structured-session-completion-focus.test.ts deleted file mode 100644 index 8717891f18e..00000000000 --- a/src/renderer/src/hooks/structured-session-completion-focus.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - createHarnessStoreState, - loadIpcEventsHarness, - type HarnessStoreState -} from './ipc-events-test-harness' - -const SESSION_WORKSPACE_ID = 'repo-1::/session-workspace' -const OTHER_WORKSPACE_ID = 'repo-1::/other-workspace' -const TAB_ID = 'structured-agent-session-session-1' - -function createStoreState(activeWorktreeId: string): HarnessStoreState { - return createHarnessStoreState({ - tabsByWorktree: {}, - activeWorktreeId, - unifiedTabsByWorktree: { - [SESSION_WORKSPACE_ID]: [ - { - id: TAB_ID, - entityId: 'session-1', - groupId: 'group-1', - worktreeId: SESSION_WORKSPACE_ID, - contentType: 'agent-session' - } - ] - }, - focusGroup: vi.fn(), - activateTab: vi.fn() - }) -} - -describe('structured session completion focus', () => { - it('focuses the chat tab when its workspace is active', async () => { - const store = createStoreState(SESSION_WORKSPACE_ID) - const harness = await loadIpcEventsHarness(store) - harness.useIpcEvents() - - harness.focusEditorTab({ tabId: TAB_ID, worktreeId: SESSION_WORKSPACE_ID }) - - expect(store.focusGroup).toHaveBeenCalledWith(SESSION_WORKSPACE_ID, 'group-1') - expect(store.activateTab).toHaveBeenCalledWith(TAB_ID) - expect(store.setActiveTabType).toHaveBeenCalledWith('agent-session', SESSION_WORKSPACE_ID) - }) - - it('does not apply focus after the user moves to another workspace', async () => { - const store = createStoreState(OTHER_WORKSPACE_ID) - const harness = await loadIpcEventsHarness(store) - harness.useIpcEvents() - - harness.focusEditorTab({ tabId: TAB_ID, worktreeId: SESSION_WORKSPACE_ID }) - - expect(store.setActiveWorktree).not.toHaveBeenCalled() - expect(store.markWorktreeVisited).not.toHaveBeenCalled() - expect(store.setActiveView).not.toHaveBeenCalled() - expect(store.focusGroup).not.toHaveBeenCalled() - expect(store.activateTab).not.toHaveBeenCalled() - expect(store.setActiveTabType).not.toHaveBeenCalled() - expect(store.revealWorktreeInSidebar).not.toHaveBeenCalled() - }) - - it('still reveals the chat on a notification click, before activateWorktree has landed', async () => { - // Explicit clicks may arrive before async activation updates active ID; userInitiated distinguishes them from courtesy reveals. - const store = createStoreState(OTHER_WORKSPACE_ID) - const harness = await loadIpcEventsHarness(store) - harness.useIpcEvents() - - harness.focusEditorTab({ - tabId: TAB_ID, - worktreeId: SESSION_WORKSPACE_ID, - userInitiated: true - }) - - expect(store.focusGroup).toHaveBeenCalledWith(SESSION_WORKSPACE_ID, 'group-1') - expect(store.activateTab).toHaveBeenCalledWith(TAB_ID) - expect(store.setActiveTabType).toHaveBeenCalledWith('agent-session', SESSION_WORKSPACE_ID) - }) -}) diff --git a/src/renderer/src/hooks/viewport-size-change-listener.test.ts b/src/renderer/src/hooks/viewport-size-change-listener.test.ts deleted file mode 100644 index 00611495bea..00000000000 --- a/src/renderer/src/hooks/viewport-size-change-listener.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { addViewportSizeChangeListener } from './viewport-size-change-listener' - -function createViewport(width: number, height: number) { - const listeners = new Set<() => void>() - return { - innerWidth: width, - innerHeight: height, - addEventListener: (_type: 'resize', listener: () => void) => { - listeners.add(listener) - }, - removeEventListener: (_type: 'resize', listener: () => void) => { - listeners.delete(listener) - }, - resizeTo(nextWidth: number, nextHeight: number) { - this.innerWidth = nextWidth - this.innerHeight = nextHeight - for (const listener of listeners) { - listener() - } - }, - emitResize() { - for (const listener of listeners) { - listener() - } - }, - get listenerCount() { - return listeners.size - } - } -} - -describe('addViewportSizeChangeListener', () => { - it('runs the callback when the viewport size changes', () => { - const viewport = createViewport(1024, 768) - const onChange = vi.fn() - addViewportSizeChangeListener(onChange, viewport) - viewport.resizeTo(1024, 900) - expect(onChange).toHaveBeenCalledTimes(1) - }) - - // Reveal reflow can emit resize with unchanged dimensions; dismissing UI then would close it on every restore. - it('ignores a resize that leaves the dimensions untouched', () => { - const viewport = createViewport(1024, 768) - const onChange = vi.fn() - addViewportSizeChangeListener(onChange, viewport) - viewport.emitResize() - expect(onChange).not.toHaveBeenCalled() - }) - - it('still reports a later real change after ignoring a no-op resize', () => { - const viewport = createViewport(1024, 768) - const onChange = vi.fn() - addViewportSizeChangeListener(onChange, viewport) - viewport.emitResize() - viewport.resizeTo(800, 768) - expect(onChange).toHaveBeenCalledTimes(1) - }) - - it('treats each size as the new baseline rather than the original', () => { - const viewport = createViewport(1024, 768) - const onChange = vi.fn() - addViewportSizeChangeListener(onChange, viewport) - viewport.resizeTo(900, 768) - viewport.emitResize() - expect(onChange).toHaveBeenCalledTimes(1) - }) - - it('stops listening once removed', () => { - const viewport = createViewport(1024, 768) - const onChange = vi.fn() - const remove = addViewportSizeChangeListener(onChange, viewport) - remove() - expect(viewport.listenerCount).toBe(0) - viewport.resizeTo(640, 480) - expect(onChange).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/runtime/web-runtime-terminal-creation.wsl-host-start.test.ts b/src/renderer/src/runtime/web-runtime-terminal-creation.wsl-host-start.test.ts deleted file mode 100644 index dd460b5b16c..00000000000 --- a/src/renderer/src/runtime/web-runtime-terminal-creation.wsl-host-start.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { createResult, reloadProjects, wslHostStatuses } = vi.hoisted(() => { - const wslHostStatuses: Record = {} - return { - createResult: vi.fn(), - reloadProjects: vi.fn(), - wslHostStatuses - } -}) - -vi.mock('./web-runtime-terminal-create-operation', () => ({ - createWebRuntimeSessionTerminalResult: createResult -})) -vi.mock('./web-runtime-terminal-create-failure-notice', () => ({ - notifyWebRuntimeTerminalCreateFailure: vi.fn() -})) -vi.mock('../lib/agent-launch-prompt-delivery', () => ({ - deliverLaunchPromptToAgentTab: vi.fn(), - seedNativeChatLaunchDraftForAgentTab: vi.fn() -})) -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, options?: Record) => - fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? '') -})) -vi.mock('@/components/status-bar/runtime-environment-explicit-connect', () => ({ - connectRuntimeHostAndReloadProjects: reloadProjects -})) -vi.mock('@/store', () => ({ - useAppStore: { getState: () => ({ wslHostStatuses }) } -})) - -import { createWebRuntimeSessionTerminal } from './web-runtime-terminal-creation' - -const ARGS = { worktreeId: 'wt-1', environmentId: 'env-1', activate: true } - -beforeEach(() => { - createResult.mockReset().mockResolvedValue({ outcome: { status: 'created' } }) - reloadProjects.mockReset().mockResolvedValue(true) - for (const key of Object.keys(wslHostStatuses)) { - delete wslHostStatuses[key] - } - wslHostStatuses['env-1'] = { state: 'distro-stopped', distro: 'Ubuntu' } -}) - -describe('New Terminal on a stopped WSL host', () => { - it('starts the distro first, as the user asked, then creates the terminal', async () => { - await expect(createWebRuntimeSessionTerminal(ARGS, { userAct: true })).resolves.toEqual({ - status: 'created' - }) - expect(reloadProjects).toHaveBeenCalledOnce() - expect(reloadProjects.mock.invocationCallOrder[0]).toBeLessThan( - createResult.mock.invocationCallOrder[0] - ) - }) - - it('never boots the distro for a terminal nobody asked for', async () => { - await createWebRuntimeSessionTerminal(ARGS) - expect(reloadProjects).not.toHaveBeenCalled() - expect(createResult).toHaveBeenCalledOnce() - }) - - it('does not touch a host that is running, or any other kind of host', async () => { - wslHostStatuses['env-1'] = { state: 'ready', distro: 'Ubuntu' } - await createWebRuntimeSessionTerminal(ARGS, { userAct: true }) - await createWebRuntimeSessionTerminal({ ...ARGS, environmentId: 'ssh-1' }, { userAct: true }) - expect(reloadProjects).not.toHaveBeenCalled() - expect(createResult).toHaveBeenCalledTimes(2) - }) - - it('creates nothing when the start is refused, such as a pending Remove', async () => { - reloadProjects.mockResolvedValueOnce(false) - await expect(createWebRuntimeSessionTerminal(ARGS, { userAct: true })).resolves.toEqual({ - status: 'failed', - message: 'Ubuntu is stopped' - }) - expect(createResult).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/startup/ssh-startup-reconnect.test.ts b/src/renderer/src/startup/ssh-startup-reconnect.test.ts deleted file mode 100644 index 44872a97f6e..00000000000 --- a/src/renderer/src/startup/ssh-startup-reconnect.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { SshConnectionState, SshProviderEpoch } from '../../../shared/ssh-types' -import { reconnectSshTargetForRendererStartup } from './ssh-startup-reconnect' - -const connectedState: SshConnectionState = { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0, - providerEpoch: 'startup-provider-epoch' as SshProviderEpoch, - connectionGeneration: 41, - remotePlatform: 'linux' -} - -afterEach(() => { - vi.useRealTimers() -}) - -describe('reconnectSshTargetForRendererStartup', () => { - it('publishes the connect result before startup terminal restoration continues', async () => { - const publishState = vi.fn() - const result = await reconnectSshTargetForRendererStartup({ - targetId: 'ssh-1', - timeoutMs: 1_000, - connect: vi.fn().mockResolvedValue(connectedState), - publishState, - onFailure: vi.fn() - }) - - expect(result).toEqual({ timedOut: false }) - expect(publishState).toHaveBeenCalledWith('ssh-1', connectedState) - expect(publishState.mock.calls[0]?.[1]).toMatchObject({ - providerEpoch: 'startup-provider-epoch', - connectionGeneration: 41 - }) - }) - - it('does not synthesize the missing half of a partial startup authority', async () => { - const publishState = vi.fn() - const partialState = { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0, - providerEpoch: 'partial-provider-epoch' as SshProviderEpoch - } satisfies SshConnectionState - - await reconnectSshTargetForRendererStartup({ - targetId: 'ssh-1', - timeoutMs: 1_000, - connect: vi.fn().mockResolvedValue(partialState), - publishState, - onFailure: vi.fn() - }) - - expect(publishState).toHaveBeenCalledWith('ssh-1', partialState) - expect(publishState.mock.calls[0]?.[1]).not.toHaveProperty('connectionGeneration') - }) - - it('marks a stalled connect as deferred without publishing stale state', async () => { - vi.useFakeTimers() - const publishState = vi.fn() - const onFailure = vi.fn() - const resultPromise = reconnectSshTargetForRendererStartup({ - targetId: 'ssh-1', - timeoutMs: 1_000, - connect: () => new Promise(() => {}), - publishState, - onFailure - }) - - await vi.advanceTimersByTimeAsync(1_000) - - await expect(resultPromise).resolves.toEqual({ timedOut: true }) - expect(publishState).not.toHaveBeenCalled() - expect(onFailure).toHaveBeenCalledWith('ssh-1', expect.any(Error)) - }) -}) diff --git a/src/renderer/src/store/plugin-syntax-packs.test.ts b/src/renderer/src/store/plugin-syntax-packs.test.ts deleted file mode 100644 index 8ead4618c45..00000000000 --- a/src/renderer/src/store/plugin-syntax-packs.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { expect, it } from 'vitest' -import type { PluginSyntaxMetadata } from '../../../shared/plugins/artifacts/plugin-syntax-artifact' -import { matchPluginSyntax } from './plugin-syntax-packs' - -function syntax(id: string, extensions: string[], filenames: string[] = []): PluginSyntaxMetadata { - return { - id: `plugin:samples.demo/${id}`, - pluginKey: 'samples.demo', - label: id, - extensions, - filenames, - revision: 'r' - } -} - -it('prefers an exact file name, then the longest extension, case-insensitively', () => { - const entries = [ - syntax('yaml', ['.yaml']), - syntax('compose', ['.compose.yaml']), - syntax('build', [], ['buildfile']) - ] - expect(matchPluginSyntax(entries, 'deploy/App.Compose.YAML')?.label).toBe('compose') - expect(matchPluginSyntax(entries, 'C:\\repo\\a.yaml')?.label).toBe('yaml') - expect(matchPluginSyntax(entries, 'repo/Buildfile')?.label).toBe('build') - expect(matchPluginSyntax(entries, 'repo/.yaml')).toBeNull() - expect(matchPluginSyntax(entries, 'repo/readme.md')).toBeNull() -}) diff --git a/src/renderer/src/store/slices/editor-rich-markdown-size-override.test.ts b/src/renderer/src/store/slices/editor-rich-markdown-size-override.test.ts deleted file mode 100644 index 238a6b45b6a..00000000000 --- a/src/renderer/src/store/slices/editor-rich-markdown-size-override.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createEditorStore } from './editor-slice-test-harness' - -const { toastErrorMock } = vi.hoisted(() => ({ - toastErrorMock: vi.fn() -})) - -vi.mock('sonner', () => ({ - toast: { error: toastErrorMock } -})) - -const { notifyHostOfMirroredEditorCloseMock } = vi.hoisted(() => ({ - notifyHostOfMirroredEditorCloseMock: vi.fn() -})) -vi.mock('@/runtime/close-mirrored-editor-tab', () => ({ - notifyHostOfMirroredEditorClose: (...args: unknown[]) => - notifyHostOfMirroredEditorCloseMock(...args) -})) - -function openMarkdown(store: ReturnType, filePath: string): void { - store.getState().openFile({ - filePath, - relativePath: filePath.replace('/repo/', ''), - worktreeId: 'wt-1', - language: 'markdown', - mode: 'edit' - }) -} - -describe('createEditorSlice rich markdown size override', () => { - it('records an opt-in per file and clears it when turned back off', () => { - const store = createEditorStore() - openMarkdown(store, '/repo/big.md') - - store.getState().setMarkdownRichModeSizeOverride('/repo/big.md', true) - expect(store.getState().markdownRichModeSizeOverride).toEqual({ '/repo/big.md': true }) - - store.getState().setMarkdownRichModeSizeOverride('/repo/big.md', false) - expect(store.getState().markdownRichModeSizeOverride).toEqual({}) - }) - - it('drops the opt-in when the file is closed', async () => { - const store = createEditorStore() - openMarkdown(store, '/repo/big.md') - store.getState().setMarkdownRichModeSizeOverride('/repo/big.md', true) - - await store.getState().closeFile('/repo/big.md') - - expect(store.getState().markdownRichModeSizeOverride).toEqual({}) - }) - - it('drops the opt-in for a replaced preview tab', () => { - const store = createEditorStore() - - store.getState().openFile( - { - filePath: '/repo/docs/README.md', - relativePath: 'docs/README.md', - worktreeId: 'wt-1', - language: 'markdown', - mode: 'edit' - }, - { preview: true } - ) - store.getState().setMarkdownRichModeSizeOverride('/repo/docs/README.md', true) - - store.getState().openFile( - { - filePath: '/repo/docs/guide.md', - relativePath: 'docs/guide.md', - worktreeId: 'wt-1', - language: 'markdown', - mode: 'edit' - }, - { preview: true } - ) - - expect(store.getState().markdownRichModeSizeOverride).toEqual({}) - }) -}) diff --git a/src/shared/plugins/installation/plugin-publisher-derivation.test.ts b/src/shared/plugins/installation/plugin-publisher-derivation.test.ts deleted file mode 100644 index 966a3786aed..00000000000 --- a/src/shared/plugins/installation/plugin-publisher-derivation.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - gitUrlPluginPublisher, - localPluginPublisher, - withPluginPublisher -} from './plugin-publisher-derivation' - -describe('plugin publisher derivation', () => { - it('names a Git URL after its owner, lowercased', () => { - expect(gitUrlPluginPublisher('https://github.com/Acme/gleam.git')).toBe('acme') - expect(gitUrlPluginPublisher('git@github.com:Acme/gleam.git')).toBe('acme') - expect(gitUrlPluginPublisher('ssh://git@gitlab.com/acme/tools/gleam.git')).toBe('acme') - expect(gitUrlPluginPublisher('https://gitlab.com/john.doe__x/gleam.git')).toBe('john-doe-x') - }) - - it('names nobody when the URL has no usable owner', () => { - expect(gitUrlPluginPublisher('ssh://git@example.com/gleam.git')).toBeNull() - expect(gitUrlPluginPublisher('https://github.com/constructor/gleam.git')).toBeNull() - expect(gitUrlPluginPublisher('file:///tmp/acme/gleam')).toBeNull() - }) - - it('keeps a folder on its declared publisher while deprecated, else local', () => { - expect(localPluginPublisher('acme')).toBe('acme') - expect(localPluginPublisher(undefined)).toBe('local') - }) - - it('overrides whatever publisher the manifest declared', () => { - expect(withPluginPublisher({ id: 'gleam', publisher: 'brand' }, 'acme')).toEqual({ - id: 'gleam', - publisher: 'acme' - }) - }) -})