diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index ccb62ddd1c0..e56ab448eb7 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1948,14 +1948,14 @@ "id": "terminal-performance.vertical-control-scan", "title": "Main terminal preview scanning skips ordinary output between controls", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "main-runtime-unit", "surfaces": ["terminal output ingestion", "terminal preview and read tails"], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], + "coveredPlatforms": [], + "coveredProviders": [], "motivatingLinks": [ "https://github.com/stablyai/orca/blob/main/.agents/skills/perf/SKILL.md" ], @@ -1967,35 +1967,13 @@ "Complete CI soak with zero unexplained flakes and preserve the observable oracle." ], "demotionRule": "Keep experimental until CI soak; investigate failures without relaxing fidelity or resource-count assertions.", - "coverageNotes": "Audit2168: Current retained source covers chunk-carried normalization, embedded/incomplete string-control framing and complete tail redraw semantics only; removed recognition and scan-resumption inventories accept coverage loss. Historical execution and measured performance refer to earlier bytes. Prior account preserved verbatim: Pure shared-host string semantics and main runtime tests cover the production scanner on macOS. Folder/git workspaces, local/daemon/SSH/remote-runtime authority, wire content and mobile/relay behavior are unchanged. No live native remote session was launched.", + "coverageNotes": "Audit5872 removes the complete remaining scanner suite, including chunk-carried normalization, embedded/incomplete string-control framing and tail redraw checks. No current test coverage is claimed. Historical scope: Audit2168: Current retained source covers chunk-carried normalization, embedded/incomplete string-control framing and complete tail redraw semantics only; removed recognition and scan-resumption inventories accept coverage loss. Historical execution and measured performance refer to earlier bytes. Prior account preserved verbatim: Pure shared-host string semantics and main runtime tests cover the production scanner on macOS. Folder/git workspaces, local/daemon/SSH/remote-runtime authority, wire content and mobile/relay behavior are unchanged. No live native remote session was launched.", "invariant": "Main terminal preview/read tails choose the same append/redraw path while ordinary text is skipped without a JavaScript code-unit walk. Complete string-control payloads are not interpreted as vertical controls; incomplete controls stop at the same point.", - "oracle": "Current retained callbacks preserve printable spans and carried controls across chunks, skip embedded CSI and stop at incomplete OSC/DCS/SOS/PM/APC strings, and verify resulting cursor-up tail redraw rows. No code-unit work budget or exhaustive parameter/final recognition matrix is asserted by this reduced source.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts" - ], - "testFiles": ["src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts"], - "assertionRefs": [ - { - "file": "src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts", - "assertions": [ - "preserves printable spans and carried controls across chunk boundaries", - "skips embedded CSI and stops at an incomplete %s", - "preserves tail rows when ordinary output is followed by a cursor-up redraw" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-07", - "runner": "local", - "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-vertical-control-scan.test.ts", - "result": "passed", - "durationSeconds": 0.325, - "summary": "29 scanner work-budget, control recognition, scan-resumption and complete-tail integration tests passed.", - "currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts" - } - ], + "oracle": "No current automated oracle remains after Audit5872 removes the sole selected scanner suite. Historical oracle: Current retained callbacks preserve printable spans and carried controls across chunks, skip embedded CSI and stop at incomplete OSC/DCS/SOS/PM/APC strings, and verify resulting cursor-up tail redraw rows. No code-unit work budget or exhaustive parameter/final recognition matrix is asserted by this reduced source.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 15, "scope": "Focused scanner and tail-contract suite; local runtime budget, not an established p95." @@ -2011,7 +1989,8 @@ "knownGaps": [ "No live end-to-end input latency, many-pane frame measurement or launched Electron/SSH/WSL/Linux/Windows journey.", "Existing preview fidelity and incomplete-control handling remain unchanged; broader runtime suite has one existing skipped case.", - "Audit2168: Intentionally remove the long retained-CSI identity, exact retained-final inventory, long plain/colored/vertical boolean table, numeric/noncanonical parameter table and scan-resumption table from src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts. Retain carried-control chunk framing, embedded/incomplete OSC/DCS/SOS/PM/APC skipping and actual tail cursor-up redraw. Accepted coverage loss; retained callbacks are not equivalent replacements. The 2026-09-07 evidenceRun (including currentCommand), redGreenEvidence and performanceBudget describe historical bytes and remain verbatim; they do not validate the changed source. No fresh execution, scanner work budget, runtime latency, real provider, remote/mobile or cross-platform result is claimed." + "Audit2168: Intentionally remove the long retained-CSI identity, exact retained-final inventory, long plain/colored/vertical boolean table, numeric/noncanonical parameter table and scan-resumption table from src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts. Retain carried-control chunk framing, embedded/incomplete OSC/DCS/SOS/PM/APC skipping and actual tail cursor-up redraw. Accepted coverage loss; retained callbacks are not equivalent replacements. The 2026-09-07 evidenceRun (including currentCommand), redGreenEvidence and performanceBudget describe historical bytes and remain verbatim; they do not validate the changed source. No fresh execution, scanner work budget, runtime latency, real provider, remote/mobile or cross-platform result is claimed.", + "Audit5872 removed the sole current scanner suite. No current automated test coverage or replacement is claimed. Historical evidence runs, preserved as complete records: [{\"date\":\"2026-09-07\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal-vertical-control-scan.test.ts\",\"result\":\"passed\",\"durationSeconds\":0.325,\"summary\":\"29 scanner work-budget, control recognition, scan-resumption and complete-tail integration tests passed.\",\"currentCommand\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts\"}]" ] }, { @@ -2791,46 +2770,39 @@ "surfaces": ["SSH filesystem reads", "AI Vault remote scanning", "system sleep/wake"], "platforms": ["macos", "linux", "windows"], "providers": ["ssh2", "system-ssh"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["ssh2", "system-ssh"], - "coverageNotes": "Deterministic fake-clock coverage proves inactivity cancellation, active-transfer renewal, sticky suspend replay before metadata, failure-isolated lifecycle fanout, committed-quit bridge disposal, timer cleanup, and listener cleanup. A real Docker SSH relay previously proved active and stalled transfer behavior; physical sleep/wake and Windows/Linux clients remain gaps.", + "coveredPlatforms": ["linux"], + "coveredProviders": [], + "coverageNotes": "Audit5872 removes the power lifecycle suite and accepts losing late/reentrant suspend replay and throwing-listener isolation alarms. The remaining mocked resume bridge suite checks unsubscription and sleep-duration breadcrumbs; it does not replace those alarms or validate SSH stream inactivity. Historical scope: Deterministic fake-clock coverage proves inactivity cancellation, active-transfer renewal, sticky suspend replay before metadata, failure-isolated lifecycle fanout, committed-quit bridge disposal, timer cleanup, and listener cleanup. A real Docker SSH relay previously proved active and stalled transfer behavior; physical sleep/wake and Windows/Linux clients remain gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/11362", "https://github.com/stablyai/orca/pull/11364" ], "invariant": "A non-empty SSH file stream that produces no valid frame for 30 seconds must cancel at its authoritative stream reader and release all local lifecycle state. System suspend is sticky across metadata and subscription races, resume grants every still-live stream one fresh inactivity window, one failing consumer cannot block the others, and the sole Electron bridge survives a vetoed before-quit without retaining a per-stream Electron listener.", - "oracle": "Publish suspend before stream metadata resolves, jump wall time by one hour, and require the late-subscribing stream to remain pending until resume grants a fresh 30-second window. Deliver a valid final chunk and end frame, require exact content, then publish another resume and require zero timers, multiplexer listeners, or renewed work; separately require stalled cancellation at 30 seconds, atomic state replay, failure-isolated fanout, and bridge disposal only after the committed will-quit gate.", + "oracle": "The remaining mocked resume bridge suite checks unsubscription and sleep-duration breadcrumbs. Late/reentrant replay and failure-isolated fanout checks were removed by Audit5872. Historical stream oracle, not current coverage: Publish suspend before stream metadata resolves, jump wall time by one hour, and require the late-subscribing stream to remain pending until resume grants a fresh 30-second window. Deliver a valid final chunk and end frame, require exact content, then publish another resume and require zero timers, multiplexer listeners, or renewed work; separately require stalled cancellation at 30 seconds, atomic state replay, failure-isolated fanout, and bridge disposal only after the committed will-quit gate.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/power/system-resume-broadcast.test.ts src/main/power/system-power-lifecycle.test.ts --reporter=dot --maxWorkers=2" - ], - "testFiles": [ - "src/main/power/system-resume-broadcast.test.ts", - "src/main/power/system-power-lifecycle.test.ts" + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/power/system-resume-broadcast.test.ts" ], + "testFiles": ["src/main/power/system-resume-broadcast.test.ts"], "assertionRefs": [ { "file": "src/main/power/system-resume-broadcast.test.ts", - "assertions": ["publishes suspend and resume to main-process lifecycle consumers"] - }, - { - "file": "src/main/power/system-power-lifecycle.test.ts", "assertions": [ - "replays suspended state to a late subscriber", - "atomically replays a transition to a subscriber added during publication", - "isolates a failing listener from the remaining subscribers" + "stops broadcasting after unsubscribe", + "spans from the first suspend when dark wake swallows the intervening resume", + "ignores sleeps too short to open a gap, keeping ring slots for real evidence", + "measures each reportable sleep independently across repeated cycles" ] } ], "evidenceRuns": [ { - "date": "2026-10-06", + "date": "2026-11-15", "runner": "local", - "platform": "macos", + "platform": "linux", "result": "passed", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/system-resume-broadcast.test.ts src/main/system-power-lifecycle.test.ts --reporter=dot --maxWorkers=2", - "currentCommand": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/power/system-resume-broadcast.test.ts src/main/power/system-power-lifecycle.test.ts --reporter=dot --maxWorkers=2", - "durationSeconds": 8.141, - "summary": "The retained behavioral cohort passed 25 tests after removing source-only ordering tests. Historical pre-removal receipts are preserved verbatim with their originally executed commands: [{\"date\":\"2026-08-01\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"pnpm exec vitest run --config config/vitest.config.ts src/main/system-resume-broadcast.test.ts src/main/system-power-lifecycle.test.ts src/main/startup/desktop-startup-ordering.test.ts --reporter=dot\",\"result\":\"passed\",\"durationSeconds\":1.6,\"summary\":\"Four focused files and 33 tests passed, including stalled cancellation, active progress, late metadata replay, failure isolation, committed-quit bridge lifetime, and post-settlement cleanup.\"}] No new native desktop or hosted run is claimed." + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/power/system-resume-broadcast.test.ts", + "durationSeconds": 5.393, + "summary": "Audit5872 fresh run of the remaining mocked resume bridge suite: unsubscription and sleep-duration breadcrumbs. No late/reentrant replay, throwing-listener isolation, physical sleep or live SSH coverage is claimed. See local resume-runtime.log for exact case count." } ], "runtimeBudget": { @@ -2856,7 +2828,8 @@ ], "knownGaps": [ "Suspend/resume is injected at the authoritative main-process event seam rather than by physically sleeping the runner.", - "Slow links that produce no complete valid frame for 30 uninterrupted awake seconds remain intentionally retryable failures." + "Slow links that produce no complete valid frame for 30 uninterrupted awake seconds remain intentionally retryable failures.", + "Audit5872 retires the complete original dated receipt as historical evidence before selector reduction: [{\"date\":\"2026-10-06\",\"runner\":\"local\",\"platform\":\"macos\",\"result\":\"passed\",\"command\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/system-resume-broadcast.test.ts src/main/system-power-lifecycle.test.ts --reporter=dot --maxWorkers=2\",\"currentCommand\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/power/system-resume-broadcast.test.ts src/main/power/system-power-lifecycle.test.ts --reporter=dot --maxWorkers=2\",\"durationSeconds\":8.141,\"summary\":\"The retained behavioral cohort passed 25 tests after removing source-only ordering tests. Historical pre-removal receipts are preserved verbatim with their originally executed commands: [{\\\"date\\\":\\\"2026-08-01\\\",\\\"runner\\\":\\\"local\\\",\\\"platform\\\":\\\"macos\\\",\\\"command\\\":\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/system-resume-broadcast.test.ts src/main/system-power-lifecycle.test.ts src/main/startup/desktop-startup-ordering.test.ts --reporter=dot\\\",\\\"result\\\":\\\"passed\\\",\\\"durationSeconds\\\":1.6,\\\"summary\\\":\\\"Four focused files and 33 tests passed, including stalled cancellation, active progress, late metadata replay, failure isolation, committed-quit bridge lifetime, and post-settlement cleanup.\\\"}] No new native desktop or hosted run is claimed.\"}]" ], "demotionRule": "Keep experimental or demote if sleep consumes inactivity evidence, stalled streams become unbounded, or settled reads retain timers or lifecycle subscriptions." }, @@ -4714,7 +4687,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts", "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" ], @@ -4741,7 +4714,6 @@ "src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts", "src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts", "src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts", - "src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts", "src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts", "src/main/ssh/port-forwarding/ssh-port-forward.test.ts", "src/main/browser/network/tunnels/remote-browser-socks-server.test.ts", @@ -4909,12 +4881,6 @@ "reaches external sites over system SSH through the host proxy" ] }, - { - "file": "src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts", - "assertions": [ - "the internal SOCKS5 client encodes the exact destination as a domain request" - ] - }, { "file": "src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts", "assertions": [ diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index e1baf59ef85..a4b360baf32 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -487,14 +487,12 @@ "src/main/ai-vault-search/session-search-service-registry.test.ts": 193, "src/main/ai-vault-search/query/session-search-snippet-marks.test.ts": 230, "src/main/ai-vault-search/session-search-synthetic-corpus.test.ts": 372, - "src/main/ai-vault-search/query/session-search-typo-policy.test.ts": 158, "src/main/ai-vault-search/query/session-search-typo-scope.test.ts": 195, "src/main/ai-vault/ai-vault-scan-progress.test.ts": 475, "src/main/ai-vault/ai-vault-wsl-session-carryover.test.ts": 46, "src/main/ai-vault/scanners/antigravity/antigravity-ide-history.test.ts": 525, "src/main/ai-vault/scanners/antigravity/antigravity-opening-prompt-workspace.test.ts": 204, "src/main/ai-vault/transcripts/local-log-tail-reader.test.ts": 59, - "src/main/ai-vault/scanners/openclaw/openclaw-session-layout.test.ts": 223, "src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts": 1230, "src/main/ai-vault/transcripts/remote-session-content-lines.test.ts": 66, "src/main/ai-vault/runtime-session-search-call.test.ts": 48, @@ -503,7 +501,6 @@ "src/main/ai-vault/transcripts/session-document-discarded-scalar-memory.test.ts": 441, "src/main/ai-vault/transcripts/session-document-stream-contract.test.ts": 279, "src/main/ai-vault/transcripts/session-document-stream-parity.test.ts": 237, - "src/main/ai-vault/transcripts/session-document-stream-projection.test.ts": 183, "src/main/ai-vault/session-list-result-validation.test.ts": 118, "src/main/ai-vault/session-newest-files.test.ts": 115, "src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts": 2723, @@ -538,7 +535,6 @@ "src/main/ai-vault/scanners/muse/session-scanner-muse.test.ts": 492, "src/main/ai-vault/scanners/omp/session-scanner-omp-subagent-listing.test.ts": 197, "src/main/ai-vault/scanners/omp/session-scanner-omp-subagent-prune.test.ts": 488, - "src/main/ai-vault/scanners/omp/session-scanner-omp-subagent-transcripts.test.ts": 183, "src/main/ai-vault/scanners/opencode/session-scanner-opencode-cancellation.test.ts": 1032, "src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-native-worker.test.ts": 1047, "src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.test.ts": 182, @@ -793,7 +789,6 @@ "src/main/browser/network/tunnels/remote-browser-socks-server.test.ts": 309, "src/main/browser/cdp/snapshots/snapshot-engine.test.ts": 48, "src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts": 643, - "src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts": 53, "src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts": 678, "src/main/browser/routing/local-host-partitions/wsl-host-browser-route-partition.test.ts": 753, "src/main/claude-accounts/sign-in/claude-account-folder.test.ts": 153, @@ -858,7 +853,6 @@ "src/main/claude/hooks/post-compact-hook-command.test.ts": 314, "src/main/claude/structured/claude-structured-conversation-stop.test.ts": 884, "src/main/claude/structured/claude-structured-dispatch-admission.test.ts": 426, - "src/main/claude/structured/claude-structured-dispatch-content.test.ts": 176, "src/main/claude/structured/claude-structured-dispatch-queue-boundary.test.ts": 911, "src/main/claude/structured/claude-structured-effort-reporting.test.ts": 1127, "src/main/claude/structured/claude-structured-execution-recording.test.ts": 2228, @@ -1097,7 +1091,6 @@ "src/main/crash-reporting/reports/crash-report-store.test.ts": 438, "src/main/crash-reporting/minidumps/minidump-crash-signature.test.ts": 87, "src/main/crash-reporting/memory/renderer-heap-allocation-sites.test.ts": 62, - "src/main/credentials/saved-credential-readability.test.ts": 56, "src/main/cursor/hook-command.live-shell.test.ts": 488, "src/main/cursor/hook-service.test.ts": 360, "src/main/daemon/pty-subprocess/testing/agent-startup-prompt-latency.node-pty.test.ts": 2576, @@ -1214,7 +1207,6 @@ "src/main/daemon/history/restoration/testing/history-reader.test.ts": 322, "src/main/daemon/admission/testing/host-terminal-policy.test.ts": 383, "src/main/daemon/health/testing/issue-6814-daemon-failure-classification.test.ts": 623, - "src/main/daemon/admission/testing/legacy-restore-records.test.ts": 487, "src/main/daemon/executable-host/macos/testing/macos-daemon-bundle-retirement.test.ts": 73, "src/main/daemon/executable-host/macos/testing/macos-daemon-bundle.test.ts": 152, "src/main/daemon/executable-host/macos/testing/macos-daemon-launchd.test.ts": 297, @@ -1489,7 +1481,6 @@ "src/main/grok/windows-hook-launcher-chain.test.ts": 175, "src/main/hang-watchdog/hang-detection-marker.test.ts": 68, "src/main/hang-watchdog/hang-watchdog-detection-loop.test.ts": 45, - "src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts": 74, "src/main/hang-watchdog/previous-hang-detection.test.ts": 151, "src/main/hermes/hermes-config-comment-boundaries.test.ts": 577, "src/main/hermes/hermes-config-document.test.ts": 252, @@ -1500,7 +1491,6 @@ "src/main/hermes/hook-service.test.ts": 589, "src/main/workspace-hooks/hook-termination-real-process.test.ts": 3284, "src/main/workspace-hooks/hooks-archive-exit-observation.test.ts": 339, - "src/main/filesystem/host-checkout-removal.test.ts": 52, "src/main/filesystem/host-tree-removal-asar.electron.test.ts": 308, "src/main/host/deferred-secret-protection-report.test.ts": 81, "src/main/host/electron-manual-redirect-fetch.test.ts": 52, @@ -1592,7 +1582,6 @@ "src/main/ipc/local-worktree-runtime-options.test.ts": 174, "src/main/ipc/macos-keyboard-layout-change-notifications.test.ts": 51, "src/main/ipc/markdown-documents-ripgrep-real.test.ts": 314, - "src/main/ipc/mobile.test.ts": 1861, "src/main/ipc/notebook-project-link.test.ts": 548, "src/main/ipc/notifications-message-formatting.test.ts": 229, "src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts": 2761, @@ -1711,7 +1700,6 @@ "src/main/jcode/hook-gate-script.test.ts": 155, "src/main/jcode/hook-service.test.ts": 150, "src/main/jira/attachments/image-read.test.ts": 248, - "src/main/jira/attachments/images.test.ts": 97, "src/main/jira/attachments/legacy-cancellation.test.ts": 135, "src/main/jira/authenticated-request-image-limit.test.ts": 67, "src/main/jira/client-scoped-token.test.ts": 500, @@ -2004,7 +1992,6 @@ "src/main/persistence/migrating-orcad-catalog/terminal-history/persistence-orcad-migration-terminal-restore-hints.test.ts": 2098, "src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.test.ts": 795, "src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts": 1245, - "src/main/persistence/moving-wsl-projects/orchestration/wsl-move-orchestrator-user-choices.test.ts": 638, "src/main/persistence/moving-wsl-projects/quiescence/wsl-move-quiesce.test.ts": 413, "src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-shell-history-blobs.test.ts": 194, "src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-scrollback.test.ts": 466, @@ -2017,7 +2004,6 @@ "src/main/persistence/persistence-protected-secret-write-race.test.ts": 2083, "src/main/persistence/persistence-remote-session-startup.test.ts": 1689, "src/main/persistence/persistence-single-serialize.test.ts": 1950, - "src/main/persistence/profile-state-cutover-fixture.test.ts": 1834, "src/main/persistence/profile-state-cutover-soak.test.ts": 2754, "src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.test.ts": 150, "src/main/persistence/profile-state/access/profile-state-access-process.test.ts": 679, @@ -2132,7 +2118,6 @@ "src/main/plugins/panels/plugin-frame-source-map-location.test.ts": 208, "src/main/plugins/panels/plugin-panel-bridge-replay.test.ts": 3287, "src/main/plugins/panels/plugin-panel-controller.test.ts": 298, - "src/main/plugins/panels/plugin-panel-image.test.ts": 202, "src/main/plugins/panels/plugin-panel-webrtc.electron.test.ts": 4804, "src/main/plugins/panels/plugin-source-transpile-client.test.ts": 345, "src/main/plugins/plugin-audit-log-scaling.test.ts": 54, @@ -2193,7 +2178,6 @@ "src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts": 558, "src/main/providers/local-pty/local-pty-shell-startup-command.node-pty.test.ts": 315, "src/main/providers/shell-launch/windows/shell-preflight-runtime.windows.test.ts": 126, - "src/main/providers/working-directory/validation.test.ts": 163, "src/main/pty/process-retirement/pty-descendant-exit-verification.test.ts": 155, "src/main/pty/process-retirement/pty-descendant-termination-libproc.test.ts": 135, "src/main/pty/process-retirement/pty-descendant-termination.test.ts": 200, @@ -2317,7 +2301,6 @@ "src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.integration.test.ts": 4022, "src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.test.ts": 315, "src/main/runtime/browser/client-pages/client-hosted-browser-row-publication.test.ts": 73, - "src/main/runtime/terminal/output/codex-notice-terminal-status.test.ts": 4438, "src/main/runtime/terminal/wait/codex-startup-paste-transcripts.test.ts": 439, "src/main/runtime/client/navigation/created-mobile-session-tab-caller-selection.test.ts": 4566, "src/main/runtime/rpc/server/pairing/delegated-mobile-device.integration.test.ts": 5255, @@ -2484,7 +2467,6 @@ "src/main/runtime/orchestration/workers/lifecycle/lifecycle-caller-edges.test.ts": 522, "src/main/runtime/orchestration/workers/lifecycle/lifecycle-reconciliation.test.ts": 884, "src/main/runtime/orchestration/workers/reports/lightweight-run-worker-exit-escalation.test.ts": 5194, - "src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-eligibility.test.ts": 594, "src/main/runtime/orchestration/db/messages/mailbox-pointer-release-query.test.ts": 658, "src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-stage.test.ts": 739, "src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-submit.test.ts": 1513, @@ -2535,7 +2517,6 @@ "src/main/runtime/push/push-host-proof-vector.test.ts": 65, "src/main/runtime/push/push-host-proof.test.ts": 139, "src/main/runtime/push/push-policy-pipeline.integration.test.ts": 343, - "src/main/runtime/push/push-preferences.test.ts": 59, "src/main/runtime/push/push-registration-races.test.ts": 360, "src/main/runtime/push/push-registration-rpc.test.ts": 5376, "src/main/runtime/push/push-unpair-persistence.test.ts": 4686, @@ -2825,7 +2806,6 @@ "src/main/runtime/workspaces/references/runtime-reference-find.test.ts": 245, "src/main/runtime/repositories/runtime-repo-update-worktree-refresh.test.ts": 4375, "src/main/runtime/repositories/runtime-repository-clone-host-dedupe.test.ts": 874, - "src/main/runtime/repositories/runtime-repository-issue-command.test.ts": 557, "src/main/runtime/repositories/runtime-repository-registration-controller.test.ts": 742, "src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts": 4402, "src/main/runtime/rpc/server/runtime-rpc-delegated-device-sync.test.ts": 4986, @@ -2836,7 +2816,6 @@ "src/main/runtime/rpc/server/runtime-rpc-mobile-terminal-streaming.test.ts": 27089, "src/main/runtime/rpc/server/runtime-rpc-pairing-mode-persistence.test.ts": 5012, "src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts": 4796, - "src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts": 4567, "src/main/runtime/rpc/server/runtime-rpc-relay-pairing.test.ts": 5823, "src/main/runtime/rpc/server/runtime-rpc-request-authorization.test.ts": 5533, "src/main/runtime/rpc/server/runtime-rpc-ssh-wedge-isolation.test.ts": 4438, @@ -2937,7 +2916,6 @@ "src/main/runtime/terminal/output/tail/terminal-tail-redraw-spans.test.ts": 166, "src/main/runtime/terminal-tail-redraw-wall-time.test.ts": 43418, "src/main/runtime/terminal/output/tail/terminal-tail-sentinel-index.test.ts": 3649, - "src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts": 168, "src/main/runtime/terminal/wait/terminal-wait-detection.test.ts": 220, "src/main/runtime/terminal/wait/terminal-wait-name-only-idle.test.ts": 5018, "src/main/runtime/terminal/wait/terminal-wait-tail-window.test.ts": 257, @@ -3010,7 +2988,6 @@ "src/main/ssh/config/ssh-config-host-picker.test.ts": 221, "src/main/ssh/config/ssh-config-loader-regression.test.ts": 102, "src/main/ssh/config/ssh-config-loader.test.ts": 110, - "src/main/ssh/config/ssh-config-parser-host-patterns.test.ts": 50, "src/main/ssh/config/ssh-config-parser.test.ts": 315, "src/main/ssh/config/ssh-g-config-resolution.test.ts": 125, "src/main/ssh/host-keys/ssh-known-hosts-source.test.ts": 124, @@ -3116,7 +3093,6 @@ "src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.test.ts": 283, "src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts": 177, "src/main/ssh/remote-host/ssh-remote-platform.test.ts": 51, - "src/main/ssh/authentication/ssh-security-key-identity.test.ts": 142, "src/main/ssh/system-transport/ssh-system-transport.integration.test.ts": 401, "src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts": 971, "src/main/ssh/system-transport/system-ssh-binary.test.ts": 53, @@ -3171,7 +3147,6 @@ "src/main/stats/agent-session-stats-feed.test.ts": 79, "src/main/stats/agent-session-transition-recorder.test.ts": 722, "src/main/stats/collector-async-save.test.ts": 497, - "src/main/power/system-power-lifecycle.test.ts": 42, "src/main/power/system-resume-broadcast.test.ts": 67, "src/main/telemetry/client-agent-dashboard-snapshot.test.ts": 201, "src/main/telemetry/client-deferred-start.test.ts": 8659, @@ -3275,7 +3250,6 @@ "src/main/workspaces/creation/preparation/worktree-create-preparation-cancellation.test.ts": 407, "src/main/workspaces/creation/preparation/worktree-create-preparation-claim.test.ts": 52, "src/main/workspaces/creation/preparation/worktree-create-preparation-contention.test.ts": 426, - "src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.test.ts": 373, "src/main/workspaces/creation/preparation/worktree-create-preparation-wsl-root.test.ts": 402, "src/main/workspaces/creation/preparation/worktree-create-preparation.test.ts": 393, "src/main/workspaces/removal/worktree-failed-removal.test.ts": 749, @@ -4336,7 +4310,6 @@ "src/renderer/src/store/plugins/localization/plugin-language-packs.test.ts": 377, "src/renderer/src/store/projects/project-catalog-null-field-ingest.test.ts": 309, "src/renderer/src/store/repos/repo-removal.test.ts": 799, - "src/renderer/src/store/slices/agent-status/agent-status-pane-owner-reclaim.test.ts": 1899, "src/renderer/src/store/slices/agent-status/agent-status-ack-cleanup.test.ts": 1776, "src/renderer/src/store/slices/agent-status/agent-status-batch.test.ts": 1933, "src/renderer/src/store/slices/agent-status/agent-status-drop-ipc.test.ts": 2205, @@ -4407,16 +4380,13 @@ "src/renderer/src/store/terminals/store-sleep-pane-hibernation.test.ts": 1932, "src/renderer/src/store/slices/worktrees/teardown/tab-worktree-orphan-map-purge-leak.test.ts": 1936, "src/renderer/src/store/slices/tabs/tabs-close-dangling-group.test.ts": 1849, - "src/renderer/src/store/slices/tabs/tabs-hydration-group-validation.test.ts": 249, "src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1703, "src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts": 1751, "src/renderer/src/store/terminals/terminal-quick-command-hosts.test.ts": 1759, "src/renderer/src/store/terminals/terminals-hydration-canonical-pty-overlap.test.ts": 1946, "src/renderer/src/store/terminals/terminals-hydration-canonical-rows.test.ts": 1680, - "src/renderer/src/store/slices/ui/ui-host-filter-sync.test.ts": 597, "src/renderer/src/store/slices/ui/ui-modal-slot-dismissal.test.ts": 662, "src/renderer/src/store/slices/workspace-attention/workspace-unread-flag-host-raises.test.ts": 1914, - "src/renderer/src/store/slices/workspace-attention/workspace-unread-on-screen-characterization.test.ts": 1780, "src/renderer/src/store/slices/worktrees/teardown/workspace-chat-draft-removal.test.ts": 1896, "src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-browse.test.ts": 69, "src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts": 750, @@ -4674,7 +4644,6 @@ "src/shared/github/project-board-columns.test.ts": 64, "src/shared/github/project-identity.test.ts": 33, "src/shared/github/project-ref-input.test.ts": 40, - "src/shared/github/pull-request-auto-merge-availability.test.ts": 52, "src/shared/github/repository-identity-key.test.ts": 39, "src/shared/grok-model-list-probe.test.ts": 54, "src/shared/grok-session-paths.test.ts": 104, @@ -4695,7 +4664,6 @@ "src/shared/jira/jira-issue-url.test.ts": 55, "src/shared/jira/jira-jql-predicate.test.ts": 50, "src/shared/jira/jira-project-reference.test.ts": 248, - "src/shared/jira/jira-saved-filters.test.ts": 48, "src/shared/json-text-structure-limit.test.ts": 67, "src/shared/json-token-reader.test.ts": 360, "src/shared/keybindings-conflicts.test.ts": 133, @@ -4753,7 +4721,6 @@ "src/shared/native-chat/tools/native-chat-edit-normalize.test.ts": 298, "src/shared/native-chat/tools/native-chat-tool-attribution-allocation.test.ts": 105, "src/shared/native-chat/tools/native-chat-tool-identity.test.ts": 73, - "src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts": 235, "src/shared/native-chat/tools/native-chat-tool-preview-prefix.test.ts": 46, "src/shared/native-chat/tools/native-chat-turn-membership-derived-tool-row.test.ts": 268, "src/shared/native-chat/transcript/native-chat-image-transcript-markers.test.ts": 94, @@ -4823,7 +4790,6 @@ "src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts": 185, "src/shared/plugins/artifacts/plugin-theme-artifact.test.ts": 165, "src/shared/plugins/authoring/plugin-host-typings.test.ts": 2140, - "src/shared/plugins/catalog/plugin-catalog.test.ts": 630, "src/shared/plugins/catalog/plugin-kill-list.test.ts": 195, "src/shared/plugins/catalog/plugin-marketplace.test.ts": 246, "src/shared/plugins/catalog/plugin-repository-link.test.ts": 205, @@ -4834,7 +4800,6 @@ "src/shared/plugins/declarative/runtime/declarative-hot-reload.test.ts": 133, "src/shared/plugins/declarative/runtime/declarative-lifecycle.test.ts": 156, "src/shared/plugins/declarative/runtime/declarative-renderer.test.ts": 231, - "src/shared/plugins/declarative/runtime/declarative-storage-sync.test.ts": 190, "src/shared/plugins/declarative/testing/orca-testing-hooks.test.ts": 506, "src/shared/plugins/declarative/testing/orca-testing-worker.test.ts": 480, "src/shared/plugins/declarative/testing/testing-editor-host.test.ts": 197, @@ -4875,7 +4840,6 @@ "src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts": 66, "src/shared/published-pane-agent-identity.test.ts": 89, "src/shared/qoder-agent.test.ts": 445, - "src/shared/queued-message-edit-lease.test.ts": 257, "src/shared/quick-open-filter.renderer-safety.test.ts": 58, "src/shared/quick-open-filter.test.ts": 85, "src/shared/quick-open-git-directory-collapse.test.ts": 80, @@ -4965,17 +4929,13 @@ "src/shared/sidebar-feed-client/sidebar-feed-reader.test.ts": 438, "src/shared/sidebar-list/sidebar-feed-rows.test.ts": 377, "src/shared/sidebar-list/sidebar-inputs-feed-installer.test.ts": 100, - "src/shared/sidebar-list/sleeping-sweep-retention.test.ts": 62, "src/shared/sidebar-list/smart-sort.test.ts": 131, - "src/shared/sidebar-list/stamp-order.test.ts": 86, - "src/shared/sidebar-list/workspace-review-facts.test.ts": 191, "src/shared/skill-package-manifest.test.ts": 188, "src/shared/skill-path-containment.test.ts": 49, "src/shared/sleeping-record-legacy-pane-key.test.ts": 59, "src/shared/source-control/listing/source-control-discard-all-sequence.test.ts": 50, "src/shared/source-scan/source-tree-scan.test.ts": 50, "src/shared/source-scan/source-tree-walk.test.ts": 62, - "src/shared/ssh-pending-pty-kill.test.ts": 43, "src/shared/ssh-pty-id.test.ts": 51, "src/shared/ssh-retained-payload-admission.test.ts": 69, "src/shared/startup-command-staging.node-pty.test.ts": 2207, diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 6caf834cde6..a803b015695 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -105,7 +105,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/git/repositories/discovery/repo-detection.test.ts', 'src/main/native-chat/paste-files/native-chat-paste-files.test.ts', 'src/main/computer/desktop-script/runtime-host/desktop-script-serve-channel.test.ts', - 'src/main/providers/working-directory/validation.test.ts', 'src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts', 'src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-output-capture.test.ts', 'src/main/native-chat/agent-session-journal/**/*.test.ts', diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 172860c6aec..1456a05aef8 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -7,7 +7,6 @@ import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node- const contracts = [ 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts', 'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx', - 'src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts', 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts', 'src/main/codex-usage/scanner-incremental-append.test.ts', 'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts', diff --git a/mobile/src/components/markdown/math/mobile-markdown-math.test.ts b/mobile/src/components/markdown/math/mobile-markdown-math.test.ts deleted file mode 100644 index b7589133c40..00000000000 --- a/mobile/src/components/markdown/math/mobile-markdown-math.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { Nodes } from 'mdast' -import { describe, expect, it } from 'vitest' -import { parseMobileMarkdownTree } from '../parsing/mobile-markdown-tree' - -/** Formulas as `D:` (display) or `I:` (inline) plus the text drawn around them. */ -function drawn(source: string, chatMath = true): { math: string[]; text: string } { - const math: string[] = [] - let text = '' - const walk = (node: Nodes): void => { - if (node.type === 'math') { - math.push(`D:${node.value}`) - } else if (node.type === 'inlineMath') { - math.push(`I:${node.value}`) - } else if (node.type === 'text') { - text += node.value - } - if ('children' in node) { - node.children.forEach(walk) - } - } - walk(parseMobileMarkdownTree(source, false, chatMath)) - return { math, text } -} - -// Expected values are what desktop chat's remark grammar produces for the same source. -describe('math in mobile Markdown follows desktop chat', () => { - it.each([ - [ - 'the PR line-count cell', - '$\\color{#1a7f37}{\\Huge{\\mathbf{+}}}$\u200b37', - ['I:\\color{#1a7f37}{\\Huge{\\mathbf{+}}}'], - '\u200b37' - ], - [ - 'a price with operators', - 'Keep $5 + 2$ typed, render $5+2$', - ['I:5+2'], - 'Keep $5 + 2$ typed, render ' - ], - ['a block that interrupts a paragraph', 'para\n$$\nx=1\n$$\nafter', ['D:x=1'], 'paraafter'], - ['display formulas alone in a paragraph', '$$a$$ $$b$$', ['D:a', 'D:b'], ''], - ['inline and bracket delimiters', '\\(a\\) and \\[b\\]', ['I:a', 'I:b'], ' and '], - ['a citation', '\\[1, 2\\]', [], '[1, 2]'], - ['a formula in a link label', '[$x$](http://a)', [], '$x$'], - ['a closed math fence', '```math\nx^2\n```', ['D:x^2'], ''] - ])('%s', (_name, source, math, text) => { - expect(drawn(source)).toEqual({ math, text }) - }) -}) - -describe('math in GitHub text (PRs, Tasks, files)', () => { - it('keeps an unclosed $$ as text instead of swallowing what follows', () => { - expect( - parseMobileMarkdownTree('$$ savings\n\n## Summary', false).children.map((n) => n.type) - ).toEqual(['paragraph', 'heading']) - }) - - it('reads dollar math but leaves escaped brackets as brackets', () => { - expect(drawn('\\[Bug\\] $x$ and \\(y\\)', false)).toEqual({ - math: ['I:x'], - text: '[Bug] and (y)' - }) - }) -}) diff --git a/src/cli/arguments/shell-command-quote.test.ts b/src/cli/arguments/shell-command-quote.test.ts deleted file mode 100644 index a0a53b547d3..00000000000 --- a/src/cli/arguments/shell-command-quote.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { quoteCliCommandArgument } from './shell-command-quote' - -describe('quoteCliCommandArgument on Windows', () => { - afterEach(() => { - vi.restoreAllMocks() - }) - - it('keeps PowerShell variables and escapes literal', () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - expect(quoteCliCommandArgument('path:C:/work/$review')).toBe("'path:C:/work/$review'") - expect(quoteCliCommandArgument("C:/it's `n $(x)")).toBe("'C:/it''s `n $(x)'") - expect(quoteCliCommandArgument('path:C:/$x&whoami&rem')).toBe('"path:C:/$x&whoami&rem"') - expect(quoteCliCommandArgument('{"a": 1}')).toBe(`'{"a": 1}'`) - expect(quoteCliCommandArgument('path:C:/my work')).toBe('"path:C:/my work"') - }) -}) diff --git a/src/main/acp/acp-dialects/antigravity-dialect.test.ts b/src/main/acp/acp-dialects/antigravity-dialect.test.ts deleted file mode 100644 index 02ee27a0f98..00000000000 --- a/src/main/acp/acp-dialects/antigravity-dialect.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { expect, it } from 'vitest' -import fixture from '../fixtures/antigravity-v1.4.3-options.json' -import { - NewSessionResponseSchema, - SessionConfigOptionSchema -} from '../generated/acp-protocol.generated' -import { acpSelectChoices } from '../options/acp-select-choices' -import { AcpStructuredOptions } from '../options/acp-structured-options' -import { ANTIGRAVITY_ACP_DIALECT } from './antigravity-dialect' - -it("reads other model families' efforts from the variants the session advertises", () => { - const options = new AcpStructuredOptions(ANTIGRAVITY_ACP_DIALECT) - const efforts = () => - Object.fromEntries( - options - .read() - .models.map((model) => [ - model.id, - model.effortsKnown === false - ? 'unknown' - : model.efforts.map(({ value, label }) => `${value}:${label}`) - ]) - ) - const flash = ['low:Low', 'medium:Medium', 'high:High'] - options.adoptSession(NewSessionResponseSchema.parse(fixture.session), 'new') - expect(efforts()).toEqual({ - 'gemini-3.8-flash': flash, - 'gemini-3.7-flash': flash, - 'gemini-3.6-flash': flash, - 'gemini-3.5-flash': flash, - 'gemini-3.1-pro': ['low:Low', 'high:High'] - }) - // The running model's live menu outranks its family's variants, even when it withdraws a level. - options.adoptConfigOptions( - SessionConfigOptionSchema.array() - .parse(fixture.pro.configOptions) - .map((option) => - option.type === 'select' && option.category === 'thought_level' - ? { - ...option, - currentValue: 'high', - options: acpSelectChoices(option).filter(({ value }) => value === 'high') - } - : option - ) - ) - expect(efforts()['gemini-3.1-pro']).toEqual(['high:High']) - expect(efforts()['gemini-3.8-flash']).toEqual(flash) -}) diff --git a/src/main/ai-vault-search/query/session-search-typo-policy.test.ts b/src/main/ai-vault-search/query/session-search-typo-policy.test.ts deleted file mode 100644 index 094b1244fb5..00000000000 --- a/src/main/ai-vault-search/query/session-search-typo-policy.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type SyncDatabase from '../../sqlite/sync-database' -import { openSessionSearchIndexFile } from '../storage/session-search-index-test-fixture' -import { ensureSessionSearchQuerySchema } from '../storage/session-search-query-schema' -import { SessionSearchTypoRepair } from './session-search-typo-repair' - -function addSession(db: SyncDatabase, id: number): void { - db.prepare( - `INSERT INTO sessions(id,agent,session_id,file_path,title,resume_command) - VALUES (?, 'claude', ?, '/synthetic/fixture', 'typo fixture', '')` - ).run(id, String(id)) -} - -function addTerm(db: SyncDatabase, sessionRowId: number, term: string): void { - const rowid = db - .prepare("INSERT INTO messages(session_row_id, role) VALUES (?, 'user')") - .run(sessionRowId).lastInsertRowid - db.prepare('INSERT INTO messages_fts(rowid, user_text) VALUES (?, ?)').run(Number(rowid), term) -} - -describe('typo repair policy', () => { - it('falls through to the best candidate a reader can still reach', async () => { - const index = await openSessionSearchIndexFile('ss-typo-orphaned') - try { - const { db } = index - ensureSessionSearchQuerySchema(db) - addSession(db, 1) - // The closer match belongs to absent session 2, simulating an unfinished orphan drain. - for (const [term, session] of [ - ['coalesces', 2], - ['coalesces', 2], - ['coalesced', 1], - ['coalesced', 1] - ] as const) { - addTerm(db, session, term) - } - expect(db.prepare("SELECT doc FROM messages_vocab WHERE term='coalesces'").get()).toEqual({ - doc: 2 - }) - expect(new SessionSearchTypoRepair(db).correct('coalescs', 'all')).toBe('coalesced') - } finally { - await index.close() - } - }) -}) diff --git a/src/main/ai-vault/scanners/omp/session-scanner-omp-subagent-transcripts.test.ts b/src/main/ai-vault/scanners/omp/session-scanner-omp-subagent-transcripts.test.ts deleted file mode 100644 index c435ae6349f..00000000000 --- a/src/main/ai-vault/scanners/omp/session-scanner-omp-subagent-transcripts.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { parseMessageGraphSessionContent } from '../session-scanner-graph-parsers' - -const SESSION_STEM = '2026-05-01T10-00-00-000Z_cccccccc-dddd-4eee-8fff-000000000000' - -let tempRoots: string[] = [] - -afterEach(async () => { - await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) - tempRoots = [] -}) - -async function makeWorkspaceDir(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-omp-subagents-')) - tempRoots.push(root) - return root -} - -describe('withOmpSubagentTranscriptCount host gating', () => { - const content = JSON.stringify({ - type: 'session', - version: 3, - id: 'cccccccc-dddd-4eee-8fff-000000000000', - cwd: '/repo/app', - timestamp: '2026-05-01T10:00:00.000Z' - }) - - it('never counts a local artifact dir for a remote-host transcript', async () => { - const workspace = await makeWorkspaceDir() - const parentPath = join(workspace, `${SESSION_STEM}.jsonl`) - // A same-path local artifact directory must not enrich a transcript fetched from an SSH host. - await mkdir(join(workspace, SESSION_STEM), { recursive: true }) - await writeFile(join(workspace, SESSION_STEM, 'AuthAndPreflight.jsonl'), '') - const file = { path: parentPath, mtimeMs: 0, modifiedAt: '2026-05-01T10:00:00.000Z' } - - const remote = await parseMessageGraphSessionContent('omp', file, content, 'linux', { - executionHostId: 'ssh:host' - }) - const local = await parseMessageGraphSessionContent('omp', file, content, 'darwin') - - expect(remote?.subagentTranscriptCount).toBe(0) - expect(local?.subagentTranscriptCount).toBe(1) - }) -}) diff --git a/src/main/ai-vault/scanners/openclaw/openclaw-session-layout.test.ts b/src/main/ai-vault/scanners/openclaw/openclaw-session-layout.test.ts deleted file mode 100644 index 037a458f577..00000000000 --- a/src/main/ai-vault/scanners/openclaw/openclaw-session-layout.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join, relative } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AI_VAULT_AGENT_SOURCES } from '../../discovery/session-scanner-agent-sources' -import { walkSessionFiles } from '../../discovery/session-scanner-discovery' - -// The layout reported in #11394: canonical sessions beside an embedded Codex home. -const CANONICAL = ['main', 'sessions', 'canonical.jsonl'] -const NESTED_CANONICAL = ['main', 'sessions', 'archive', 'older.jsonl'] -const EMBEDDED_CODEX = ['main', 'agent', 'codex-home', 'sessions', '2026', 'rollout-x.jsonl'] - -let home: string -let agentsDir: string - -beforeEach(async () => { - home = await mkdtemp(join(tmpdir(), 'openclaw-layout-')) - agentsDir = join(home, '.openclaw', 'agents') - for (const segments of [CANONICAL, NESTED_CANONICAL, EMBEDDED_CODEX]) { - const path = join(agentsDir, ...segments) - await mkdir(join(path, '..'), { recursive: true }) - await writeFile(path, '{}\n') - } -}) - -afterEach(async () => { - await rm(home, { recursive: true, force: true }) -}) - -function relativeToAgents(paths: readonly string[]): string[] { - return paths.map((path) => relative(agentsDir, path).split(/[\\/]/).join('/')).sort() -} - -const EXPECTED = [CANONICAL.join('/'), NESTED_CANONICAL.join('/')].sort() - -describe('OpenClaw session discovery', () => { - it('walks only each agent sessions tree on this host', async () => { - const source = AI_VAULT_AGENT_SOURCES.openclaw - const files = await walkSessionFiles(agentsDir, 'openclaw', [], { - extensions: new Set(source.extensions), - filePredicate: source.filePredicate, - directoryPredicate: source.directoryPredicate - }) - - expect(relativeToAgents(files)).toEqual(EXPECTED) - }) -}) diff --git a/src/main/ai-vault/transcripts/session-document-stream-projection.test.ts b/src/main/ai-vault/transcripts/session-document-stream-projection.test.ts deleted file mode 100644 index 09dc335d090..00000000000 --- a/src/main/ai-vault/transcripts/session-document-stream-projection.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { - parseDevinSessionContent, - parseDevinSessionDocument -} from '../scanners/devin/session-scanner-devin-parser' -import { readStreamedSessionDocument } from './session-document-stream' -const file = { path: '/devin/test.json', modifiedAt: new Date(0).toISOString(), mtimeMs: 0 } -const options = { - executionHostId: 'ssh:projection' as const, - executionHostPlatform: 'darwin' as const -} -async function* bytes(content: string) { - const b = Buffer.from(content) - for (let i = 0; i < b.length; i += 7) { - yield b.subarray(i, i + 7) - } -} -describe('Devin consumed metadata projection', () => { - for (const suffix of [ - '{}', - 'null', - '[]', - '{"model":"last"}', - '{"model_name":"last-name","model":"fallback"}', - '{"model_name":[],"model":123}', - '{"model":"old","model":"last"}' - ]) { - it(`preserves duplicate root agent ${suffix}`, async () => { - const content = `{"agent":{"model_name":"old"},"steps":[{"role":"assistant","text":"message","metadata":{"generation_model":"step"}}],"generation_model":"root-fallback","agent":${suffix}}` - expect(await parseDevinSessionDocument(file, bytes(content), 'darwin', options)).toEqual( - parseDevinSessionContent(file, content, 'darwin', options) - ) - }) - } - it('retains only model fields from the agent object', async () => { - const result = await readStreamedSessionDocument({ - bytes: bytes( - '{"agent":{"ignored":{"many":[1,2,3]},"model_name":"root","model":"fallback"},"steps":[]}' - ), - arrayKey: 'steps', - fields: [], - objectFields: { agent: ['model_name', 'model'] }, - create: () => 0, - consume: () => {} - }) - expect(result).toEqual({ - record: { agent: { model_name: 'root', model: 'fallback' } }, - state: 0 - }) - }) -}) diff --git a/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding.test.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding.test.ts deleted file mode 100644 index a0b1ca9126e..00000000000 --- a/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { EventEmitter } from 'node:events' -import { expect, it, vi } from 'vitest' -import { setupGuestShortcutForwarding } from './browser-guest-shortcut-forwarding' - -vi.mock('../../../cdp/input/agent-input-injection', () => ({ isAgentInjectingInput: () => false })) - -it('forwards a modifier double tap without arming it during composition', () => { - const guest = new EventEmitter() - const send = vi.fn() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: forwarding uses only the guest event emitter. - const webContents = guest as unknown as Electron.WebContents - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: forwarding uses only send on this renderer. - const renderer = { send } as unknown as Electron.WebContents - setupGuestShortcutForwarding({ - browserTabId: 'page', - guest: webContents, - resolveRenderer: () => renderer, - isLocalRenderer: () => true, - getKeybindings: () => ({ 'view.plugins': ['DoubleTap+Mod'] }) - }) - const event = { preventDefault: vi.fn() } - const shift = - process.platform === 'darwin' - ? { key: 'Meta', code: 'MetaLeft', meta: true } - : { key: 'Control', code: 'ControlLeft', control: true } - guest.emit('before-input-event', event, { ...shift, type: 'keyDown', isComposing: true }) - guest.emit('before-input-event', event, { ...shift, type: 'keyUp', isComposing: true }) - guest.emit('before-input-event', event, { ...shift, type: 'keyDown' }) - expect(send).not.toHaveBeenCalled() - guest.emit('before-input-event', event, { ...shift, type: 'keyUp' }) - guest.emit('before-input-event', event, { ...shift, type: 'keyDown' }) - expect(send).toHaveBeenCalledWith( - 'ui:browserPageTabShortcut', - expect.objectContaining({ doubleTapModifier: process.platform === 'darwin' ? 'Cmd' : 'Ctrl' }) - ) -}) diff --git a/src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts b/src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts deleted file mode 100644 index 16aed7c3e91..00000000000 --- a/src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { once } from 'node:events' -import { connect, createServer, type AddressInfo, type Socket } from 'node:net' -import { afterEach, describe, expect, it } from 'vitest' -import { SystemSshSocksClientSocket } from './system-ssh-socks-client-socket' - -const servers: ReturnType[] = [] - -afterEach(async () => { - await Promise.all( - servers.splice(0).map((server) => new Promise((resolve) => server.close(() => resolve()))) - ) -}) - -describe('SystemSshSocksClientSocket', () => { - it('carries the exact destination domain through the internal SOCKS handshake', async () => { - let accepted: Socket | undefined - let request: Buffer | undefined - const server = createServer((socket) => { - accepted = socket - socket.once('data', (greeting) => { - expect([...greeting]).toEqual([5, 1, 0]) - socket.write(new Uint8Array([5, 0])) - socket.once('data', (connectRequest) => { - request = - typeof connectRequest === 'string' ? Buffer.from(connectRequest) : connectRequest - socket.write(new Uint8Array([5, 0, 0, 1, 0, 0, 0, 0, 0, 0])) - }) - }) - }) - servers.push(server) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() as AddressInfo - const socket = new SystemSshSocksClientSocket( - { host: 'split-horizon.internal', port: 8443 }, - async () => connect({ host: '127.0.0.1', port: address.port }) - ) - socket.on('error', () => {}) - await once(socket, 'connect') - - const host = new TextEncoder().encode('split-horizon.internal') - expect(request).toEqual( - Buffer.from([5, 1, 0, 3, host.byteLength, ...host, (8443 >>> 8) & 0xff, 8443 & 0xff]) - ) - socket.destroy() - accepted?.destroy() - }) -}) diff --git a/src/main/claude/structured/claude-structured-dispatch-content.test.ts b/src/main/claude/structured/claude-structured-dispatch-content.test.ts deleted file mode 100644 index 8853e02215c..00000000000 --- a/src/main/claude/structured/claude-structured-dispatch-content.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import { claudeDispatchMessageContent } from './claude-structured-dispatch-content' - -function userMessage(blocks: AgentJournalMessageItem['blocks']): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks } -} - -const REMOTE_IMAGE = { type: 'image-ref' as const, url: 'https://example.test/a.png' } - -describe('claudeDispatchMessageContent', () => { - it('puts the text block last so a slash command still expands with an attachment', async () => { - const content = await claudeDispatchMessageContent( - userMessage([{ type: 'text', text: '/goal ship the parser' }, REMOTE_IMAGE]) - ) - - expect(content).toEqual([ - { type: 'image', source: { type: 'url', url: 'https://example.test/a.png' } }, - { type: 'text', text: '/goal ship the parser' } - ]) - }) - - it('sends a local image over the API per-image limit for Claude to shrink', async () => { - const directory = await mkdtemp(join(tmpdir(), 'orca-claude-image-')) - try { - const path = join(directory, 'retina-screenshot.png') - await writeFile(path, Buffer.alloc(6 * 1024 * 1024, 1)) - - const content = await claudeDispatchMessageContent(userMessage([{ type: 'image-ref', path }])) - - expect(content).toEqual([ - { - type: 'image', - source: { - type: 'base64', - media_type: 'image/png', - data: Buffer.alloc(6 * 1024 * 1024, 1).toString('base64') - } - } - ]) - } finally { - await rm(directory, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/credentials/saved-credential-readability.test.ts b/src/main/credentials/saved-credential-readability.test.ts deleted file mode 100644 index d693c19b732..00000000000 --- a/src/main/credentials/saved-credential-readability.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { _resetSecretStoreForTests, setSecretStore } from '../../shared/secure-storage/secret-store' -import { savedCredentialUnreadable } from './saved-credential-readability' - -const PREFIX = 'orca-test-key:v1:' -const SEAL = 'sealed-here:' - -let dir: string -let path: string - -beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orca-saved-credential-readability-')) - path = join(dir, 'key.enc') - setSecretStore({ - isEncryptionAvailable: () => true, - encryptString: (plainText) => Buffer.from(`${SEAL}${plainText}`), - decryptString: (cipher) => { - const text = cipher.toString() - if (!text.startsWith(SEAL)) { - throw new Error('not sealed by this store') - } - return text.slice(SEAL.length) - }, - describeProtectionGap: () => null - }) -}) - -afterEach(() => { - _resetSecretStoreForTests() - rmSync(dir, { recursive: true, force: true }) -}) - -function judge(contents: string): ReturnType { - writeFileSync(path, contents) - return savedCredentialUnreadable({ path, envelopePrefix: PREFIX }) -} - -function encrypted(cipher: Buffer): string { - return `${PREFIX}encrypted:${cipher.toString('base64')}` -} - -describe('savedCredentialUnreadable', () => { - it('reports a well-formed file another store sealed as sealed elsewhere', () => { - expect(judge(encrypted(Buffer.from('other-app-cipher')))).toBe('sealed-elsewhere') - }) - - it.each([ - ['an empty', ''], - ['a non-base64', 'not*base64!'] - ])('reports %s payload as unreadable, not sealed elsewhere', (_label, payload) => { - expect(judge(`${PREFIX}encrypted:${payload}`)).toBe('unreadable') - }) -}) diff --git a/src/main/daemon/admission/testing/legacy-restore-records.test.ts b/src/main/daemon/admission/testing/legacy-restore-records.test.ts deleted file mode 100644 index 0cadbe14461..00000000000 --- a/src/main/daemon/admission/testing/legacy-restore-records.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { LegacyRestoreRecords, type LegacyRestoreDetails } from '../legacy-restore-records' - -const details = (overrides: Partial = {}): LegacyRestoreDetails => ({ - sessionId: 'wt-1@@aaaa1111', - agent: 'claude', - cwd: '/repo', - command: 'claude --resume 6f1c', - worktreeId: 'wt-1', - identityDigest: null, - ...overrides -}) - -describe('LegacyRestoreRecords', () => { - let dir: string - let path: string - let now: number - - beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orca-legacy-restores-')) - path = join(dir, 'daemon-v44.legacy-restores.json') - now = 1_000_000 - }) - - afterEach(() => { - rmSync(dir, { recursive: true, force: true }) - }) - - const open = () => new LegacyRestoreRecords(path, { log: vi.fn() }, () => now) - - it('keeps a refused restore across a daemon restart, private to the user', () => { - open().record(details(), 'pressure') - expect(open().list()).toEqual([{ ...details(), reason: 'pressure', refusedAt: now }]) - if (process.platform !== 'win32') { - expect(statSync(path).mode & 0o077).toBe(0) - } - }) - - it('treats an unreadable file as empty and never throws into a spawn', () => { - writeFileSync(path, '{not json') - const records = open() - expect(records.list()).toEqual([]) - records.record(details(), 'pressure') - expect(JSON.parse(readFileSync(path, 'utf8')).records).toHaveLength(1) - const unwritable = new LegacyRestoreRecords(join(dir, 'missing', 'x.json'), { log: vi.fn() }) - expect(() => unwritable.record(details(), 'pressure')).not.toThrow() - }) -}) diff --git a/src/main/filesystem/host-checkout-removal.test.ts b/src/main/filesystem/host-checkout-removal.test.ts deleted file mode 100644 index d6cec479ae5..00000000000 --- a/src/main/filesystem/host-checkout-removal.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import * as fs from './asar-transparent-fs' -import { removeHostCheckout } from './host-tree-removal' - -vi.mock('./asar-transparent-fs', () => ({ - readdir: vi.fn(), - rm: vi.fn(), - unlink: vi.fn(), - rmdir: vi.fn(), - lstat: vi.fn() -})) -vi.mock('node:timers/promises', () => ({ - // Route promise backoff through the clock installed by vi.useFakeTimers. - // ast-grep-ignore: test-no-real-time-wait -- Schedules the installed fake clock for production backoff. - setTimeout: (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) -})) -const platform = process.platform -const root = 'C:/checkout-partition' -const busy = Object.assign(new Error('held child'), { code: 'EBUSY' }) -beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - vi.useFakeTimers() -}) -afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: platform }) - vi.useRealTimers() - vi.resetAllMocks() -}) - -it('settles public child promises before starting another pass or touching the marker', async () => { - vi.mocked(fs.readdir).mockResolvedValue(['held', 'pending', '.git']) - const pending = Promise.withResolvers() - vi.mocked(fs.rm).mockImplementation(async (target) => { - if (String(target).endsWith('held')) { - throw busy - } - await pending.promise - }) - const controller = new AbortController() - const removal = removeHostCheckout(root, async () => true, controller.signal).catch( - (error: unknown) => error - ) - await vi.advanceTimersByTimeAsync(10_000) - expect(fs.unlink).not.toHaveBeenCalled() - controller.abort() - pending.resolve() - await vi.runAllTimersAsync() - expect(await removal).toMatchObject({ name: 'AbortError' }) - expect(fs.readdir).toHaveBeenCalledOnce() -}) diff --git a/src/main/github/repositories/github-api-repository-origin-stand-in-real-git.test.ts b/src/main/github/repositories/github-api-repository-origin-stand-in-real-git.test.ts deleted file mode 100644 index c5f43c181c7..00000000000 --- a/src/main/github/repositories/github-api-repository-origin-stand-in-real-git.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { runProcess } from '@orca/process-host' -import { afterEach, expect, it } from 'vitest' -import { resolveIssueGitHubApiRepositorySource } from './github-api-repository' -import { resolvePrWorkItemSource } from '../client/list/work-item-list-request' -import { installRealWorkerThreadChildProcesses } from '../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' - -let directory: string | null = null - -afterEach(async () => { - if (directory) { - await rm(directory, { recursive: true, force: true }) - directory = null - } -}) - -async function createRepo(remotes: [name: string, url: (repo: string) => string][]) { - const repo = await mkdtemp(join(tmpdir(), 'orca-origin-stand-in-')) - directory = repo - const git = async (args: string[]) => { - const result = await runProcess({ program: 'git', args, cwd: repo }) - if (result.code !== 0) { - throw new Error(result.stderr) - } - } - await git(['init', '-q']) - await git(['init', '--bare', '-q', join(repo, 'mirror.git')]) - for (const [name, url] of remotes) { - await git(['remote', 'add', name, url(repo)]) - } - return repo -} - -it('reads GitHub from the remote standing in for an origin that is a local path (#42102)', async () => { - const repo = await createRepo([ - ['origin', (root) => join(root, 'mirror.git')], - ['github', () => 'https://github.com/acme/widgets.git'] - ]) - const expected = { owner: 'acme', repo: 'widgets', host: 'github.com' } - - expect((await resolveIssueGitHubApiRepositorySource(repo, undefined)).source).toEqual(expected) - expect((await resolvePrWorkItemSource(repo, undefined)).source).toEqual(expected) -}) - -installRealWorkerThreadChildProcesses() diff --git a/src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts b/src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts deleted file mode 100644 index 7e4b8e0f579..00000000000 --- a/src/main/hang-watchdog/main-thread-hang-watchdog-entry.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { consumeHangDetectionMarker } from './hang-detection-marker' - -import { runWatchdog } from './main-thread-hang-watchdog-entry' - -describe('watchdog worker entry', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(0) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('routes heartbeats and shuts down its timer and port', () => { - const markerPath = join(tmpdir(), `hang-watchdog-entry-${process.pid}.json`) - let onMessage: ((message: { type: 'heartbeat' | 'shutdown' }) => void) | undefined - const port = { - on: vi.fn( - (_event: 'message', listener: (message: { type: 'heartbeat' | 'shutdown' }) => void) => { - onMessage = listener - } - ), - close: vi.fn() - } - try { - runWatchdog( - { - parentPid: process.pid, - markerPath, - timeoutMs: 100, - checkIntervalMs: 25 - }, - port - ) - vi.advanceTimersByTime(75) - onMessage?.({ type: 'heartbeat' }) - vi.advanceTimersByTime(75) - expect(consumeHangDetectionMarker(markerPath)).toBeNull() - vi.advanceTimersByTime(50) - expect(consumeHangDetectionMarker(markerPath)).toMatchObject({ selfRecovered: false }) - - onMessage?.({ type: 'heartbeat' }) - expect(consumeHangDetectionMarker(markerPath)).toMatchObject({ selfRecovered: true }) - onMessage?.({ type: 'shutdown' }) - expect(port.close).toHaveBeenCalledOnce() - vi.advanceTimersByTime(1_000) - expect(port.close).toHaveBeenCalledOnce() - expect(consumeHangDetectionMarker(markerPath)).toBeNull() - } finally { - rmSync(markerPath, { force: true }) - } - }) -}) diff --git a/src/main/ipc/mobile.test.ts b/src/main/ipc/mobile.test.ts deleted file mode 100644 index 87b303a5f91..00000000000 --- a/src/main/ipc/mobile.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock } = vi.hoisted(() => ({ handleMock: vi.fn() })) - -vi.mock('electron', () => ({ - app: { isPackaged: false }, - ipcMain: { handle: handleMock }, - shell: { openExternal: vi.fn() } -})) -import { registerMobileHandlers } from './mobile' - -describe('registerMobileHandlers', () => { - const handlers = new Map unknown>() - - beforeEach(() => { - handlers.clear() - handleMock.mockReset() - handleMock.mockImplementation((channel: string, handler: (...args: unknown[]) => unknown) => { - handlers.set(channel, handler) - }) - }) - - it('rejects firewall mutation from a non-window renderer', async () => { - const runPowerShell = vi.fn() - const rpcServer = { getWebSocketEndpoint: () => 'ws://0.0.0.0:6768' } - registerMobileHandlers(rpcServer as never, { - firewallEnvironment: { - platform: 'win32', - isPackaged: true, - executablePath: 'C:\\Program Files\\Orca\\Orca.exe', - runPowerShell - } - }) - - expect( - handlers.get('mobile:repairWindowsFirewall')?.({ - sender: { isDestroyed: () => false, getType: () => 'webview' } - }) - ).toEqual({ ok: false, reason: 'unsupported' }) - expect(runPowerShell).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/jira/attachments/images.test.ts b/src/main/jira/attachments/images.test.ts deleted file mode 100644 index ff91076cfe3..00000000000 --- a/src/main/jira/attachments/images.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { jiraRequestBinaryMock } = vi.hoisted(() => ({ - jiraRequestBinaryMock: vi.fn() -})) - -const { JiraApiError: JiraApiErrorMock } = vi.hoisted(() => ({ - JiraApiError: class JiraApiError extends Error { - status: number | null - constructor(message: string, status: number | null = null) { - super(message) - this.status = status - } - } -})) - -vi.mock('../jira-api-error', () => ({ JiraApiError: JiraApiErrorMock })) - -vi.mock('../authenticated-request', () => ({ - jiraRequestBinary: (...args: unknown[]) => jiraRequestBinaryMock(...args), - apiBasePath: (site: { authType?: string }) => - site.authType === 'server' ? '/rest/api/2' : '/rest/api/3', - JiraApiError: JiraApiErrorMock -})) - -describe('attachment image helpers', () => { - beforeEach(async () => { - jiraRequestBinaryMock.mockReset() - const { _resetAttachmentImageCache } = await import('./image-cache') - _resetAttachmentImageCache() - }) - - it('does not re-emit an already consumed attachment for a third shared-alt node', async () => { - const { createMediaMarkdownResolver } = await import('./images') - const images = [ - { - id: '1', - filename: 'image.png', - mimeType: 'image/png', - byteSize: 1, - dataUrl: 'data:image/png;base64,AA==' - }, - { - id: '2', - filename: 'image.png', - mimeType: 'image/png', - byteSize: 1, - dataUrl: 'data:image/png;base64,BB==' - } - ] - const resolve = createMediaMarkdownResolver(images, ['1', '2']) - expect(resolve({ id: 'm1', alt: 'image.png' })).toContain('AA==') - expect(resolve({ id: 'm2', alt: 'image.png' })).toContain('BB==') - expect(resolve({ id: 'm3', alt: 'image.png' })).toBeNull() - }) -}) diff --git a/src/main/persistence/moving-wsl-projects/orchestration/wsl-move-orchestrator-user-choices.test.ts b/src/main/persistence/moving-wsl-projects/orchestration/wsl-move-orchestrator-user-choices.test.ts deleted file mode 100644 index 6a116ff8755..00000000000 --- a/src/main/persistence/moving-wsl-projects/orchestration/wsl-move-orchestrator-user-choices.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { WslMovePreview } from '../../../../shared/wsl-move/wsl-move-driver-types' -import { WslMoveOrchestrator } from '../wsl-move-orchestrator' -import { fakePorts, ready, stateOf } from './wsl-move-orchestrator.test-support' - -// The orchestrator under the user's own choices and the reviews' race and failure cases. -describe('WslMoveOrchestrator: user choices, races and failures', () => { - describe('re-review fixes (#33802)', () => { - // 1: an unreadable journal at startup must not escape the constructor. - - // 2: a release by the user during a step must win over the step's stale view. - it('does not move a distro the user released while its preview was running', async () => { - let release: () => void = () => {} - const ports = fakePorts({ - preview: vi.fn( - () => - new Promise((resolve) => { - release = () => resolve(ready('Ubuntu')) - }) - ) - }) - const orchestrator = new WslMoveOrchestrator(ports) - const step = orchestrator.trigger('Ubuntu', 'connect') - await vi.waitFor(() => expect(ports.preview).toHaveBeenCalled()) - await orchestrator.releasedByUser('Ubuntu', 'released-here') - release() - await step - expect(ports.start).not.toHaveBeenCalled() - expect(stateOf(orchestrator, 'Ubuntu')).toEqual({ - kind: 'parked', - reason: 'declined', - cause: 'released-here' - }) - }) - - // 3: a wake queued during Restore's own busy section runs after it. - }) - - // Pre-review #1: a pruned decline would let a later wake re-add a host the user removed. - - // #34632's stopped-distro gates: the user's Check again is their act on the distro, so the - // driver's reads for a just-connected distro are not refused as background work. -}) diff --git a/src/main/persistence/profile-state-cutover-fixture.test.ts b/src/main/persistence/profile-state-cutover-fixture.test.ts deleted file mode 100644 index 0bfdab3b143..00000000000 --- a/src/main/persistence/profile-state-cutover-fixture.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { removeTreeSync } from '../../shared/file-write/windows-transient-lock-removal' -import { buildProfileStateCutoverFixture } from './profile-state-cutover-fixture' -import { Store } from './loading-store/store' -import { closeTestStores, dataFile, testState, writeDataFile } from './persistence-test-harness' - -const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({ - trackMock: vi.fn(), - getCohortAtEmitMock: vi.fn(() => ({ nth_repo_added: 2 })) -})) - -vi.mock('electron', () => ({ - app: { getPath: () => testState.dir }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), - decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) - } -})) - -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) -vi.mock('../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: vi.fn(() => ({ hosts: [] })), - sshConfigHostsToTargets: vi.fn(() => []) -})) - -describe('profile-state cutover fixture', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-profile-cutover-fixture-')) - }) - - afterEach(async () => { - await closeTestStores() - removeTreeSync(testState.dir) - }) - - it('fails closed for an invalid serialized import instead of reading a fallback file', () => { - writeDataFile(buildProfileStateCutoverFixture(testState.dir)) - - expect(() => new Store({ dataFile: dataFile(), serializedState: '{not valid json' })).toThrow( - 'Failed to load imported profile state' - ) - }) -}) diff --git a/src/main/plugins/panels/panel-lifetime/plugin-panel-image.test.ts b/src/main/plugins/panels/panel-lifetime/plugin-panel-image.test.ts deleted file mode 100644 index 18775b5aaa1..00000000000 --- a/src/main/plugins/panels/panel-lifetime/plugin-panel-image.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { readFileSync } from 'node:fs' -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { readPluginPanelImage } from './plugin-panel-image' - -const LOGO = readFileSync( - join(import.meta.dirname, '../../../../../examples/plugins/components-gallery/assets/logo.png') -) -const roots: string[] = [] -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -async function plugin(): Promise<{ root: string; outside: string }> { - const base = await mkdtemp(join(tmpdir(), 'orca-panel-image-')) - roots.push(base) - const root = join(base, 'plugin') - await mkdir(join(root, 'assets'), { recursive: true }) - await writeFile(join(root, 'assets', 'logo.png'), LOGO) - // An image extension is not enough: the header must be a real, bounded image. - await writeFile(join(root, 'assets', 'fake.png'), '') - await writeFile(join(root, 'notes.txt'), 'not an image') - const outside = join(base, 'secret.png') - await writeFile(outside, 'outside') - return { root, outside } -} - -describe('readPluginPanelImage', () => { - it('reads an image inside the plugin of a live components-panel session', async () => { - const { root } = await plugin() - const read = (sessionToken: string, path: string) => - readPluginPanelImage( - { resolveComponentsPanelRoot: (token) => (token === 'live' ? root : null) }, - { sessionToken, path } - ) - expect(await read('live', 'assets/logo.png')).toEqual({ - contentType: 'image/png', - bytes: new Uint8Array(LOGO) - }) - expect(await read('stale', 'assets/logo.png')).toBeNull() - expect(await read('live', 'assets/missing.png')).toBeNull() - }) -}) diff --git a/src/main/power/system-power-lifecycle.test.ts b/src/main/power/system-power-lifecycle.test.ts deleted file mode 100644 index a3536ece7e4..00000000000 --- a/src/main/power/system-power-lifecycle.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - publishSystemResume, - publishSystemSuspend, - subscribeSystemPowerLifecycle -} from './system-power-lifecycle' - -afterEach(() => { - publishSystemResume() - vi.restoreAllMocks() -}) - -describe('system power lifecycle', () => { - it('replays suspended state to a late subscriber', () => { - publishSystemSuspend() - const listener = { onSuspend: vi.fn(), onResume: vi.fn() } - const unsubscribe = subscribeSystemPowerLifecycle(listener) - - expect(listener.onSuspend).toHaveBeenCalledOnce() - expect(listener.onResume).not.toHaveBeenCalled() - unsubscribe() - }) - - it('atomically replays a transition to a subscriber added during publication', () => { - const lateListener = { onSuspend: vi.fn(), onResume: vi.fn() } - let unsubscribeLate: (() => void) | undefined - const unsubscribeFirst = subscribeSystemPowerLifecycle({ - onSuspend: () => { - unsubscribeLate = subscribeSystemPowerLifecycle(lateListener) - }, - onResume: vi.fn() - }) - - publishSystemSuspend() - - expect(lateListener.onSuspend).toHaveBeenCalledOnce() - unsubscribeLate?.() - unsubscribeFirst() - }) - - it('isolates a failing listener from the remaining subscribers', () => { - vi.spyOn(console, 'error').mockImplementation(() => {}) - const unsubscribeFailing = subscribeSystemPowerLifecycle({ - onSuspend: () => { - throw new Error('listener failed') - }, - onResume: vi.fn() - }) - const healthyListener = { onSuspend: vi.fn(), onResume: vi.fn() } - const unsubscribeHealthy = subscribeSystemPowerLifecycle(healthyListener) - - publishSystemSuspend() - - expect(healthyListener.onSuspend).toHaveBeenCalledOnce() - expect(console.error).toHaveBeenCalledOnce() - unsubscribeHealthy() - unsubscribeFailing() - }) -}) diff --git a/src/main/providers/working-directory/validation.test.ts b/src/main/providers/working-directory/validation.test.ts deleted file mode 100644 index 898c4f067fe..00000000000 --- a/src/main/providers/working-directory/validation.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const wslUncDirectoryExistsAsyncMock = vi.hoisted(() => vi.fn()) - -vi.mock('../../wsl/filesystem/unc-path-access', async (importOriginal) => { - const actual = (await importOriginal()) as Record - return { ...actual, wslUncDirectoryExistsAsync: wslUncDirectoryExistsAsyncMock } -}) - -import { - validateWorkingDirectoryAsync, - _resetWorkingDirectoryValidationStateForTest -} from './validation' - -beforeEach(() => { - wslUncDirectoryExistsAsyncMock.mockReset() - wslUncDirectoryExistsAsyncMock.mockResolvedValue(null) - _resetWorkingDirectoryValidationStateForTest() -}) - -describe('validateWorkingDirectoryAsync', () => { - describe('cancellation', () => { - // Unsettled probes persist in the module-level dedupe map; use a distinct path per test. - const deadShare = (name: string): string => `\\\\wsl.localhost\\Ubuntu\\dead-${name}` - - beforeEach(() => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('leaves the shared probe intact for callers that are still waiting', async () => { - let releaseProbe: () => void = () => {} - wslUncDirectoryExistsAsyncMock.mockReturnValue( - new Promise((resolve) => { - releaseProbe = () => resolve(true) - }) - ) - const abort = new AbortController() - - const shared = deadShare('shared') - const staying = validateWorkingDirectoryAsync(shared) - const leaving = validateWorkingDirectoryAsync(shared, { signal: abort.signal }) - abort.abort() - await expect(leaving).rejects.toThrow('was canceled') - - releaseProbe() - await expect(staying).resolves.toBeUndefined() - expect(wslUncDirectoryExistsAsyncMock).toHaveBeenCalledOnce() - }) - }) -}) diff --git a/src/main/runtime/agent-senders/runtime-agent-sender-graph-unavailable.test.ts b/src/main/runtime/agent-senders/runtime-agent-sender-graph-unavailable.test.ts deleted file mode 100644 index 3cb8e5cc568..00000000000 --- a/src/main/runtime/agent-senders/runtime-agent-sender-graph-unavailable.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../orca-runtime' -import '../terminal/records/runtime-leaf-record-projection.test-fixture' -import '../terminal/wait/tui-idle-wait-test-harness' - -const PTY_ID = 'pty-local-1' -const WORKTREE_ID = 'repo::/worktree' -const TAB_ID = 'tab-terminal' -const LEAF_ID = '11111111-1111-4111-8111-111111111111' - -it('keeps a running terminal’s sender row, by its start-time handle, while no window graph exists', async () => { - const runtime = new OrcaRuntimeService(null) - runtime.setPtyController({ - write: () => true, - kill: vi.fn(() => true), - getForegroundProcess: async () => null - }) - // The handle the terminal's agent is started with, which its mail cards save as the sender. - const handle = runtime.preAllocateHandleForPty(PTY_ID) - runtime.registerPty(PTY_ID, WORKTREE_ID, 'target', { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: 'inc-1' - }) - runtime.attachWindow(1) - await runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: LEAF_ID, - layout: null - } - ], - leaves: [ - { tabId: TAB_ID, worktreeId: WORKTREE_ID, leafId: LEAF_ID, paneRuntimeId: 1, ptyId: PTY_ID } - ] - }) - const { senders } = runtime['agentProjections'] - const row = { identity: handle, paneKey: `${TAB_ID}:${LEAF_ID}`, worktreeId: WORKTREE_ID } - expect( - (await senders.withPreparedPublication(() => senders.build())).associations - ).toContainEqual(row) - - // The window closes: the host drops its leaves and handle records, and keeps start-time handles. - runtime.markGraphUnavailable(1) - expect( - (await senders.withPreparedPublication(() => senders.build())).associations - ).toContainEqual(row) -}) diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-eligibility.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-eligibility.test.ts deleted file mode 100644 index c5aae454b5f..00000000000 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/mailbox-pointer-eligibility.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { OrchestrationDb } from '../../db/orchestration-db' -import { selectOrchestrationPointerBatch } from './mailbox-pointer-eligibility' - -describe('selectOrchestrationPointerBatch', () => { - it('selects only mail outside the unacked batch, and reselects behind the next one after an ack', () => { - const db = new OrchestrationDb(':memory:') - try { - const run = db.createRun({ - objective: 'Held batch', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'tab:11111111-1111-4111-8111-111111111111' - }) - const mailbox = `run:${run.id}` - const params = { - runId: run.id, - mailboxHandle: mailbox, - consumerGeneration: run.consumer_generation - } - const insert = (subject: string) => - db.insertMessage({ runId: run.id, from: 'worker', to: mailbox, subject }) - const heldMessage = insert('held') - const first = db.getOrCreateMailboxDelivery(params)!.delivery - const newer = insert('newer') - const select = () => - selectOrchestrationPointerBatch({ - db, - mailboxHandle: mailbox, - waiters: undefined, - reservedTypes: undefined - }) - - const batch = select() - expect(batch.heldDeliveryId).toBe(first.id) - expect(batch.messages.map((message) => message.id)).toEqual([newer.id]) - expect(db.getMessageById(heldMessage.id)).toMatchObject({ read: 0, delivered_at: null }) - - db.acknowledgeMailboxDelivery({ ...params, deliveryId: first.id }) - const second = db.getOrCreateMailboxDelivery(params)!.delivery - const later = insert('later') - expect(select()).toEqual({ - heldDeliveryId: second.id, - messages: [expect.objectContaining({ id: later.id })] - }) - } finally { - db.close() - } - }) -}) diff --git a/src/main/runtime/push/push-preferences.test.ts b/src/main/runtime/push/push-preferences.test.ts deleted file mode 100644 index 012ecc33f69..00000000000 --- a/src/main/runtime/push/push-preferences.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { expect, it } from 'vitest' -import { createHarness, notification, registration, flush } from './push-dispatcher.test-fixture' - -it('applies desktop category eligibility regardless of phone sound preferences', async () => { - const harness = createHarness({ - devices: [ - { - deviceId: 'mirror', - pushRegistration: registration({ - registrationId: 'mirror' - }) - }, - { - deviceId: 'quiet', - pushRegistration: registration({ - registrationId: 'quiet', - filter: { sound: false } - }) - }, - { - deviceId: 'second-phone', - pushRegistration: registration({ registrationId: 'second-phone' }) - } - ] - }) - harness.dispatcher.enqueue(notification({ source: 'terminal-bell', desktopAllowed: false })) - await flush() - expect(harness.sends).toHaveLength(0) - - harness.dispatcher.enqueue(notification({ source: 'terminal-bell', desktopAllowed: true })) - await flush() - expect(harness.sends).toHaveLength(2) - expect(harness.sends[0]).toMatchObject({ registrationIds: ['mirror', 'second-phone'] }) - expect(harness.sends[1]).toMatchObject({ - registrationIds: ['quiet'], - notification: { sound: false } - }) -}) diff --git a/src/main/runtime/repositories/runtime-repository-issue-command.test.ts b/src/main/runtime/repositories/runtime-repository-issue-command.test.ts deleted file mode 100644 index 44562d512d4..00000000000 --- a/src/main/runtime/repositories/runtime-repository-issue-command.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { RuntimeRepositoryIssueCommand } from './runtime-repository-issue-command' - -const mocks = vi.hoisted(() => ({ localCheck: vi.fn() })) - -vi.mock('../../git/source-control/ignores/check-ignored-paths', () => ({ - checkIgnoredPaths: mocks.localCheck -})) - -describe('local issue command runtime routing', () => { - it.each(['command', ' '])( - 'preserves local file writes with an unavailable runtime: %j', - async (content) => { - const root = mkdtempSync(join(tmpdir(), 'orca-runtime-ignore-')) - const repo = { - id: 'repo-1', - path: root, - displayName: 'local', - badgeColor: '#000', - addedAt: 0 - } - mkdirSync(join(root, '.orca')) - writeFileSync(join(root, '.orca', 'issue-command'), 'old command\n') - const getLocalGitArgs = vi.fn((): [] => { - throw new Error('Project runtime requires repair') - }) - const commands = new RuntimeRepositoryIssueCommand({ - resolveRepo: async () => repo, - getLocalGitArgs - }) - try { - await commands.write(repo.id, content) - if (content.trim()) { - expect(readFileSync(join(root, '.orca', 'issue-command'), 'utf8')).toBe('command\n') - expect(readFileSync(join(root, '.gitignore'), 'utf8')).toBe('.orca\n') - } else { - expect(existsSync(join(root, '.orca', 'issue-command'))).toBe(false) - expect(existsSync(join(root, '.gitignore'))).toBe(false) - expect(getLocalGitArgs).not.toHaveBeenCalled() - } - } finally { - rmSync(root, { recursive: true, force: true }) - } - } - ) -}) diff --git a/src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts b/src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts deleted file mode 100644 index a81adad8518..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-pinned-port.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import '../dispatch/testing/unused-default-rpc-methods.test-fixture' -import { mkdtempSync } from 'node:fs' -import { createServer, type Server } from 'node:net' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { OrcaRuntimeService } from '../../orca-runtime' -import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { PinnedPortUnavailableError } from '../transports/websocket/ws-transport' - -const holders: Server[] = [] - -async function holdPort(): Promise { - const holder = createServer() - holders.push(holder) - await new Promise((resolve) => holder.listen(0, '0.0.0.0', resolve)) - const address = holder.address() - if (!address || typeof address === 'string') { - throw new Error('holder has no TCP port') - } - return address.port -} - -afterEach(async () => { - await Promise.all( - holders.splice(0).map((holder) => new Promise((resolve) => holder.close(resolve))) - ) -}) - -function serveServer(wsPort: number, requirePinnedWsPort: boolean): OrcaRuntimeRpcServer { - return new OrcaRuntimeRpcServer({ - methods: [], - runtime: new OrcaRuntimeService(), - userDataPath: mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-pinned-')), - enableWebSocket: true, - exposeNetworkByDefault: true, - wsPort, - preferPinnedWsPort: true, - requirePinnedWsPort - }) -} - -describe('orca serve --port', () => { - it('fails startup when the requested port is taken instead of serving on another port', async () => { - const port = await holdPort() - const server = serveServer(port, true) - const started = server.start() - await expect(started).rejects.toBeInstanceOf(PinnedPortUnavailableError) - await expect(started).rejects.toThrow(`Port ${port}`) - expect(server.getWebSocketEndpoint()).toBeNull() - await server.stop() - }) -}) diff --git a/src/main/runtime/terminal/output/codex-notice-terminal-status.test.ts b/src/main/runtime/terminal/output/codex-notice-terminal-status.test.ts deleted file mode 100644 index dcb05b69530..00000000000 --- a/src/main/runtime/terminal/output/codex-notice-terminal-status.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { readFileSync } from 'node:fs' -import { describe, expect, it } from 'vitest' -import { HeadlessEmulator } from '../../../daemon/emulation/headless-emulator' -import { observeCodexCapacityTerminalStatus } from './codex-notice-terminal-status' - -const transcript = readFileSync( - new URL('../../__fixtures__/codex-model-capacity.txt', import.meta.url), - 'utf8' -) -void readFileSync( - new URL('../../__fixtures__/codex-model-capacity-fullscreen.txt', import.meta.url), - 'utf8' -) - -describe('Codex model capacity terminal status', () => { - it.each([100, 101])( - 'does not close a hook turn starting at or after output time (%i)', - async (turnStartedAt) => { - const emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) - try { - await emulator.write(transcript) - expect( - observeCodexCapacityTerminalStatus( - emulator, - transcript, - undefined, - 'codex', - () => ({ - agentType: 'codex', - prompt: 'Retry', - turnStartedAt - }), - 100 - ) - ).toBeNull() - } finally { - emulator.dispose() - } - } - ) -}) diff --git a/src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts b/src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts deleted file mode 100644 index 1879a09f7ce..00000000000 --- a/src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - containsTerminalVerticalLineControl, - normalizeTerminalChunk -} from './terminal-ansi-normalization' -import { appendNormalizedToTailBuffer } from './tail/terminal-tail-buffer' - -describe('terminal vertical-control scanning', () => { - it('preserves printable spans and carried controls across chunk boundaries', () => { - const first = normalizeTerminalChunk('漢\ud800\x1b[31m字\t\r\n\x00a\x1b[2') - expect(first).toEqual({ text: '漢\ud800字\t\na', pendingAnsi: '\x1b[2' }) - expect(normalizeTerminalChunk('K\udfff😀\b\r\x7f\x9fend', first.pendingAnsi)).toEqual({ - text: '\x1b[2K\udfff😀\b\rend', - pendingAnsi: '' - }) - }) - - it.each([ - ['OSC BEL', '\x1b]2;title', '\x07'], - ['OSC ST', '\x1b]2;title', '\x1b\\'], - ['DCS', '\x1bPpayload', '\x1b\\'], - ['SOS', '\x1bXpayload', '\x1b\\'], - ['PM', '\x1b^payload', '\x1b\\'], - ['APC', '\x1b_payload', '\x1b\\'] - ])('skips embedded CSI and stops at an incomplete %s', (_name, prefix, terminator) => { - const incomplete = `${prefix}\x1b[2A` - expect(containsTerminalVerticalLineControl(incomplete)).toBe(false) - expect(containsTerminalVerticalLineControl(`${incomplete}${terminator}ordinary`)).toBe(false) - expect(containsTerminalVerticalLineControl(`${incomplete}${terminator}\x1b[3A`)).toBe(true) - }) - - it('preserves tail rows when ordinary output is followed by a cursor-up redraw', () => { - const first = appendNormalizedToTailBuffer([], '', 'first\nold\n') - const normalized = normalizeTerminalChunk('\x1b[1A\x1b[2K\x1b[32mnew\x1b[0m\n') - const next = appendNormalizedToTailBuffer( - first.lines, - first.partialLine, - normalized.text, - first.redrawCursor - ) - - expect(next.lines).toEqual(['first', 'new']) - expect(next.partialLine).toBe('') - }) -}) diff --git a/src/main/runtime/terminal/wait/reused-agent-mid-turn-readiness.test.ts b/src/main/runtime/terminal/wait/reused-agent-mid-turn-readiness.test.ts deleted file mode 100644 index c4ba4f86762..00000000000 --- a/src/main/runtime/terminal/wait/reused-agent-mid-turn-readiness.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createTranscriptPane } from '../../orca-runtime-tests/agent-transcript-pane-test-harness' -import { waitForWorkerAgentReady } from './launched-agent-composer-readiness' - -vi.mock('electron', () => ({ - BrowserWindow: { fromId: vi.fn(() => null) }, - webContents: { fromId: vi.fn(() => null) }, - ipcMain: { on: vi.fn(), removeListener: vi.fn() }, - app: { getPath: vi.fn(() => '/tmp') } -})) - -describe('a worker start reusing a pane whose agent is mid-turn', () => { - afterEach(() => { - vi.restoreAllMocks() - }) - - // Claude's spinner title while a turn runs. - function midTurnClaudePane() { - return createTranscriptPane({ - paneTitle: 'Terminal', - foregroundProcess: 'claude', - data: '\x1b]0;⠂ Watch PR checks\x07✻ Running gh pr checks --watch…\r\n', - launchAgent: 'claude' - }) - } - - it('is ready at once, since the agent queues a task sent mid-turn', async () => { - const pane = await midTurnClaudePane() - await expect( - waitForWorkerAgentReady(pane.runtime, pane.handle, { - agent: undefined, - reusesTerminal: true, - timeoutMs: 150 - }) - ).resolves.toMatchObject({ satisfied: true }) - }) -}) diff --git a/src/main/ssh/authentication/ssh-security-key-identity.test.ts b/src/main/ssh/authentication/ssh-security-key-identity.test.ts deleted file mode 100644 index 705e8bda8da..00000000000 --- a/src/main/ssh/authentication/ssh-security-key-identity.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { rm } from 'node:fs/promises' -import 'node:os' -import 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { isOpenSshSecurityKeyPrivateKey } from './ssh-security-key-identity' -import { createOpenSshPrivateKeyFixture } from './testing/ssh-security-key-identity.test-fixture' -import '../system-transport/ssh-transport-selection' - -const { findSystemSshMock } = vi.hoisted(() => ({ findSystemSshMock: vi.fn() })) - -vi.mock('../system-transport/system-ssh-binary', () => ({ findSystemSsh: findSystemSshMock })) - -vi.mock('node:os', async (importOriginal) => { - const actual = await importOriginal<{ homedir: () => string }>() - return { - ...actual, - homedir: () => process.env.ORCA_TEST_SSH_HOME || actual.homedir() - } -}) - -const ED25519_SECURITY_KEY = 'sk-ssh-ed25519@openssh.com' -const ECDSA_SECURITY_KEY = 'sk-ecdsa-sha2-nistp256@openssh.com' -const tempDirs: string[] = [] - -beforeEach(() => { - findSystemSshMock.mockReset() - findSystemSshMock.mockReturnValue('/usr/bin/ssh') -}) - -afterEach(async () => { - vi.unstubAllEnvs() - await Promise.all(tempDirs.splice(0).map((directory) => rm(directory, { recursive: true }))) -}) - -describe('isOpenSshSecurityKeyPrivateKey', () => { - it.each([ED25519_SECURITY_KEY, ECDSA_SECURITY_KEY])( - 'recognizes unencrypted %s keys', - (keyType) => { - expect(isOpenSshSecurityKeyPrivateKey(createOpenSshPrivateKeyFixture([keyType]))).toBe(true) - } - ) - - it('does not match security-key text outside a valid public-key type', () => { - const key = createOpenSshPrivateKeyFixture(['ssh-ed25519'], { - privateBlock: Buffer.from(ED25519_SECURITY_KEY) - }) - expect(isOpenSshSecurityKeyPrivateKey(key)).toBe(false) - expect( - isOpenSshSecurityKeyPrivateKey(Buffer.from(`${ED25519_SECURITY_KEY} AAAA comment`)) - ).toBe(false) - }) -}) diff --git a/src/main/ssh/config/ssh-config-parser-host-patterns.test.ts b/src/main/ssh/config/ssh-config-parser-host-patterns.test.ts deleted file mode 100644 index ffbe0e0d470..00000000000 --- a/src/main/ssh/config/ssh-config-parser-host-patterns.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseSshConfig } from './ssh-config-parser' - -describe('parseSshConfig host pattern filtering', () => { - it('ignores negated aliases on mixed Host lines', () => { - const config = ` -Host prod !prod-admin - HostName prod.example.com -` - expect(parseSshConfig(config)).toEqual([{ host: 'prod', hostname: 'prod.example.com' }]) - }) - - it('imports only literal positive aliases from mixed wildcard and negated patterns', () => { - const config = ` -Host !legacy *.corp prod - HostName prod.example.com -` - expect(parseSshConfig(config)).toEqual([{ host: 'prod', hostname: 'prod.example.com' }]) - }) - - it('ignores inline comments on mixed Host lines', () => { - const config = ` -Host prod stage # shared production aliases - HostName prod.example.com -` - expect(parseSshConfig(config)).toEqual([ - { host: 'prod', hostname: 'prod.example.com' }, - { host: 'stage', hostname: 'prod.example.com' } - ]) - }) - - it('skips Host entries containing only wildcard and negated patterns', () => { - const config = ` -Host !legacy *.corp ?? - HostName ignored.example.com -` - expect(parseSshConfig(config)).toEqual([]) - }) -}) diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.test.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.test.ts deleted file mode 100644 index 2a39b5375a0..00000000000 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - preparationOwnerExitedHere, - type PreparationOwnerProbe -} from './worktree-create-preparation-stale-cleanup' - -const MACHINE_A = '0123456789abcdef0123456789abcdef' -const MACHINE_B = 'fedcba9876543210fedcba9876543210' -const REPO = '/home/dev/repo' - -function probe(overrides: Partial = {}): PreparationOwnerProbe { - return { - machineIdentity: () => MACHINE_A, - repoIsOnLocalDisk: () => true, - isProcessAlive: () => false, - ...overrides - } -} - -const reasonFrom = (machine: string | null): string => - `orca-create-preparation:v1:4242:4242-11111111-1111-4111-8111-111111111111${ - machine ? `:machine=${machine}` : '' - }` - -describe('preparationOwnerExitedHere', () => { - it('never reads an owner on another machine as exited', () => { - expect(preparationOwnerExitedHere(reasonFrom(MACHINE_B), REPO, {}, probe())).toBe(false) - }) - - it('never reads a machine-scoped owner as exited when this host has no identity', () => { - expect( - preparationOwnerExitedHere( - reasonFrom(MACHINE_B), - REPO, - {}, - probe({ machineIdentity: () => null }) - ) - ).toBe(false) - }) - - it('judges a reason with no machine by pid only on a disk no other host sees', () => { - expect(preparationOwnerExitedHere(reasonFrom(null), REPO, {}, probe())).toBe(true) - expect( - preparationOwnerExitedHere( - reasonFrom(null), - REPO, - {}, - probe({ repoIsOnLocalDisk: () => false }) - ) - ).toBe(false) - expect( - preparationOwnerExitedHere( - reasonFrom(null), - '\\\\wsl.localhost\\Ubuntu\\home\\dev\\repo', - { wslDistro: 'Ubuntu' }, - probe({ repoIsOnLocalDisk: () => false }) - ) - ).toBe(true) - }) -}) diff --git a/src/renderer/src/store/repos/repos-manual-order-hydration.test.ts b/src/renderer/src/store/repos/repos-manual-order-hydration.test.ts deleted file mode 100644 index 8ffb5383068..00000000000 --- a/src/renderer/src/store/repos/repos-manual-order-hydration.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repository/repo-types' -import { createTestStore } from '../testing/app-store-test-fixture' -import { - createCompatibleRuntimeStatusResponseIfNeeded, - type RuntimeEnvironmentCallRequest -} from '../../runtime/rpc/testing/runtime-compatibility-test-fixture' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../runtime/rpc/compatibility/runtime-compatibility-cache' - -const reposList = vi.fn() -const projectsList = vi.fn() -const listHostSetups = vi.fn() -const runtimeEnvironmentsList = vi.fn() -const runtimeEnvironmentCall = vi.fn() -const runtimeEnvironmentTransportCall = vi.fn() - -const reposByEnvironment: Record = { - 'node-a': [ - { id: 'alpha', path: '/alpha', displayName: 'alpha', badgeColor: '#000', addedAt: 1 }, - { id: 'bravo', path: '/bravo', displayName: 'bravo', badgeColor: '#000', addedAt: 2 } - ], - 'node-b': [ - { id: 'charlie', path: '/charlie', displayName: 'charlie', badgeColor: '#000', addedAt: 1 }, - { id: 'delta', path: '/delta', displayName: 'delta', badgeColor: '#000', addedAt: 2 } - ] -} - -type RepoListResolver = (value: unknown) => void - -async function loadWithCompletionOrder(completionOrder: string[]): Promise { - clearRuntimeCompatibilityCacheForTests() - const repoListResolvers = new Map() - runtimeEnvironmentCall.mockImplementation( - (args: RuntimeEnvironmentCallRequest & { selector?: string }) => { - if (args.method === 'repo.list' && args.selector) { - return new Promise((resolve) => repoListResolvers.set(args.selector!, resolve)) - } - const result = args.method === 'project.list' ? { projects: [] } : { setups: [] } - return { id: `rpc-${args.method}`, ok: true, result, _meta: { runtimeId: 'runtime' } } - } - ) - const store = createTestStore() - store.setState({ - manualRepoOrder: [ - { hostId: 'runtime:node-a', repoId: 'alpha' }, - { hostId: 'runtime:node-b', repoId: 'charlie' }, - { hostId: 'runtime:node-a', repoId: 'bravo' }, - { hostId: 'runtime:node-b', repoId: 'delta' } - ] - }) - - const load = store.getState().fetchReposForAllHosts() - await vi.waitFor(() => expect(repoListResolvers.size).toBe(2)) - for (const environmentId of completionOrder) { - repoListResolvers.get(environmentId)?.({ - id: `rpc-repo-${environmentId}`, - ok: true, - result: { repos: reposByEnvironment[environmentId] }, - _meta: { runtimeId: environmentId } - }) - await Promise.resolve() - } - await load - expect(store.getState().manualRepoOrder).toHaveLength(4) - return store.getState().repos.map((repo) => `${repo.executionHostId}:${repo.id}`) -} - -describe('manual repo order hydration', () => { - beforeEach(() => { - clearRuntimeCompatibilityCacheForTests() - reposList.mockReset().mockResolvedValue([]) - projectsList.mockReset().mockResolvedValue([]) - listHostSetups.mockReset().mockResolvedValue([]) - runtimeEnvironmentsList.mockReset().mockResolvedValue([ - { id: 'node-a', name: 'A' }, - { id: 'node-b', name: 'B' } - ]) - runtimeEnvironmentCall.mockReset() - runtimeEnvironmentTransportCall.mockReset() - runtimeEnvironmentTransportCall.mockImplementation( - (args: RuntimeEnvironmentCallRequest) => - createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) - ) - vi.stubGlobal('window', { - api: { - repos: { list: reposList }, - projects: { list: projectsList, listHostSetups }, - runtimeEnvironments: { - list: runtimeEnvironmentsList, - call: runtimeEnvironmentTransportCall - } - } - }) - }) - - it('restores the same cross-host order for either catalog completion order', async () => { - const expected = [ - 'runtime:node-a:alpha', - 'runtime:node-b:charlie', - 'runtime:node-a:bravo', - 'runtime:node-b:delta' - ] - - await expect(loadWithCompletionOrder(['node-b', 'node-a'])).resolves.toEqual(expected) - await expect(loadWithCompletionOrder(['node-a', 'node-b'])).resolves.toEqual(expected) - }) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-pane-owner-reclaim.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-pane-owner-reclaim.test.ts deleted file mode 100644 index 3d1174b507d..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-status-pane-owner-reclaim.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createTestStore } from '../../testing/app-store-test-fixture' - -const PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111' -const NOW = Date.UTC(2026, 9, 25, 12) - -afterEach(() => vi.useRealTimers()) - -// #30589: a nested agent's row arrived while the owner idled; the owner's next hook must land. -function reclaim(session?: string) { - const store = createTestStore() - vi.useFakeTimers() - vi.setSystemTime(NOW) - store - .getState() - .setAgentStatus(PANE_KEY, { state: 'working', prompt: 'Background job', agentType: 'claude' }) - store.getState().setAgentStatus( - PANE_KEY, - { state: 'working', prompt: 'Next task', agentType: 'codex' }, - undefined, - { updatedAt: NOW + 1 }, - undefined, - session - ? { - paneOwner: { agent: 'codex', session: 'owner' }, - providerSession: { key: 'session_id', id: session } - } - : undefined - ) - return store.getState().agentStatusByPaneKey.get(PANE_KEY) -} - -describe('pane owner reclaim', () => { - it("accepts the owner's hook over a fresh nested-agent row", () => { - expect(reclaim('owner')).toMatchObject({ - agentType: 'codex', - prompt: 'Next task' - }) - }) - - it.each([undefined, 'nested-exec'])('suppresses a different agent from session %s', (session) => { - expect(reclaim(session)).toMatchObject({ agentType: 'claude', prompt: 'Background job' }) - }) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.test.ts deleted file mode 100644 index 0fea9fdbf68..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-status-projection-topology.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createTestStore } from '../../testing/app-store-test-fixture' -import { makeUnifiedTab } from '../tabs/tab-group.test-fixture' -import { withWorktreeTabEntry } from '@/runtime/web-session-tabs-sync/presentation-record-drafts' -import { structuredAgentSessionPaneKey } from '../../../../../shared/agent-session/view/structured-agent-session-projection' -import { acceptedAgentStatuses, AcceptedAgentStatuses } from './accepted-agent-statuses' - -afterEach(() => vi.restoreAllMocks()) - -it.each([100, 1000])('addresses tab changes beside %i unrelated recognized chats', (count) => { - const now = 1000 - vi.spyOn(Date, 'now').mockReturnValue(now) - const store = createTestStore() - const visits: string[] = [] - const chats = Array.from({ length: count }, (_, index) => { - const id = `native-${index}` - const tab = makeUnifiedTab({ - id, - worktreeId: `workspace-${index}`, - groupId: 'group', - contentType: 'agent-session', - entityId: `session-${index}`, - agentSessionAgent: 'claude' - }) - Object.defineProperty(tab, 'id', { - enumerable: true, - get: () => { - visits.push(id) - return id - } - }) - return tab - }) - const key = structuredAgentSessionPaneKey('native-0', 'session-0') - const terminal = makeUnifiedTab({ - id: 'target', - worktreeId: 'target-workspace', - groupId: 'group' - }) - store.setState({ - unifiedTabsByWorktree: { - ...Object.fromEntries(chats.map((tab) => [tab.worktreeId, [tab]])), - 'target-workspace': [terminal] - }, - agentStatusByPaneKey: acceptedAgentStatuses([ - [ - key, - { - paneKey: key, - worktreeId: 'workspace-0', - state: 'working', - agentType: 'claude', - prompt: 'Native task', - updatedAt: now, - stateStartedAt: now, - stateHistory: [] - } - ] - ]) - }) - const reads = vi.spyOn(AcceptedAgentStatuses.prototype, 'get') - visits.length = 0 - store.setState((state) => ({ - unifiedTabsByWorktree: withWorktreeTabEntry( - state, - 'unifiedTabsByWorktree', - 'target-workspace', - [{ ...terminal, label: 'Updated shell' }], - (previous, next) => previous === next - ) - })) - expect(visits).toEqual([]) - expect(reads).not.toHaveBeenCalled() - expect(store.getState().unifiedTabsByWorktree['target-workspace'][0].label).toBe('Updated shell') - - const changed = { ...chats[0], label: 'Updated chat' } - visits.length = 0 - reads.mockClear() - store.setState((state) => ({ - unifiedTabsByWorktree: withWorktreeTabEntry( - state, - 'unifiedTabsByWorktree', - 'workspace-0', - [changed], - (previous, next) => previous === next - ) - })) - expect(visits.filter((id) => id !== 'native-0')).toEqual([]) - expect(new Set(reads.mock.calls.map(([paneKey]) => paneKey))).toEqual(new Set([key])) - expect( - store - .getState() - .agentStatusByPaneKey.projection.list('workspace-0') - .map((row) => row.entry.prompt) - ).toEqual(['Native task']) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-sleep-capacity.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-sleep-capacity.test.ts deleted file mode 100644 index be6fd005c55..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-status-sleep-capacity.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { acceptedAgentStatuses } from './accepted-agent-statuses' -import { createTestStore } from '../../testing/app-store-test-fixture' - -const NOW = 1_800_000_000_000 -const KEY = 'tab:11111111-1111-4111-8111-111111111111' -afterEach(() => vi.restoreAllMocks()) - -it('keeps sleeping capacity consistent across wake, aborted writes, capture and reset', () => { - vi.spyOn(Date, 'now').mockReturnValue(NOW) - const store = createTestStore() - const done = { - paneKey: KEY, - state: 'done' as const, - prompt: 'Finished', - updatedAt: NOW, - stateStartedAt: NOW, - stateHistory: [], - paneSleep: { ptyId: 'ended' } - } - store.setState({ agentStatusByPaneKey: acceptedAgentStatuses([[KEY, done]]) }) - const captured = store.getState().agentStatusByPaneKey.capture() - expect(() => - store.getState().transactAgentStatuses((transaction) => { - transaction.apply({ paneKey: KEY, payload: { state: 'working', prompt: 'Wake' } }) - expect(transaction.getState().agentStatusByPaneKey.awakeSize).toBe(1) - throw new Error('abort wake') - }) - ).toThrow('abort wake') - expect(store.getState().agentStatusByPaneKey.get(KEY)).toBe(done) - expect(store.getState().agentStatusByPaneKey.awakeSize).toBe(0) - store.getState().setAgentStatus(KEY, { state: 'working', prompt: 'Wake' }) - expect(store.getState().agentStatusByPaneKey.awakeSize).toBe(1) - store.setState({ - agentStatusByPaneKey: store.getState().agentStatusByPaneKey.replace([ - [KEY, null], - [KEY, done] - ]) - }) - expect(store.getState().agentStatusByPaneKey.size).toBe(1) - expect(store.getState().agentStatusByPaneKey.awakeSize).toBe(0) - store.setState({ agentStatusByPaneKey: acceptedAgentStatuses() }) - expect(store.getState().agentStatusByPaneKey.size).toBe(0) - expect(store.getState().agentStatusByPaneKey.awakeSize).toBe(0) - expect(captured.get(KEY)).toBe(done) - expect(captured.size).toBe(1) - expect(captured.awakeSize).toBe(0) -}) diff --git a/src/renderer/src/store/slices/browser/cleanup/browser-close-focused-group.test.ts b/src/renderer/src/store/slices/browser/cleanup/browser-close-focused-group.test.ts deleted file mode 100644 index 3560819617e..00000000000 --- a/src/renderer/src/store/slices/browser/cleanup/browser-close-focused-group.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import { createTestStore, seedStore } from '../../../testing/app-store-test-fixture' -import { makeTab } from '../../../terminals/testing/terminal-tab.test-fixture' -import { makeTabGroup, makeUnifiedTab } from '../../tabs/tab-group.test-fixture' -import { makeWorktree } from '../../worktrees/worktree.test-fixture' -import '../../../terminals/retirement/terminal-orphan-cleanup' -import { createStoreCascadesMockApi } from '../../../testing/app-store-cascade-api.test-fixture' -import { - drawTabsFromMain, - type TabsDrawnFromMain -} from '../../tabs/tabs-drawn-from-main.test-fixture' - -const mockUnregisterPtyDataHandlers = vi.hoisted(() => vi.fn<() => unknown[]>(() => [])) -const mockRestorePtyDataHandlersAfterFailedShutdown = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) - -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: mockRestorePtyDataHandlersAfterFailedShutdown, - unregisterPtyDataHandlers: mockUnregisterPtyDataHandlers -})) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) - -const mockApi = createStoreCascadesMockApi() - -let main: TabsDrawnFromMain | undefined -afterEach(() => { - main?.close() - main = undefined -}) - -describe('setActiveWorktree', () => { - beforeEach(() => { - vi.clearAllMocks() - mockApi.worktrees.updateMeta.mockResolvedValue({}) - }) - - it('promotes the next tab in the focused split into the global active surface on close', async () => { - const store = createTestStore() - const wt = 'repo1::/path/wt1' - const terminalTabId = 'terminal-1' - const browserTabId = 'browser-1' - const groupId = 'group-1' - - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] - }, - activeWorktreeId: wt, - activeTabType: 'browser', - activeBrowserTabId: browserTabId, - activeBrowserTabIdByWorktree: { [wt]: browserTabId }, - activeTabId: terminalTabId, - activeTabIdByWorktree: { [wt]: terminalTabId }, - activeTabTypeByWorktree: { [wt]: 'browser' }, - tabsByWorktree: { - [wt]: [makeTab({ id: terminalTabId, worktreeId: wt })] - }, - browserTabsByWorktree: { - [wt]: [ - { - id: browserTabId, - worktreeId: wt, - url: 'https://example.com', - title: 'Example', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 0 - } - ] - }, - unifiedTabsByWorktree: { - [wt]: [ - makeUnifiedTab({ - id: terminalTabId, - entityId: terminalTabId, - worktreeId: wt, - groupId, - contentType: 'terminal' - }), - makeUnifiedTab({ - id: 'browser-view-1', - entityId: browserTabId, - worktreeId: wt, - groupId, - contentType: 'browser', - label: 'Example' - }) - ] - }, - groupsByWorktree: { - [wt]: [ - makeTabGroup({ - id: groupId, - worktreeId: wt, - activeTabId: 'browser-view-1', - tabOrder: [terminalTabId, 'browser-view-1'] - }) - ] - }, - layoutByWorktree: { - [wt]: { type: 'leaf', groupId } - }, - activeGroupIdByWorktree: { [wt]: groupId } - }) - main = await drawTabsFromMain(store) - - store.getState().closeBrowserTab(browserTabId) - await main.settle() - - const s = store.getState() - expect(s.groupsByWorktree[wt]?.[0]?.activeTabId).toBe(terminalTabId) - expect(s.activeTabType).toBe('terminal') - expect(s.activeTabTypeByWorktree[wt]).toBe('terminal') - expect(s.activeTabId).toBe(terminalTabId) - expect(s.activeBrowserTabId).toBeNull() - expect(s.activeBrowserTabIdByWorktree[wt]).toBeNull() - }) -}) diff --git a/src/renderer/src/store/slices/browser/cleanup/browser-close-mru-selection.test.ts b/src/renderer/src/store/slices/browser/cleanup/browser-close-mru-selection.test.ts deleted file mode 100644 index 2ae9b728a19..00000000000 --- a/src/renderer/src/store/slices/browser/cleanup/browser-close-mru-selection.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' -import { createTestStore, seedStore } from '../../../testing/app-store-test-fixture' - -import { makeWorktree } from '../../worktrees/worktree.test-fixture' -import { createStoreCascadesMockApi } from '../../../testing/app-store-cascade-api.test-fixture' -import { - drawTabsFromMain, - type TabsDrawnFromMain -} from '../../tabs/tabs-drawn-from-main.test-fixture' - -const mockUnregisterPtyDataHandlers = vi.hoisted(() => vi.fn<() => unknown[]>(() => [])) -const mockRestorePtyDataHandlersAfterFailedShutdown = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) - -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: mockRestorePtyDataHandlersAfterFailedShutdown, - unregisterPtyDataHandlers: mockUnregisterPtyDataHandlers -})) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) - } -}) - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) - -const mockApi = createStoreCascadesMockApi() - -let main: TabsDrawnFromMain | undefined -afterEach(() => { - main?.close() - main = undefined -}) - -/** Every change is drawn once this resolves; at once with the switch off. */ -async function settled(): Promise { - await main?.settle() -} - -describe('setActiveWorktree', () => { - beforeEach(() => { - vi.clearAllMocks() - mockApi.worktrees.updateMeta.mockResolvedValue({}) - }) - - it('uses unified MRU selection when closing an active browser tab', async () => { - const store = createTestStore() - const wt = 'repo1::/path/wt1' - - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] - }, - activeWorktreeId: wt - }) - main = await drawTabsFromMain(store) - - const previous = store.getState().createBrowserTab(wt, 'https://previous.example.com') - await settled() - store.getState().createBrowserTab(wt, 'https://neighbor.example.com') - await settled() - const closing = store.getState().createBrowserTab(wt, 'https://closing.example.com') - await settled() - store.getState().setActiveBrowserTab(previous.id) - await settled() - store.getState().setActiveBrowserTab(closing.id) - await settled() - - store.getState().closeBrowserTab(closing.id) - await settled() - - expect(store.getState().activeBrowserTabId).toBe(previous.id) - expect(store.getState().activeBrowserTabIdByWorktree[wt]).toBe(previous.id) - }) - - it('keeps the unified MRU target when closing the last browser tab', async () => { - const store = createTestStore() - const wt = 'repo1::/path/wt1' - - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] - }, - activeWorktreeId: wt - }) - main = await drawTabsFromMain(store) - - store.getState().createTab(wt) - await settled() - const previous = store.getState().createTab(wt) - await settled() - const closing = store.getState().createBrowserTab(wt, 'https://closing.example.com') - await settled() - - store.getState().closeBrowserTab(closing.id) - await settled() - - expect(store.getState().activeTabId).toBe(previous.id) - expect(store.getState().activeTabType).toBe('terminal') - }) -}) diff --git a/src/renderer/src/store/slices/tabs/recently-closed-tabs.test.ts b/src/renderer/src/store/slices/tabs/recently-closed-tabs.test.ts deleted file mode 100644 index 9b6f6fa23f4..00000000000 --- a/src/renderer/src/store/slices/tabs/recently-closed-tabs.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -// Reopen terminal/browser/editor snapshots in true cross-type MRU order via Cmd/Ctrl+Shift+T. -import { describe, it, expect, vi, beforeEach } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } -})) - -vi.mock('@/components/terminal-pane/pty-transport/delivery/pty-dispatcher', () => ({})) - -vi.mock('@/components/terminal-pane/pty-transport/shutdown/pty-shutdown-data-suspension', () => ({ - restorePtyDataHandlersAfterFailedShutdown: vi.fn(), - unregisterPtyDataHandlers: vi.fn() -})) - -vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } -}) - -const mockApi = { - worktrees: { - remove: vi.fn().mockResolvedValue(undefined), - updateMeta: vi.fn().mockResolvedValue({}) - }, - pty: { kill: vi.fn().mockResolvedValue(undefined) }, - runtimeEnvironments: { call: vi.fn().mockResolvedValue({ ok: true, result: {} }) } -} - -// @ts-expect-error -- minimal window.api stub for the store under test -globalThis.window = { api: mockApi } - -import { createTestStore, seedStore } from '../../testing/app-store-test-fixture' -import { makeWorktree } from '../worktrees/worktree.test-fixture' -import { makeOpenFile } from '../editor/types/open-file.test-fixture' - -import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture' -import { drawTabsFromMain } from './tabs-drawn-from-main.test-fixture' - -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeRpcClientWithLayoutApply(await importOriginal()) -) -vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) => - ( - await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture') - ).runtimeLayoutClientWithTestFrames(await importOriginal()) -) - -const WT = 'repo1::/path/wt1' - -function makeSeededStore(): ReturnType { - const store = createTestStore() - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt1' })] - }, - activeWorktreeId: WT - }) - return store -} - -beforeEach(() => { - vi.clearAllMocks() -}) - -describe('reopenClosedTab cross-type MRU', () => { - it('reopens closed tabs of mixed kinds in most-recent-first order', async () => { - const store = makeSeededStore() - // A layout-owner build draws the browser tab from main's frames. - const main = await drawTabsFromMain(store) - - store.setState({ openFiles: [makeOpenFile({ id: '/repo/a.ts', worktreeId: WT })] }) - store.getState().closeFile('/repo/a.ts') - const terminal = store - .getState() - .createTab(WT, undefined, undefined, { startupCwd: '/path/wt1/api' }) - store.getState().closeTab(terminal.id) - await layoutApplyTestTransport.settle() - const browser = store.getState().createBrowserTab(WT, 'https://example.com', { title: 'Ex' }) - await main.settle() - store.getState().closeBrowserTab(browser.id) - await main.settle() - - expect(store.getState().recentlyClosedTabKindsByWorktree[WT]).toEqual([ - 'browser', - 'terminal', - 'editor' - ]) - - expect(store.getState().reopenClosedTab(WT)).toBe(true) - await main.settle() - expect(store.getState().browserTabsByWorktree[WT]?.[0]?.url).toBe('https://example.com') - expect(store.getState().tabsByWorktree[WT] ?? []).toHaveLength(0) - - expect(store.getState().reopenClosedTab(WT)).toBe(true) - expect(store.getState().tabsByWorktree[WT]?.[0]?.startupCwd).toBe('/path/wt1/api') - expect(store.getState().openFiles).toHaveLength(0) - - expect(store.getState().reopenClosedTab(WT)).toBe(true) - expect(store.getState().openFiles[0]?.filePath).toBe('/repo/a.ts') - - expect(store.getState().reopenClosedTab(WT)).toBe(false) - main.close() - }) - - it('skips kind entries whose per-type snapshot has drained', () => { - const store = makeSeededStore() - store.setState({ - recentlyClosedTabKindsByWorktree: { [WT]: ['browser', 'terminal'] }, - recentlyClosedTerminalTabsByWorktree: { [WT]: [{ startupCwd: '/path/wt1' }] }, - recentlyClosedBrowserTabsByWorktree: { [WT]: [] } - }) - - expect(store.getState().reopenClosedTab(WT)).toBe(true) - - expect(store.getState().tabsByWorktree[WT]?.[0]?.startupCwd).toBe('/path/wt1') - expect(store.getState().recentlyClosedTabKindsByWorktree[WT]).toEqual([]) - }) -}) diff --git a/src/renderer/src/store/slices/tabs/tabs-hydration-group-validation.test.ts b/src/renderer/src/store/slices/tabs/tabs-hydration-group-validation.test.ts deleted file mode 100644 index 9a18c255f8d..00000000000 --- a/src/renderer/src/store/slices/tabs/tabs-hydration-group-validation.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { WorkspaceSessionState } from '../../../../../shared/workspace-session/workspace-session-state-types' -import { buildHydratedTabState } from './tabs-hydration' - -function makeBaseSession(): WorkspaceSessionState { - return { - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {} - } -} - -describe('buildHydratedTabState referential repair', () => { - const tab = (id: string, groupId: string, sortOrder: number) => ({ - id, - entityId: id, - groupId, - worktreeId: 'w1', - contentType: 'terminal' as const, - label: id, - customLabel: null, - color: null, - sortOrder, - createdAt: 1 - }) - - function leafGroupIds(node: unknown): string[] { - const layout = node as - | { type: 'leaf'; groupId: string } - | { type: 'split'; first: unknown; second: unknown } - return layout.type === 'leaf' - ? [layout.groupId] - : [...leafGroupIds(layout.first), ...leafGroupIds(layout.second)] - } - - it('keeps tabs reachable when a worktree lost every tab group', () => { - // Salvage can drop groups but retain tabs; groupless tabs block auto-create yet render nowhere, leaving a blank workspace. - const result = buildHydratedTabState( - { - ...makeBaseSession(), - unifiedTabs: { w1: [tab('t1', 'g1', 0), tab('t2', 'g1', 1)] }, - tabGroups: { w1: [] } - }, - new Set(['w1']) - ) - - const groups = result.groupsByWorktree.w1 - expect(groups).toHaveLength(1) - expect(groups[0].tabOrder).toEqual(['t1', 't2']) - expect(groups[0].activeTabId).toBe('t1') - expect(result.activeGroupIdByWorktree.w1).toBe(groups[0].id) - expect(leafGroupIds(result.layoutByWorktree.w1)).toEqual([groups[0].id]) - expect(result.unifiedTabsByWorktree.w1.map((t) => t.groupId)).toEqual([ - groups[0].id, - groups[0].id - ]) - }) -}) diff --git a/src/renderer/src/store/slices/ui/automations-page-history.test.ts b/src/renderer/src/store/slices/ui/automations-page-history.test.ts deleted file mode 100644 index ddc5678e505..00000000000 --- a/src/renderer/src/store/slices/ui/automations-page-history.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { useAppStore } from '../../index' -import { - rewindHistoryIndexPastView, - type WorktreeNavHistoryEntry -} from './workspace-navigation-history' -import { appendAutomationsPageEntry } from './automations-page-history' -import { - automationsPageLocationKey, - type AutomationsPageLocation -} from './automations-page-location' - -const detail: AutomationsPageLocation = { page: 'detail', automationId: 'a1' } -const run: AutomationsPageLocation = { - page: 'run', - automationId: 'a1', - runId: 'r1', - origin: 'automation' -} -const page = (location: AutomationsPageLocation): WorktreeNavHistoryEntry => ({ - kind: 'automations-page', - location -}) - -describe('automations page history', () => { - it('preserves Forward entries when replay replaces a legacy sentinel', () => { - const next = appendAutomationsPageEntry( - { worktreeNavHistory: ['skills', 'automations', 'artifacts'], worktreeNavHistoryIndex: 1 }, - { page: 'list' } - ) - expect(next.worktreeNavHistory).toEqual([ - 'skills', - { kind: 'automations-page', location: { page: 'list' } }, - 'artifacts' - ]) - expect(next.worktreeNavHistoryIndex).toBe(1) - }) - - it('appends each sub-page so Back steps run → detail → list → previous view', () => { - let s: { worktreeNavHistory: WorktreeNavHistoryEntry[]; worktreeNavHistoryIndex: number } = { - worktreeNavHistory: ['skills', 'automations'], - worktreeNavHistoryIndex: 1 - } - s = appendAutomationsPageEntry(s, { page: 'list' }) - s = appendAutomationsPageEntry(s, detail) - s = appendAutomationsPageEntry(s, run) - expect(s.worktreeNavHistory).toEqual([ - 'skills', - page({ page: 'list' }), - page(detail), - page(run) - ]) - expect(s.worktreeNavHistoryIndex).toBe(3) - }) - - it('does not duplicate the current sub-page, whatever the run origin', () => { - const s: { worktreeNavHistory: WorktreeNavHistoryEntry[]; worktreeNavHistoryIndex: number } = { - worktreeNavHistory: ['skills', page(run)], - worktreeNavHistoryIndex: 1 - } - const next = appendAutomationsPageEntry(s, { ...run, origin: 'runs' }) - expect(next).toBe(s) - }) - - it('Escape to the previous entry steps back and keeps the left page as Forward', () => { - const next = appendAutomationsPageEntry( - { worktreeNavHistory: ['skills', page(detail), page(run)], worktreeNavHistoryIndex: 2 }, - detail, - 'return' - ) - expect(next.worktreeNavHistory).toEqual(['skills', page(detail), page(run)]) - expect(next.worktreeNavHistoryIndex).toBe(1) - }) - - it('Escape to a parent that is not the previous entry appends it', () => { - const next = appendAutomationsPageEntry( - { worktreeNavHistory: ['skills', page(run)], worktreeNavHistoryIndex: 1 }, - detail, - 'return' - ) - expect(next.worktreeNavHistory).toEqual(['skills', page(run), page(detail)]) - expect(next.worktreeNavHistoryIndex).toBe(2) - }) - - it('keys locations by host so same-id automations on two hosts stay distinct', () => { - expect(automationsPageLocationKey(detail)).not.toBe( - automationsPageLocationKey({ ...detail, hostId: 'runtime:env-1' }) - ) - }) - - it('closing the page rewinds past every Automations entry', () => { - const state = { - ...useAppStore.getInitialState(), - worktreeNavHistory: ['skills', page({ page: 'list' }), page(detail), page(run)], - worktreeNavHistoryIndex: 3 - } - expect(rewindHistoryIndexPastView(state, 'automations')).toBe(0) - }) -}) diff --git a/src/renderer/src/store/slices/ui/ui-host-filter-sync.test.ts b/src/renderer/src/store/slices/ui/ui-host-filter-sync.test.ts deleted file mode 100644 index bb15fb3c0c8..00000000000 --- a/src/renderer/src/store/slices/ui/ui-host-filter-sync.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createUIStore, makePersistedUI } from './ui-slice-test-harness' - -beforeEach(() => { - vi.stubGlobal('window', { api: { ui: { set: vi.fn().mockResolvedValue(undefined) } } }) -}) -afterEach(() => vi.unstubAllGlobals()) - -describe('host visibility across saved UI broadcasts', () => { - it('keeps All hosts while the prior selection is being saved', () => { - const store = createUIStore() - const previous = makePersistedUI({ workspaceHostScope: 'all', visibleWorkspaceHostIds: null }) - store.getState().hydratePersistedUI(previous) - const fields = ['workspaceHostScope', 'visibleWorkspaceHostIds'] as const - store.getState().setWorkspaceHostScope('local') - store.getState().notePersistedUIWriteStarted(fields) - store.getState().setWorkspaceHostScope('all') - - store - .getState() - .hydratePersistedUI( - makePersistedUI({ workspaceHostScope: 'local', visibleWorkspaceHostIds: ['local'] }), - 'sync' - ) - - expect(store.getState().workspaceHostScope).toBe('all') - expect(store.getState().visibleWorkspaceHostIds).toBeNull() - }) -}) diff --git a/src/renderer/src/store/slices/workspace-attention/workspace-unread-on-screen-characterization.test.ts b/src/renderer/src/store/slices/workspace-attention/workspace-unread-on-screen-characterization.test.ts deleted file mode 100644 index 9c5c1819f91..00000000000 --- a/src/renderer/src/store/slices/workspace-attention/workspace-unread-on-screen-characterization.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as WorktreeMetaPersistModule from '../worktrees/metadata/worktree-meta-persist' -import '../../../../../shared/agent-session/view/structured-agent-session-projection' -import '@/attention/agent-subject-read-actions' - -import { - completeAgentTurn, - pointerDownInTab, - ringBell, - setWindowOnScreen -} from './workspace-unread-characterization-driver' -import { - addLiveTerminalTab, - createAttentionStore, - installAttentionMockApi, - observe, - WS_A -} from './workspace-unread-characterization-fixture' - -// On screen means read, the flag follows its markers, and reads retire OS notifications. - -vi.mock('sonner', () => ({ - toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn(), dismiss: vi.fn() } -})) - -vi.mock('../worktrees/metadata/worktree-meta-persist', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, persistWorktreeMeta: vi.fn(async () => undefined) } -}) - -let dismiss: ReturnType - -beforeEach(() => { - vi.clearAllMocks() - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(1000) - dismiss = installAttentionMockApi() -}) - -afterEach(() => { - vi.useRealTimers() -}) - -const dismissedPaneKeys = (): string[][] => - dismiss.mock.calls.map((call) => [...(call[1] ?? [])].sort()) - -describe('on screen means read', () => { - it('clears the workspace dot when returning input reads a completed agent on the same tab', async () => { - const { store } = createAttentionStore({ desktopAway: true }) - const pane = addLiveTerminalTab(store, WS_A, 'tab-a1') - store.getState().setActiveWorktree(WS_A) - store.setState({ - agentStatusByPaneKey: acceptedAgentStatuses( - Object.entries({ - [pane.paneKey]: { - state: 'done', - prompt: 'Fix the sidebar', - updatedAt: 900, - stateStartedAt: 900, - stateHistory: [], - agentType: 'claude', - ...pane - } - }) - ) - }) - completeAgentTurn(store, pane) - await Promise.resolve() - await Promise.resolve() - expect(store.getState().worktreesByRepo.repo1![0]!.isUnread).toBe(true) - - pointerDownInTab(store, pane) - - expect(store.getState().unreadAgentCompletionPanes).toEqual({}) - expect(store.getState().worktreesByRepo.repo1![0]!.isUnread).toBe(false) - }) - - it('a bell on screen waits while the window is unfocused and is read when focus returns', () => { - const { store, persists } = createAttentionStore({ windowOnScreen: false }) - const pane = addLiveTerminalTab(store, WS_A, 'tab-a1') - store.getState().setActiveWorktree(WS_A) - observe(store, persists) - - ringBell(store, pane) - expect(observe(store, persists)).toMatchInlineSnapshot(` - [ - "rows a@local:UNREAD:1000 b@local:read:0 sortEpoch=1", - "tabs tab-a1=terminal-bell", - "panes -", - "completions -", - "dock=1 floatingDot=false", - "persist worktree a {"isUnread":true,"lastActivityAt":1000}", - ] - `) - expect(dismiss).not.toHaveBeenCalled() - - setWindowOnScreen(store, true) - expect(observe(store, persists)).toMatchInlineSnapshot(` - [ - "rows a@local:read:1000 b@local:read:0 sortEpoch=1", - "tabs -", - "panes -", - "completions -", - "dock=0 floatingDot=false", - "persist worktree a {"isUnread":false}", - ] - `) - expect(dismissedPaneKeys()).toEqual([[pane.paneKey]]) - }) -}) diff --git a/src/shared/github/pull-requests/merge/pull-request-auto-merge-availability.test.ts b/src/shared/github/pull-requests/merge/pull-request-auto-merge-availability.test.ts deleted file mode 100644 index cfc2789e5e3..00000000000 --- a/src/shared/github/pull-requests/merge/pull-request-auto-merge-availability.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - canShowGitHubPRAutoMergeControl, - type GitHubPRAutoMergeAvailabilityInput -} from './pull-request-auto-merge-availability' - -function pr( - overrides: Partial = {} -): GitHubPRAutoMergeAvailabilityInput { - return { - state: 'open', - mergeable: 'MERGEABLE', - mergeStateStatus: 'CLEAN', - autoMergeAllowed: true, - ...overrides - } -} - -describe('github PR auto-merge availability', () => { - it('offers auto-merge for requirement-blocked PRs', () => { - expect( - canShowGitHubPRAutoMergeControl( - pr({ mergeable: 'UNKNOWN', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED' }) - ) - ).toBe(true) - expect(canShowGitHubPRAutoMergeControl(pr({ mergeStateStatus: 'BLOCKED' }))).toBe(true) - expect(canShowGitHubPRAutoMergeControl(pr({ mergeStateStatus: 'BEHIND' }))).toBe(true) - expect( - canShowGitHubPRAutoMergeControl(pr({ mergeable: 'UNKNOWN', mergeStateStatus: 'BLOCKED' })) - ).toBe(true) - }) - - it('keeps merge-queue branches available for merge-when-ready', () => { - expect(canShowGitHubPRAutoMergeControl(pr({ mergeQueueRequired: true }))).toBe(true) - expect( - canShowGitHubPRAutoMergeControl(pr({ autoMergeAllowed: false, mergeQueueRequired: true })) - ).toBe(true) - expect( - canShowGitHubPRAutoMergeControl( - pr({ mergeStateStatus: 'UNSTABLE', mergeQueueRequired: true }) - ) - ).toBe(true) - }) - - it('keeps enabled auto-merge visible so users can disable it', () => { - expect(canShowGitHubPRAutoMergeControl(pr({ autoMergeEnabled: true }))).toBe(true) - expect( - canShowGitHubPRAutoMergeControl( - pr({ - autoMergeEnabled: true, - autoMergeAllowed: false, - mergeable: 'CONFLICTING', - mergeStateStatus: 'DIRTY' - }) - ) - ).toBe(true) - }) - - it('suppresses closed, draft, disallowed, conflicting, and unstable PRs', () => { - expect( - canShowGitHubPRAutoMergeControl(pr({ state: 'draft', mergeStateStatus: 'BLOCKED' })) - ).toBe(false) - expect(canShowGitHubPRAutoMergeControl(pr({ state: 'closed', autoMergeEnabled: true }))).toBe( - false - ) - expect( - canShowGitHubPRAutoMergeControl( - pr({ autoMergeAllowed: false, mergeable: 'UNKNOWN', mergeStateStatus: 'BLOCKED' }) - ) - ).toBe(false) - expect( - canShowGitHubPRAutoMergeControl(pr({ mergeable: 'CONFLICTING', mergeStateStatus: 'DIRTY' })) - ).toBe(false) - expect( - canShowGitHubPRAutoMergeControl(pr({ mergeable: 'UNKNOWN', mergeStateStatus: 'UNSTABLE' })) - ).toBe(false) - }) -}) diff --git a/src/shared/jira/jira-saved-filters.test.ts b/src/shared/jira/jira-saved-filters.test.ts deleted file mode 100644 index 646e24e65a8..00000000000 --- a/src/shared/jira/jira-saved-filters.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - mutateJiraSavedFilterState, - normalizeJiraSavedFilterState, - MAX_JIRA_SAVED_FILTERS -} from './jira-saved-filters' -const mine = { id: 'mine', name: 'My work', jql: 'assignee = currentUser()' } -const bugs = { id: 'bugs', name: 'Bugs', jql: 'project = APP AND type = Bug' } - -describe('host Jira saved filters', () => { - it('updates and renames only the targeted filter and clears a deleted selection', () => { - const initial = { filters: [mine, bugs], activeFilterId: mine.id } - const renamed = { ...mine, name: 'Active work', jql: 'status = Open' } - const updated = mutateJiraSavedFilterState(initial, { kind: 'save', filter: renamed }) - expect(updated).toEqual({ filters: [renamed, bugs], activeFilterId: mine.id }) - expect(initial.filters[0]).toEqual(mine) - expect(mutateJiraSavedFilterState(updated, { kind: 'delete', id: mine.id })).toEqual({ - filters: [bugs], - activeFilterId: null - }) - }) - it('never silently overwrites duplicate names or corrupts filters after rejected edits', () => { - const initial = { filters: [mine, bugs], activeFilterId: mine.id } - expect(() => - mutateJiraSavedFilterState(initial, { kind: 'save', filter: { ...mine, name: ' bugs ' } }) - ).toThrow('already exists') - expect(() => - mutateJiraSavedFilterState(initial, { kind: 'save', filter: { ...mine, jql: '' } }) - ).toThrow('Invalid') - expect(initial.filters).toEqual([mine, bugs]) - // Jira validates syntax when the stored text is run, not while it is saved. - expect( - mutateJiraSavedFilterState(initial, { kind: 'save', filter: { ...mine, jql: 'invalid JQL' } }) - .filters[0]?.jql - ).toBe('invalid JQL') - }) - it('bounds malformed persisted values, removes duplicate IDs and clears dangling selections', () => { - expect( - normalizeJiraSavedFilterState({ - filters: [mine, null, { ...bugs, id: mine.id }, { ...bugs, name: ' my work ' }, bugs], - activeFilterId: 'missing' - }) - ).toEqual({ filters: [mine, bugs], activeFilterId: null }) - const filters = Array.from({ length: MAX_JIRA_SAVED_FILTERS }, (_, index) => ({ - ...mine, - id: String(index), - name: String(index) - })) - expect(() => mutateJiraSavedFilterState({ filters }, { kind: 'save', filter: bugs })).toThrow( - 'limit' - ) - expect(() => - mutateJiraSavedFilterState({ filters: [mine] }, { kind: 'select', id: 'deleted' }) - ).toThrow('no longer exists') - }) -}) diff --git a/src/shared/native-chat/native-chat-reasoning-order.spec.ts b/src/shared/native-chat/native-chat-reasoning-order.spec.ts deleted file mode 100644 index 534bb1f8f74..00000000000 --- a/src/shared/native-chat/native-chat-reasoning-order.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { expect, it } from 'vitest' -import type { NativeChatMessage } from './native-chat-types' -import { - compareNativeChatTranscriptMessages, - projectNativeChatTranscriptMessages -} from './transcript/native-chat-transcript-projection' - -function row(id: string, role: NativeChatMessage['role'], timestamp = 1): NativeChatMessage { - return { id, role, timestamp, source: 'transcript', blocks: [{ type: 'text', text: id }] } -} - -it('keeps derived reasoning immediately before its answer without changing provider timestamps', () => { - const messages = [ - row('opencode:msg_b', 'assistant'), - row('opencode:msg_a:other', 'assistant'), - row('opencode:msg_a', 'assistant'), - row('opencode:msg_b:reasoning', 'reasoning'), - row('opencode:msg_a:reasoning', 'reasoning') - ] - const sorted = [...messages].sort(compareNativeChatTranscriptMessages) - expect(sorted.map((message) => message.id)).toEqual([ - 'opencode:msg_a:reasoning', - 'opencode:msg_a', - 'opencode:msg_a:other', - 'opencode:msg_b:reasoning', - 'opencode:msg_b' - ]) - expect(projectNativeChatTranscriptMessages(messages)).toEqual(sorted) - expect(messages.every((message) => message.timestamp === 1)).toBe(true) - for (let first = 0; first < sorted.length; first++) { - for (let second = first + 1; second < sorted.length; second++) { - expect(compareNativeChatTranscriptMessages(sorted[first], sorted[second])).toBeLessThan(0) - expect(compareNativeChatTranscriptMessages(sorted[second], sorted[first])).toBeGreaterThan(0) - } - } -}) - -it('keeps timestamp and journal authority ahead of a derived reasoning key', () => { - const answer = row('row', 'assistant', 1) - const laterReasoning = row('row:reasoning', 'reasoning', 2) - expect(compareNativeChatTranscriptMessages(answer, laterReasoning)).toBeLessThan(0) - answer.journalPosition = { sequence: 1, index: 0 } - laterReasoning.journalPosition = { sequence: 2, index: 0 } - laterReasoning.timestamp = 0 - expect(compareNativeChatTranscriptMessages(answer, laterReasoning)).toBeLessThan(0) -}) - -it('preserves a provider sequence ahead of timestamps and keeps split reasoning beside its answer', () => { - const messages = [ - row('pending-send', 'user', 50), - { ...row('a', 'assistant', 0), transcriptOrder: 2 }, - { ...row('z', 'assistant', 100), transcriptOrder: 1 }, - { ...row('z:reasoning', 'reasoning', 100), transcriptOrder: 1 } - ] - expect(projectNativeChatTranscriptMessages(messages).map((message) => message.id)).toEqual([ - 'z:reasoning', - 'z', - 'a', - 'pending-send' - ]) -}) diff --git a/src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts b/src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts deleted file mode 100644 index 70813875a34..00000000000 --- a/src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { pairToolBlocks, type NativeChatToolPair } from './native-chat-tool-pairs' -import type { NativeChatToolCallBlock, NativeChatToolResultBlock } from '../native-chat-types' - -function call(callId?: string): NativeChatToolCallBlock { - return { type: 'tool-call', name: 'Bash', input: {}, ...(callId !== undefined ? { callId } : {}) } -} - -function result(callId?: string): NativeChatToolResultBlock { - return { type: 'tool-result', output: 'done', ...(callId !== undefined ? { callId } : {}) } -} - -function expectSameReferences( - actual: readonly NativeChatToolPair[], - expected: readonly NativeChatToolPair[] -): void { - expect(actual).toEqual(expected) - actual.forEach((pair, index) => { - expect(pair.call).toBe(expected[index]?.call) - expect(pair.result).toBe(expected[index]?.result) - }) -} - -describe('tool pairing identity and ordering', () => { - it('matches repeated and empty IDs FIFO while positional results consume the oldest call', () => { - const calls = [call('same'), call(''), call('same'), call(), call('same')] - const results = [result('same'), result(), result('same'), result(), result('same')] - const blocks = Object.freeze([ - ...calls.map((block) => Object.freeze(block)), - ...results.map((block) => Object.freeze(block)) - ]) - expectSameReferences(pairToolBlocks(blocks), [ - { call: calls[0], result: results[0] }, - { call: calls[1], result: results[1] }, - { call: calls[2], result: results[2] }, - { call: calls[3], result: results[3] }, - { call: calls[4], result: results[4] } - ]) - }) - - it('does not retroactively answer future calls or consume unrelated calls for a named result', () => { - const early = result('later') - const pending = call('waiting') - const unrelated = result('other') - const later = call('later') - const completed = result('later') - const positional = result() - const repeated = result('later') - expectSameReferences( - pairToolBlocks([early, pending, unrelated, later, completed, positional, repeated]), - [ - { result: early }, - { call: pending, result: positional }, - { result: unrelated }, - { call: later, result: completed }, - { result: repeated } - ] - ) - }) -}) diff --git a/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts b/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts index 503f24f97e5..6766f1e80d9 100644 --- a/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts +++ b/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts @@ -1,4 +1,3 @@ -import '../native-chat-reasoning-order.spec' import '../tools/native-chat-tool-pair-limit.spec' import '../tools/native-chat-tool-fold-attribution.spec' import '../tools/native-chat-tool-pairing.spec' diff --git a/src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts b/src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts index 0128029e0f6..b6d347b82b8 100644 --- a/src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts +++ b/src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts @@ -1,4 +1,3 @@ -import '../native-chat-reasoning-order.spec' import { describe, expect, it } from 'vitest' import type { AgentJournalItemBody, diff --git a/src/shared/plugins/catalog/plugin-catalog.test.ts b/src/shared/plugins/catalog/plugin-catalog.test.ts deleted file mode 100644 index 75fe6960ce5..00000000000 --- a/src/shared/plugins/catalog/plugin-catalog.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { legacyPluginCatalog } from '../../../../config/scripts/plugin-authoring/content-validation/export-legacy-plugin-catalog.mjs' -import { pluginCatalogSchema, selectPluginCatalogRelease } from './plugin-catalog' -import { pluginCatalogReleaseSchema } from './plugin-catalog-release' -import { pluginMarketplaceSchema } from './plugin-marketplace' - -function release(version: string, minimumOrca = '1.4.0') { - return pluginCatalogReleaseSchema.parse({ - version, - commit: 'a'.repeat(40), - contentHash: 'b'.repeat(64), - execution: 'data', - minimumOrca, - types: ['app-theme'] - }) -} - -function entry(id: string, overrides: Record = {}) { - return { - id, - source: { kind: 'git', url: `https://github.com/acme/${id}.git`, ref: 'main' }, - categories: ['themes'], - releases: [release('1.0.0')], - ...overrides - } -} - -function catalog(plugins: unknown[], extra: Record = {}) { - return { catalogVersion: 2, name: 'Acme', owner: 'acme', plugins, ...extra } -} - -describe('plugin catalog', () => { - it('offers the newest release this Orca can install', () => { - const releases = [ - release('3.0.0', '2.0.0'), - release('2.0.0', '1.5.0'), - release('1.0.0', '1.4.0') - ] - expect(selectPluginCatalogRelease(releases, '1.6.0')?.version).toBe('2.0.0') - expect(selectPluginCatalogRelease(releases, '2.1.0')?.version).toBe('3.0.0') - // Why the smallest: "Needs Orca X" should name the first Orca that unlocks anything. - expect(selectPluginCatalogRelease(releases, '1.0.0')?.version).toBe('1.0.0') - expect( - selectPluginCatalogRelease([release('2.0.0', '9.0.0'), release('1.0.0', '8.0.0')], '1.0.0') - ?.minimumOrca - ).toBe('8.0.0') - }) - - it('leaves plugins in a repository directory out of the frozen v1 file', () => { - const nested = entry('acme.two', { - source: { kind: 'git', url: 'https://github.com/acme/plugins.git', ref: 'main', path: 'two' } - }) - const parsed = pluginCatalogSchema.parse(catalog([entry('acme.one'), nested])) - const legacy = legacyPluginCatalog(parsed) - expect(legacy.plugins.map((plugin: { id: string }) => plugin.id)).toEqual(['acme.one']) - expect( - pluginMarketplaceSchema.safeParse({ - ...legacy, - plugins: [{ ...legacy.plugins[0], source: nested.source }] - }).success - ).toBe(false) - }) -}) diff --git a/src/shared/plugins/declarative/runtime/declarative-storage-sync.test.ts b/src/shared/plugins/declarative/runtime/declarative-storage-sync.test.ts deleted file mode 100644 index 5826a6ab7e1..00000000000 --- a/src/shared/plugins/declarative/runtime/declarative-storage-sync.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { atom, read, set } from './declarative-atoms' -import { h } from './declarative-elements' -import { createOrcaDeclarativeRuntime } from './declarative-renderer' -import type { OrcaBridge } from './declarative-runtime-types' - -function storageBridge(initial: Record) { - const values = new Map(Object.entries(initial)) - const listeners = new Set<(change: { key: string }) => void>() - const storage = { - get: vi.fn(async (key: string) => values.get(key) ?? null), - set: vi.fn(async (key: string, value: unknown) => void values.set(key, value)), - delete: vi.fn(async () => undefined), - keys: vi.fn(async () => [...values.keys()]), - onDidChange: (listener: (change: { key: string }) => void) => { - listeners.add(listener) - return { dispose: () => listeners.delete(listener) } - } - } - const bridge: OrcaBridge = { on: () => ({ dispose: () => undefined }), storage } - const workerWrites = (key: string, value: unknown) => { - values.set(key, value) - for (const listener of listeners) { - listener({ key }) - } - } - return { bridge, storage, workerWrites } -} - -describe("persist: 'storage' atoms", () => { - it("render the plugin's stored value first, write back under their key, and follow the worker", async () => { - vi.useFakeTimers() - const { bridge, storage, workerWrites } = storageBridge({ 'sync.todos': ['from worker'] }) - const todos = atom('sync.todos', [], { persist: 'storage' }) - const posted: { event: string; payload: unknown }[] = [] - const runtime = createOrcaDeclarativeRuntime({ - post: (event, payload) => posted.push({ event, payload }), - schedule: (flush) => queueMicrotask(flush), - bridge - }) - await runtime.boot({ default: () => h('Text', null, read(todos).join(',')) }) - expect(posted.at(-1)).toMatchObject({ payload: { tree: { children: ['from worker'] } } }) - - set(todos, ['mine']) - vi.advanceTimersByTime(500) - expect(storage.set).toHaveBeenCalledWith('sync.todos', ['mine']) - // Storage atoms never ride the panel-state channel. - expect(posted.some((entry) => entry.event === 'ui.persist')).toBe(false) - - workerWrites('sync.todos', ['worker again']) - await vi.waitFor(() => expect(read(todos)).toEqual(['worker again'])) - runtime.dispose() - vi.useRealTimers() - }) -}) diff --git a/src/shared/queued-message-edit-lease.test.ts b/src/shared/queued-message-edit-lease.test.ts deleted file mode 100644 index 7497fa30901..00000000000 --- a/src/shared/queued-message-edit-lease.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { beforeAll, afterEach, expect, it, vi } from 'vitest' -import { startQueuedEditLease, QUEUED_EDIT_LEASE_RENEW_MS } from './queued-message-edit-lease' -import type { QueuedEditHostFixtureModule } from './queued-edit-host.test-fixture' -import type { - AgentSessionQueuedMessageEditHoldParams, - AgentSessionQueuedMessageEditHoldResult -} from './agent-session/requests/agent-session-queued-message-wire' - -let queuedEditHost: QueuedEditHostFixtureModule['queuedEditHost'] -beforeAll(async () => { - const fixtures = await vi.importActual( - '../main/native-chat/agent-session-journal/queued-messages/queued-edit-host.test-fixture' - ) - queuedEditHost = fixtures.queuedEditHost -}) - -const message = { - messageId: 'card', - position: 1, - state: 'waiting' as const, - body: { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: 'A' }] - } -} -afterEach(() => vi.useRealTimers()) - -it('keeps the existing held/failure/expired-to-held request protocol without terminal delivery', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const host = queuedEditHost('session', message) - const onLost = vi.fn() - let fail = true - const request = vi.fn( - async ( - params: AgentSessionQueuedMessageEditHoldParams - ): Promise => { - if (params.action === 'release') { - return { status: 'released' } - } - if (params.action === 'renew' && fail) { - fail = false - throw new Error('offline') - } - return params.action === 'acquire' - ? host.acquire(params.editId, params.expectedBodyFingerprint ?? '') - : host.leases.renew({ callerKey: 'client', editId: params.editId }, params.messageId) - } - ) - const lease = startQueuedEditLease({ - sessionId: 'session', - messageId: 'card', - editId: 'edit', - expectedBodyFingerprint: host.row!.fingerprint, - request, - onLost - }) - await lease.acquired - await vi.advanceTimersByTimeAsync(QUEUED_EDIT_LEASE_RENEW_MS) - host.leases.retire('card') - await vi.advanceTimersByTimeAsync(QUEUED_EDIT_LEASE_RENEW_MS) - expect(request.mock.calls.map(([params]) => params.action)).toEqual([ - 'acquire', - 'renew', - 'renew', - 'acquire' - ]) - expect(host.leases.heldIds()).toEqual(new Set(['card'])) - expect(onLost).not.toHaveBeenCalled() - lease.end() - await vi.advanceTimersByTimeAsync(0) - host.leases.dispose() - warn.mockRestore() -}) diff --git a/src/shared/remote-runtime/ssh/ssh-pending-pty-kill.test.ts b/src/shared/remote-runtime/ssh/ssh-pending-pty-kill.test.ts deleted file mode 100644 index 04493f9b347..00000000000 --- a/src/shared/remote-runtime/ssh/ssh-pending-pty-kill.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { normalizeSshPendingPtyKill } from './ssh-pending-pty-kill' - -// Epoch-scoped pty2: IDs fence one process even when incarnation was never learned. -describe('normalizeSshPendingPtyKill', () => { - const unfenced = { requestedAt: 1_800_000_000_000, attempts: 0 } - - it('keeps an unfenced order for an epoch-scoped relay id and drops it for a legacy one', () => { - expect(normalizeSshPendingPtyKill(unfenced, 'pty2:epoch-a:3')).toEqual(unfenced) - expect(normalizeSshPendingPtyKill(unfenced, 'pty-3')).toBeNull() - }) - - it('keeps a fenced order and drops a malformed one', () => { - const fenced = { ...unfenced, incarnationId: 'inc-a' } - expect(normalizeSshPendingPtyKill(fenced, 'pty-3')).toEqual(fenced) - expect(normalizeSshPendingPtyKill({ attempts: 0 }, 'pty2:epoch-a:3')).toBeNull() - }) -}) diff --git a/src/shared/sidebar-list/feed-facts/workspace-review-facts.test.ts b/src/shared/sidebar-list/feed-facts/workspace-review-facts.test.ts deleted file mode 100644 index cbad9c86d10..00000000000 --- a/src/shared/sidebar-list/feed-facts/workspace-review-facts.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildWorkspaceReviewFacts, readWorkspaceReviewFact } from './workspace-review-facts' - -const repo = { id: 'repo-1', path: '/r', connectionId: null, executionHostId: null } -const row = { id: 'repo-1::/r/a', repoId: 'repo-1', branch: 'refs/heads/a', linkedPR: null } -const pr = (state: string, number = 7) => ({ data: { number, state } }) - -describe('readWorkspaceReviewFact', () => { - it('prefers the repo-scoped entry over legacy ones', () => { - const cache = { 'repo-1::a': pr('merged'), '/r::a': pr('closed') } - expect(readWorkspaceReviewFact(row, repo, cache)).toEqual({ - provider: 'github', - reviewState: 'merged' - }) - expect(readWorkspaceReviewFact(row, repo, { '/r::a': pr('closed') })?.reviewState).toBe( - 'closed' - ) - }) - - it('reads only host-scoped entries for SSH and paired-server repos', () => { - const cache = { 'repo-1::a': pr('merged'), 'ssh:c1::repo-1::a': pr('open') } - expect(readWorkspaceReviewFact(row, { ...repo, connectionId: 'c1' }, cache)?.reviewState).toBe( - 'open' - ) - expect( - readWorkspaceReviewFact(row, { ...repo, executionHostId: 'runtime:env' }, cache) - ).toBeNull() - }) - - it('drops a PR the user unlinked, and rows with no repo, branch or PR', () => { - const cache = { 'repo-1::a': pr('open') } - expect(readWorkspaceReviewFact({ ...row, suppressedGitHubPR: 7 }, repo, cache)).toBeNull() - expect( - readWorkspaceReviewFact({ ...row, linkedPR: 7, suppressedGitHubPR: 7 }, repo, cache) - ).not.toBeNull() - expect(readWorkspaceReviewFact(row, undefined, cache)).toBeNull() - expect(readWorkspaceReviewFact({ ...row, branch: '' }, repo, cache)).toBeNull() - expect(readWorkspaceReviewFact(row, repo, { 'repo-1::a': { data: null } })).toBeNull() - }) -}) - -it('reads each host’s copy of a same-id workspace with its own repo, under its own key', () => { - const sshRepo = { ...repo, connectionId: 'box' } - const local = { ...row, hostId: 'local' as const } - const remote = { ...row, hostId: 'ssh:box' as const } - const cache = { 'repo-1::a': pr('merged'), 'ssh:box::repo-1::a': pr('open') } - expect(buildWorkspaceReviewFacts([local, remote], [repo, sshRepo], cache)).toEqual({ - [`local|${row.id}`]: { provider: 'github', reviewState: 'merged' }, - [`ssh:box|${row.id}`]: { provider: 'github', reviewState: 'open' } - }) -}) diff --git a/src/shared/sidebar-list/selection/sleeping-sweep-retention.test.ts b/src/shared/sidebar-list/selection/sleeping-sweep-retention.test.ts deleted file mode 100644 index 795636f0a0b..00000000000 --- a/src/shared/sidebar-list/selection/sleeping-sweep-retention.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - createSleepingSweepRetentionState, - SLEEPING_SWEEP_SETTLE_MS, - updateSleepingSweepRetention -} from './sleeping-sweep-retention' - -function runPass( - state: ReturnType, - activeIds: readonly string[], - nowMs: number, - candidates: readonly string[] = ['wt-a', 'wt-b'] -): ReturnType { - const active = new Set(activeIds) - return updateSleepingSweepRetention({ - state, - candidateWorktreeIds: candidates, - isActive: (id) => active.has(id), - nowMs - }) -} - -describe('sleeping sweep retention', () => { - it('retains a workspace whose liveness drops for a single pass', () => { - const state = createSleepingSweepRetentionState() - runPass(state, ['wt-a', 'wt-b'], 1_000) - - // The PTY rebind commit: wt-a reads inactive for one pass. - const dropped = runPass(state, ['wt-b'], 1_016) - expect([...dropped.retainedIds]).toEqual(['wt-a']) - - // Rebind settles; the grace window closes with no visible change. - const recovered = runPass(state, ['wt-a', 'wt-b'], 1_032) - expect([...recovered.retainedIds]).toEqual([]) - expect(recovered.nextExpiryInMs).toBeNull() - }) - - it('sweeps once the workspace stays inactive past the settle window', () => { - const state = createSleepingSweepRetentionState() - runPass(state, ['wt-a'], 1_000) - - // Start grace on first observed inactivity; time between passes must not consume it. - const during = runPass(state, [], 1_000) - expect([...during.retainedIds]).toEqual(['wt-a']) - - const after = runPass(state, [], 1_000 + SLEEPING_SWEEP_SETTLE_MS) - expect([...after.retainedIds]).toEqual([]) - expect(after.nextExpiryInMs).toBeNull() - }) - - it('drops grace state for a workspace that leaves the candidate set', () => { - const state = createSleepingSweepRetentionState() - runPass(state, ['wt-a'], 1_000) - // wt-a is deleted; a later id reuse must not inherit its grace window. - runPass(state, [], 1_100, ['wt-b']) - const reused = runPass(state, [], 1_200, ['wt-a', 'wt-b']) - - expect([...reused.retainedIds]).toEqual([]) - }) - - it('grants no grace when the caller marks the inactivity as definitive', () => { - const state = createSleepingSweepRetentionState() - runPass(state, ['wt-a', 'wt-b'], 1_000) - const result = updateSleepingSweepRetention({ - state, - candidateWorktreeIds: ['wt-a', 'wt-b'], - isActive: () => false, - isUnverifiableGap: (id) => id === 'wt-b', - nowMs: 1_016 - }) - expect([...result.retainedIds]).toEqual(['wt-b']) - }) -}) diff --git a/src/shared/sidebar-list/sorting/stamp-order.test.ts b/src/shared/sidebar-list/sorting/stamp-order.test.ts deleted file mode 100644 index 7053f8f8432..00000000000 --- a/src/shared/sidebar-list/sorting/stamp-order.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { compareSmartStamps, recentStamp, type StampOrderRow } from './stamp-order' - -function sortSmart(rows: Record): string[] { - return Object.entries(rows) - .sort(([, a], [, b]) => compareSmartStamps(a, b)) - .map(([id]) => id) -} - -describe('stamp order', () => { - it('ranks Needs you, unread Done, Working, then Rest, each newest first', () => { - expect( - sortSmart({ - rest: { lastActivityAt: 900 }, - working: { lastActivityAt: 1, smartTier: 'working', smartAt: 50 }, - doneOld: { lastActivityAt: 1, smartTier: 'done', smartAt: 10, isUnread: true }, - doneNew: { lastActivityAt: 1, smartTier: 'done', smartAt: 20, isUnread: true }, - needsYou: { lastActivityAt: 1, smartTier: 'needs-you', smartAt: 5 }, - restOld: { lastActivityAt: 100 } - }) - ).toEqual(['needsYou', 'doneNew', 'doneOld', 'working', 'rest', 'restOld']) - }) - - it('reads a tier it does not know, and missing or broken stamps, as Rest', () => { - // A newer host's tier, parsed off the wire as this client receives it. - const unknownTier: StampOrderRow = JSON.parse( - '{"lastActivityAt":30,"smartTier":"later","smartAt":99}' - ) - expect( - sortSmart({ - unknown: unknownTier, - broken: { lastActivityAt: Number.NaN }, - missing: {}, - recent: { lastActivityAt: 40 } - }) - ).toEqual(['recent', 'unknown', 'broken', 'missing']) - expect(recentStamp({ lastActivityAt: Number.POSITIVE_INFINITY })).toBe(0) - }) - - it('ties within a tier fall to Recent', () => { - expect( - sortSmart({ - older: { lastActivityAt: 1, smartTier: 'done', smartAt: 5, isUnread: true }, - newer: { lastActivityAt: 2, smartTier: 'done', smartAt: 5, isUnread: true } - }) - ).toEqual(['newer', 'older']) - }) - - it('a Done you have seen rests by Recent, below Working (owner decision Q1)', () => { - expect( - sortSmart({ - seen: { lastActivityAt: 30, smartTier: 'done', smartAt: 30, isUnread: false }, - working: { lastActivityAt: 1, smartTier: 'working', smartAt: 1 }, - quiet: { lastActivityAt: 20 }, - // An older row without the flag reads as seen. - noFlag: { lastActivityAt: 10, smartTier: 'done', smartAt: 40 } - }) - ).toEqual(['working', 'seen', 'quiet', 'noFlag']) - }) -})