diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 439fa103ea0..0e5b0379dd2 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -474,7 +474,6 @@ 1 test-no-wall-clock:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx 2 test-no-wall-clock:src/renderer/src/components/artifacts/ArtifactCollection.test.tsx 1 test-no-wall-clock:src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx -2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 05e105f129e..02add88aab4 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -3686,7 +3686,7 @@ "providers": ["local", "daemon", "ssh", "paired-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "paired-runtime"], - "coverageNotes": "Audit5644 integrates source audit5640: retire the whole renderer sync-runtime-graph-payload-partition suite and its active command/testFiles selectors. Intentionally lose failed graph publication acknowledgement/memo retry of changed worktree payloads and unchanged worktree resync self-republication alarms. Remaining main/E2E selectors retain only their own scope; no equivalent replacement, fresh execution, platform or remote evidence is claimed. Complete original selectors are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5594 removes the entire src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts suite and its active selectors. Intentionally lose disposed-frame containment, reload/cancel resume and closed-sender refusal alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\nWindow folder cleanup retires the mock-call-only navigation fence suite and the per-generation warning-count case. Retained sender results and existing rendered checks keep their own original scope; no equivalent replacement or fresh execution is claimed here.", + "coverageNotes": "Audit5736 removes whole runtime/SSH IPC test suites from active selectors, accepting fake-window frame/contract/VM/upload cancellation and fake-transport SSH state/forward ownership alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5644 integrates source audit5640: retire the whole renderer sync-runtime-graph-payload-partition suite and its active command/testFiles selectors. Intentionally lose failed graph publication acknowledgement/memo retry of changed worktree payloads and unchanged worktree resync self-republication alarms. Remaining main/E2E selectors retain only their own scope; no equivalent replacement, fresh execution, platform or remote evidence is claimed. Complete original selectors are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5594 removes the entire src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts suite and its active selectors. Intentionally lose disposed-frame containment, reload/cancel resume and closed-sender refusal alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\nWindow folder cleanup retires the mock-call-only navigation fence suite and the per-generation warning-count case. Retained sender results and existing rendered checks keep their own original scope; no equivalent replacement or fresh execution is claimed here.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/14066", "https://linear.app/stably/issue/STA-4016", @@ -3695,7 +3695,7 @@ "invariant": "Every genuine renderer graph reload revision settles exactly once, while a blocked external navigation that preserves the current document never starts a revision. A cancelled renderer-document navigation restores authority only when that same renderer survived; cancellation after an earlier document committed remains fenced until publication or timeout. Replacing a reload cancels only the prior revision; its timer and callbacks cannot settle a newer revision. A desktop reload succeeds only from a publication carrying a new renderer-document generation, while a failed headless promotion may recover only from its originating window. Timeout, renderer loss, and close reach a terminal graph state, and successful desktop publication permanently retires headless sentinel fallback until a new headless runtime is established.", "oracle": "Audit5644 integrates source audit5640: retire the whole renderer sync-runtime-graph-payload-partition suite and its active command/testFiles selectors. Intentionally lose failed graph publication acknowledgement/memo retry of changed worktree payloads and unchanged worktree resync self-republication alarms. Remaining main/E2E selectors retain only their own scope; no equivalent replacement, fresh execution, platform or remote evidence is claimed. Complete original selectors are preserved in knownGaps. Historical prior account (preserved verbatim): Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/runtime/construction/orca-runtime.test.ts", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -3703,7 +3703,6 @@ ], "testFiles": [ "src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts", - "src/main/ipc/runtime.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts", "tests/e2e/renderer-crash-recovery-terminal-input.spec.ts", @@ -3829,7 +3828,8 @@ "Audit5594 exact prior command before retired suite selector removal: pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", "Audit5644/source5640 intentional loss: renderer failed-publication acknowledgement/memo retry and unchanged worktree-resync republication tests removed wholesale without replacement. Current reduced command has no fresh run; historical receipts preserve original scopes and do not validate changed selectors.", "Audit5644 exact original complete commands before renderer suite selector removal: [\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts\",\"pnpm exec electron-vite build --mode e2e\",\"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"]", - "Audit5644 exact original complete testFiles before renderer suite selector removal: [\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"src/main/ipc/runtime.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts\",\"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\"tests/e2e/headless-serve-desktop-activation.spec.ts\"]" + "Audit5644 exact original complete testFiles before renderer suite selector removal: [\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"src/main/ipc/runtime.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts\",\"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\"tests/e2e/headless-serve-desktop-activation.spec.ts\"]", + "Audit5736 exact original active selector fields before whole IPC suite removal (historical, not current coverage): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm exec electron-vite build --mode e2e\",\"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"],\"testFiles\":[\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"src/main/ipc/runtime.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\"tests/e2e/headless-serve-desktop-activation.spec.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"assertions\":[\"each revision settles exactly once\",\"replacement cancels the old revision and fences its timeout\",\"settlement and timeout release their timers\"]},{\"file\":\"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\"assertions\":[\"blocked external navigation starts and stops loading without replacing the renderer document\",\"runtime graph epoch, readiness, and authoritative window remain unchanged\",\"a later listener can cancel a renderer navigation while its canary and authoritative graph recover\"]},{\"file\":\"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\"assertions\":[\"main observes renderer process loss and a completed recovery load\",\"the same daemon-backed PTY remains reachable through transport and direct-write probes\"]},{\"file\":\"tests/e2e/headless-serve-desktop-activation.spec.ts\",\"assertions\":[\"promotion preserves main owner, runtime, daemon, and PTY identity\",\"terminal output survives promotion and post-promotion input/output remains live\"]}]}" ], "demotionRule": "Demote if a reload revision settles more than once, a stale document or competing window can publish, a timer survives settlement, desktop failure stays indefinitely reloading, headless fallback returns after successful promotion, or either isolated Electron journey loses runtime or PTY identity." }, @@ -9125,7 +9125,7 @@ "providers": ["ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["linux"], "coveredProviders": ["ssh", "remote-runtime"], - "coverageNotes": "Audit5658 integrates source audit5652: retire the whole remote-runtime-pty-recovery-state.test.ts suite and its exact active selectors and assertionRef. Intentionally lose reentrant retry single dispatch; shared owner-refresh caller settlement and per-epoch allowance; deadline registry revival; parked same-epoch retry; actual deadline versus UI disconnected latch alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3554 intentionally removes the whole worktrees-ssh-repo-owner-resolution suite (2 authored cases). Dedicated duplicate-exact/ambiguous-legacy owner refusal and fixed runtime-host/wrong-target/missing-authority/zero-owner/contradictory-owner status alarms are lost. The suite did not exercise an authority transition or actual SSH listing; its no-local-Git spy was also unreachable on an admitted SSH metadata-only route. Remaining suites are not equivalent replacements. Current selectors have no fresh execution from this static packet; historical receipts retain their original scope. No new SSH/provider/native/UI/mobile/mixed-version/cross-platform result is claimed. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands. Audit5043 intentionally deletes the entire remote-runtime-client-error-classification suite (3 authored/9 finite cases): structured-code precedence over contradictory legacy text and7 unstructured-message compatibility alarms are lost. Whole retired-request-ID helper suite (3 cases) also removed outside this selector, losing direct TTL/non-refresh, eviction refresh and backward-clock expiry alarms. No equivalent replacement is claimed. Other selectors and dated evidence retain their original scope; no fresh execution, native/provider/mobile/mixed-version/cross-platform or full-gate result is claimed.", + "coverageNotes": "Audit5736 removes whole runtime/SSH IPC test suites from active selectors, accepting fake-window frame/contract/VM/upload cancellation and fake-transport SSH state/forward ownership alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5658 integrates source audit5652: retire the whole remote-runtime-pty-recovery-state.test.ts suite and its exact active selectors and assertionRef. Intentionally lose reentrant retry single dispatch; shared owner-refresh caller settlement and per-epoch allowance; deadline registry revival; parked same-epoch retry; actual deadline versus UI disconnected latch alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3554 intentionally removes the whole worktrees-ssh-repo-owner-resolution suite (2 authored cases). Dedicated duplicate-exact/ambiguous-legacy owner refusal and fixed runtime-host/wrong-target/missing-authority/zero-owner/contradictory-owner status alarms are lost. The suite did not exercise an authority transition or actual SSH listing; its no-local-Git spy was also unreachable on an admitted SSH metadata-only route. Remaining suites are not equivalent replacements. Current selectors have no fresh execution from this static packet; historical receipts retain their original scope. No new SSH/provider/native/UI/mobile/mixed-version/cross-platform result is claimed. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands. Audit5043 intentionally deletes the entire remote-runtime-client-error-classification suite (3 authored/9 finite cases): structured-code precedence over contradictory legacy text and7 unstructured-message compatibility alarms are lost. Whole retired-request-ID helper suite (3 cases) also removed outside this selector, losing direct TTL/non-refresh, eviction refresh and backward-clock expiry alarms. No equivalent replacement is claimed. Other selectors and dated evidence retain their original scope; no fresh execution, native/provider/mobile/mixed-version/cross-platform or full-gate result is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3107", "https://github.com/stablyai/orca/pull/12664", @@ -9147,7 +9147,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "pnpm run build:web-from-renderer", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -9167,7 +9167,6 @@ "tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts", "src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts", "src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts", - "src/main/ipc/ssh/ssh.test.ts", "src/main/ssh/connection/ssh-connection-manager.test.ts", "src/main/ssh/connection/ssh-connection.test.ts", "src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts", @@ -9361,7 +9360,8 @@ "Audit5658/source5652 intentional loss: reentrant retry single dispatch; shared owner-refresh caller settlement and per-epoch allowance; deadline registry revival; parked same-epoch retry; actual deadline versus UI disconnected latch alarms removed wholesale. No equivalent replacement or fresh validation of reduced selectors; historical receipts preserve exact original scope.", "Audit5658 exact original complete commands: [\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot\",\"pnpm exec electron-vite build --mode e2e\",\"pnpm run build:web-from-renderer\",\"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"]", "Audit5658 exact original complete testFiles: [\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\"src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\"tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts\",\"src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts\",\"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\"src/main/ipc/ssh/ssh.test.ts\",\"src/main/ssh/connection/ssh-connection-manager.test.ts\",\"src/main/ssh/connection/ssh-connection.test.ts\",\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\"src/shared/ssh-retained-payload-admission.test.ts\"]", - "Audit5658 exact original complete assertionRefs: [{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\"assertions\":[\"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"assertions\":[\"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\"assertions\":[\"the automatic-recovery deadline cancels pending backoff and a manual retry owns a new epoch\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\"assertions\":[\"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"]},{\"file\":\"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\"assertions\":[\"one authenticated client/worktree mutation derives a stable server-owned terminal handle\",\"an unknown-outcome retry adopts the same provider PTY after runtime-process restart without rerunning startup\",\"retry inventory failure, missing same-worktree identity metadata, or ownership mismatch fails closed without spawning\",\"in-flight mutation coordination is bounded and releases capacity after settlement\"]},{\"file\":\"src/main/ssh/connection/ssh-connection-manager.test.ts\",\"assertions\":[\"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"]},{\"file\":\"src/main/ssh/connection/ssh-connection.test.ts\",\"assertions\":[\"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"]},{\"file\":\"src/shared/ssh-retained-payload-admission.test.ts\",\"assertions\":[\"retained connection states reject partial or malformed authority\",\"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"]},{\"file\":\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"assertions\":[\"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"]},{\"file\":\"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\"assertions\":[\"held replies from an old generation cannot replace a newer generation; failed full refresh preserves live state behind queued metadata\",\"an unknown target triggers an authoritative list reread\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\"assertions\":[\"abandoning an obsolete reattach drops its data, replay, write-unavailable, and exit handlers without killing the durable PTY\"]}]" + "Audit5658 exact original complete assertionRefs: [{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\"assertions\":[\"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"assertions\":[\"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\"assertions\":[\"the automatic-recovery deadline cancels pending backoff and a manual retry owns a new epoch\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\"assertions\":[\"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"]},{\"file\":\"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\"assertions\":[\"one authenticated client/worktree mutation derives a stable server-owned terminal handle\",\"an unknown-outcome retry adopts the same provider PTY after runtime-process restart without rerunning startup\",\"retry inventory failure, missing same-worktree identity metadata, or ownership mismatch fails closed without spawning\",\"in-flight mutation coordination is bounded and releases capacity after settlement\"]},{\"file\":\"src/main/ssh/connection/ssh-connection-manager.test.ts\",\"assertions\":[\"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"]},{\"file\":\"src/main/ssh/connection/ssh-connection.test.ts\",\"assertions\":[\"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"]},{\"file\":\"src/shared/ssh-retained-payload-admission.test.ts\",\"assertions\":[\"retained connection states reject partial or malformed authority\",\"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"]},{\"file\":\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"assertions\":[\"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"]},{\"file\":\"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\"assertions\":[\"held replies from an old generation cannot replace a newer generation; failed full refresh preserves live state behind queued metadata\",\"an unknown target triggers an authoritative list reread\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\"assertions\":[\"abandoning an obsolete reattach drops its data, replay, write-unavailable, and exit handlers without killing the durable PTY\"]}]", + "Audit5736 exact original active selector fields before whole IPC suite removal (historical, not current coverage): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts --reporter=dot\",\"pnpm exec electron-vite build --mode e2e\",\"pnpm run build:web-from-renderer\",\"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"],\"testFiles\":[\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\"src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\"tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts\",\"src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts\",\"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\"src/main/ipc/ssh/ssh.test.ts\",\"src/main/ssh/connection/ssh-connection-manager.test.ts\",\"src/main/ssh/connection/ssh-connection.test.ts\",\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\"assertions\":[\"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"assertions\":[\"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\"assertions\":[\"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"]},{\"file\":\"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\"assertions\":[\"one authenticated client/worktree mutation derives a stable server-owned terminal handle\",\"an unknown-outcome retry adopts the same provider PTY after runtime-process restart without rerunning startup\",\"retry inventory failure, missing same-worktree identity metadata, or ownership mismatch fails closed without spawning\",\"in-flight mutation coordination is bounded and releases capacity after settlement\"]},{\"file\":\"src/main/ssh/connection/ssh-connection-manager.test.ts\",\"assertions\":[\"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"]},{\"file\":\"src/main/ssh/connection/ssh-connection.test.ts\",\"assertions\":[\"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"]},{\"file\":\"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\",\"assertions\":[\"retained connection states reject partial or malformed authority\",\"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"]},{\"file\":\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"assertions\":[\"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"]},{\"file\":\"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\"assertions\":[\"held replies from an old generation cannot replace a newer generation; failed full refresh preserves live state behind queued metadata\",\"an unknown target triggers an authoritative list reread\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\"assertions\":[\"abandoning an obsolete reattach drops its data, replay, write-unavailable, and exit handlers without killing the durable PTY\"]}]}" ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index ccd8ddd10c4..404552418d1 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -51,7 +51,6 @@ "config/scripts/ci/unit-selection/ci-unit-selection-review.test.mjs": 51, "config/scripts/ci/unit-selection/ci-unit-selection.test.mjs": 271, "config/scripts/ci/sharding/ci-unit-sequencer.test.mjs": 296, - "config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs": 374, "config/scripts/ci/workflow-contracts/cloud-security-history-workflow.test.mjs": 357, "config/scripts/runtime-verification/codex-account/codex-primary-home-tripwire.test.ts": 378, "config/scripts/desktop-build/output-contracts/dark-build-switches.test.mjs": 52, @@ -397,7 +396,6 @@ "src/main/acp/history/acp-history-scaling.test.ts": 24879, "src/main/persistence/preferences/active-view-persistence-boundary.test.ts": 2119, "src/main/persistence/preferences/active-view-preference-sync-flush-veto.test.ts": 781, - "src/main/persistence/preferences/active-view-preference.test.ts": 61, "src/main/providers/accounts/agent-auth-restart-preservation.test.ts": 55, "src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts": 202, "src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts": 403, @@ -1597,7 +1595,6 @@ "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-http-client.test.ts": 496, "src/main/host/electron-manual-redirect-fetch.test.ts": 52, "src/main/host/secret-protection-report.test.ts": 59, "src/main/i18n/main-i18n-lazy-locale.test.ts": 518, @@ -1612,7 +1609,6 @@ "src/main/ipc/ai-vault/ai-vault-scan-coalescing.test.ts": 2230, "src/main/ipc/ai-vault/ai-vault-search-all-hosts-real-index.test.ts": 1852, "src/main/ipc/ai-vault/ai-vault-search-all-hosts.test.ts": 123, - "src/main/ipc/ai-vault/ai-vault-search.test.ts": 1424, "src/main/ipc/ai-vault/ai-vault-unresolved-owner.test.ts": 1436, "src/main/ipc/app.test.ts": 319, "src/main/ipc/automations-external-scope.test.ts": 359, @@ -1625,7 +1621,6 @@ "src/main/ipc/crash-reporting/crash-reporting-replay-guard-wedge-burst.test.ts": 82, "src/main/ipc/created-worktree-root-prune.test.ts": 494, "src/main/ipc/developer-permissions.test.ts": 147, - "src/main/ipc/diagnostics.test.ts": 124, "src/main/ipc/dropped-path-resolution.test.ts": 92, "src/main/ipc/emulator-frame-stream-socket-lifetime.test.ts": 166, "src/main/ipc/emulator-renderer-lifetime.test.ts": 116, @@ -1652,12 +1647,10 @@ "src/main/ipc/filesystem/filesystem-list-files.test.ts": 796, "src/main/ipc/filesystem/filesystem-listing-cancel-admission.test.ts": 157, "src/main/ipc/filesystem/filesystem-mutations.test.ts": 1189, - "src/main/ipc/filesystem/access/filesystem-path-containment-remote-enoent.test.ts": 45, "src/main/ipc/filesystem/access/filesystem-path-containment-unicode-normalization.test.ts": 505, "src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts": 2532, "src/main/ipc/filesystem/filesystem-quick-open-options.integration.test.ts": 1350, "src/main/ipc/filesystem/filesystem-runtime-upload-staging.test.ts": 106, - "src/main/ipc/filesystem/filesystem-search-file-paths.test.ts": 443, "src/main/ipc/filesystem/filesystem-symlink-directory-entries.test.ts": 56, "src/main/ipc/filesystem/filesystem-write-bytes.test.ts": 147, "src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts": 1163, @@ -1762,7 +1755,6 @@ "src/main/ipc/runtime-environments/runtime-environments-repair.test.ts": 4122, "src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts": 5098, "src/main/ipc/runtime-upload-file-stream.test.ts": 144, - "src/main/ipc/runtime.test.ts": 3323, "src/main/ipc/sender-scoped-request-cancellation.test.ts": 80, "src/main/ipc/session-window-view-save.test.ts": 1998, "src/main/ipc/settings-delayed-response.test.ts": 2804, @@ -1774,7 +1766,6 @@ "src/main/ipc/ssh/ssh-credential-cancel.test.ts": 4604, "src/main/ipc/ssh/ssh-host-user-disconnect.test.ts": 4734, "src/main/ipc/ssh/ssh-passphrase.test.ts": 135, - "src/main/ipc/ssh/ssh.test.ts": 6905, "src/main/ipc/terminal-render-desync-evidence.test.ts": 78, "src/main/ipc/terminal-startup-color-query-replies.test.ts": 265, "src/main/workspaces/removal/watcher-removal-gate.test.ts": 384, @@ -1788,7 +1779,6 @@ "src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.test.ts": 57, "src/main/ipc/worktrees/git/worktree-git-common-watch-reconciliation.test.ts": 121, "src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts": 1963, - "src/main/ipc/worktrees/git/worktree-git-status-ref-watch.test.ts": 59, "src/main/ipc/worktrees/creation/worktree-head-identity-reader-incremental.test.ts": 144, "src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts": 74, "src/main/ipc/worktree-logic.test.ts": 323, @@ -1803,7 +1793,6 @@ "src/main/ipc/worktrees-removal-recovery.test.ts": 1971, "src/main/ipc/worktrees-remove-preflight.test.ts": 1415, "src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts": 650, - "src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts": 105, "src/main/ipc/worktrees/listing/detected-worktree-scan-listing-distro.test.ts": 880, "src/main/ipc/worktrees/listing/detected-worktree-scan-superseded.test.ts": 110, "src/main/ipc/wsl-guest-native-program.test.ts": 107, @@ -1884,7 +1873,6 @@ "src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts": 9000, "src/main/managed-server/install/orcad-remote-windows-scripts.test.ts": 3474, "src/main/managed-server/install/remote-install-lock-exited-owner.test.ts": 380, - "src/main/managed-server/install/remote-install-lock-termination.test.ts": 215, "src/main/managed-server/install/remote-install-model.test.ts": 164, "src/main/managed-server/install/remote-install-noisy-sftp-wire.test.ts": 520, "src/main/managed-server/install/remote-node-runtime-store-gc.test.ts": 2254, @@ -1897,7 +1885,6 @@ "src/main/managed-server/lifecycle/orcad-managed-tunnel-peer-restart.test.ts": 494, "src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts": 360, "src/main/managed-server/lifecycle/orcad-managed-update-deferrals.test.ts": 44, - "src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts": 857, "src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.test.ts": 595, "src/main/media/media-preview-protocol.test.ts": 1027, "src/main/media/preview-grant-range-read.test.ts": 691, @@ -1936,7 +1923,6 @@ "src/main/native-chat/agent-session-timeline/provider-timeline-assembler-held-rows.test.ts": 799, "src/main/native-chat/agent-session-timeline/provider-timeline-assembler-refusal.test.ts": 1225, "src/main/native-chat/agent-session-timeline/provider-timeline-assembler-restart.test.ts": 576, - "src/main/native-chat/agent-session-timeline/provider-timeline-assembler-rows.test.ts": 1710, "src/main/native-chat/agent-session-timeline/provider-timeline-assembler-streams.test.ts": 757, "src/main/native-chat/agent-session-timeline/provider-timeline-assembler-turns.test.ts": 809, "src/main/native-chat/agent-session-timeline/provider-timeline-identity.test.ts": 52, @@ -2168,7 +2154,6 @@ "src/main/persistence/profile-state/database/profile-state-write-transaction.test.ts": 94, "src/main/persistence/profile-state/writer/profile-state-writer-worker.test.ts": 1458, "src/main/persistence/restoring-sessions/pane-alias-normalization.test.ts": 847, - "src/main/persistence/restoring-sessions/session-worktree-ownership.test.ts": 490, "src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.test.ts": 348, "src/main/persistence/restoring-sessions/terminal-layout-normalization.test.ts": 73, "src/main/persistence/restoring-sessions/unattached-terminal-row-sweep.test.ts": 347, @@ -2197,7 +2182,6 @@ "src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts": 1766, "src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts": 1941, "src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts": 1626, - "src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts": 544, "src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts": 619, "src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts": 2374, "src/main/persistence/tracking-repos/persistence-duplicate-repo-id-host-scope.test.ts": 2045, @@ -2205,7 +2189,6 @@ "src/main/persistence/tracking-repos/persistence-folder-workspace-notes.test.ts": 2124, "src/main/persistence/tracking-repos/persistence-invalid-workspace-layout-purge.test.ts": 2151, "src/main/persistence/tracking-repos/persistence-update-repo.test.ts": 2213, - "src/main/persistence/tracking-repos/persistence-workspace-attachments.test.ts": 2030, "src/main/persistence/tracking-repos/persistence-workspace-pinned-automation-fence.test.ts": 2412, "src/main/persistence/tracking-repos/persistence-workspace-repin-automation-owner.test.ts": 2205, "src/main/persistence/tracking-repos/persistence-workspace-session-scrollback.test.ts": 1952, @@ -2219,7 +2202,6 @@ "src/main/persistence/tracking-repos/project-group-session-batch.test.ts": 496, "src/main/persistence/tracking-repos/repo-update-host-guard.test.ts": 478, "src/main/persistence/tracking-repos/worktree-identity-migration-field-coverage.test.ts": 505, - "src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts": 372, "src/main/persistence/window-save-sleep-records.test.ts": 60, "src/main/pi/managed-extensions/agent-status/agent-status-extension-nested-run-settlement.test.ts": 335, "src/main/pi/managed-extensions/agent-status/agent-status-extension-session-change.test.ts": 613, @@ -2233,7 +2215,6 @@ "src/main/plugins/catalog/plugin-catalog-monorepo-images.test.ts": 216, "src/main/plugins/catalog/plugin-install-stats-service.test.ts": 196, "src/main/plugins/catalog/plugin-kill-list-content-revocation.test.ts": 3680, - "src/main/plugins/catalog/plugin-kill-list-service.test.ts": 289, "src/main/plugins/catalog/plugin-marketplace-installer.test.ts": 859, "src/main/plugins/catalog/plugin-marketplace-store.test.ts": 250, "src/main/plugins/catalog/plugin-private-marketplace.integration.test.ts": 978, @@ -2288,7 +2269,6 @@ "src/main/plugins/plugin-vm-recipe-registry.test.ts": 349, "src/main/plugins/view/plugin-view-editor-shot.test.ts": 194, "src/main/plugins/view/plugin-view-replay-shot.test.ts": 256, - "src/main/plugins/view/plugin-view-target.test.ts": 143, "src/main/plugins/workers/plugin-host-panel-methods.test.ts": 304, "src/main/plugins/workers/plugin-host-runtime.test.ts": 274, "src/main/plugins/workers/plugin-worker-controller.test.ts": 394, @@ -3585,7 +3565,6 @@ "src/renderer/src/components/agent-tab-shortcut-launch.test.ts": 369, "src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx": 2090, "src/renderer/src/components/artifacts/ArtifactCollection.test.tsx": 1833, - "src/renderer/src/components/artifacts/ArtifactPreview.test.tsx": 474, "src/renderer/src/components/artifacts/ArtifactPublishButton.test.tsx": 706, "src/renderer/src/components/artifacts/ArtifactsPage.test.tsx": 2052, "src/renderer/src/components/artifacts/artifact-publish-flow.test.ts": 114, @@ -3884,7 +3863,6 @@ "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.host-outage.test.tsx": 3552, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx": 3014, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx": 4459, - "src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx": 583, "src/renderer/src/components/native-chat/tools/lines/NativeChatToolLine.test.tsx": 3544, "src/renderer/src/components/native-chat/tools/lines/NativeChatToolOutput.test.tsx": 410, "src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.identity.test.tsx": 3269, @@ -3916,7 +3894,6 @@ "src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx": 951, "src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts": 1937, "src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts": 895, - "src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts": 49, "src/renderer/src/components/native-chat/attachments/chips/native-chat-image-references.test.tsx": 2485, "src/renderer/src/components/native-chat/session/terminal/assembly/native-chat-live-message-preparation.test.ts": 252, "src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.test.ts": 207, @@ -3950,7 +3927,6 @@ "src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.test.tsx": 2467, "src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-preview-lifetime.test.tsx": 1926, "src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx": 797, - "src/renderer/src/components/native-chat/session/status/use-native-chat-hook-status.test.ts": 1927, "src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.test.tsx": 2131, "src/renderer/src/components/native-chat/drafts/use-native-chat-launch-draft-adoption.test.tsx": 319, "src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-pending.test.ts": 2063, @@ -3962,7 +3938,6 @@ "src/renderer/src/components/native-chat/session/terminal/delivery/use-native-chat-pending-delivery.test.tsx": 457, "src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.test.tsx": 315, "src/renderer/src/components/native-chat/use-native-chat-rail-history-jump.test.ts": 572, - "src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-retained-session.test.ts": 229, "src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx": 686, "src/renderer/src/components/native-chat/session/terminal/send/use-native-chat-send-lifecycle.test.tsx": 281, "src/renderer/src/components/native-chat/session/options/terminal/use-native-chat-session-options.test.ts": 1068, @@ -4003,7 +3978,6 @@ "src/renderer/src/components/quick-open-file-list.test.ts": 54, "src/renderer/src/components/quick-open-recent-validation.test.ts": 213, "src/renderer/src/components/render-phase-adjustment-discarded-render.test.tsx": 2577, - "src/renderer/src/components/right-sidebar/ai-vault/scanning/AiVaultScanProgressStrip.test.tsx": 893, "src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionHistoryDialog.test.tsx": 2796, "src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionVirtualList.measurement.test.tsx": 3117, "src/renderer/src/components/right-sidebar/FolderWorkspaceWorktreesPanel.test.tsx": 461, @@ -4011,7 +3985,6 @@ "src/renderer/src/components/right-sidebar/PortsPanel.test.tsx": 1618, "src/renderer/src/components/right-sidebar/source-control/ai/SourceControlAgentActionDialog.test.tsx": 2772, "src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-account-native.test.tsx": 2785, - "src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-account-peer.test.tsx": 2516, "src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane.test.ts": 64, "src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-panel-session-list-request.test.tsx": 3044, "src/renderer/src/components/right-sidebar/ai-vault/session-list/ai-vault-session-filters.test.ts": 105, @@ -4022,7 +3995,6 @@ "src/renderer/src/components/right-sidebar/checks-panel/checks-list-expanded-details.test.tsx": 1549, "src/renderer/src/components/right-sidebar/checks-panel/comments/review-comment-markdown.test.tsx": 2171, "src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx": 2023, - "src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts": 1767, "src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-expanded-dirs-refresh.test.ts": 1962, "src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-inline-input-ime-enter.test.tsx": 479, "src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-recovery.test.tsx": 2158, @@ -4041,14 +4013,12 @@ "src/renderer/src/components/right-sidebar/source-control/review/create-pr-intent-operation-target.test.ts": 1735, "src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx": 688, "src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-terminal-worktree.test.ts": 2116, - "src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-jira-review-title.test.tsx": 1979, "src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-git-history.test.tsx": 1951, "src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.save-refusal.test.tsx": 840, "src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.trash-failure.test.tsx": 774, "src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileExplorerImport.committed-scope.test.tsx": 588, "src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerTree.stale-dirs.test.tsx": 1958, "src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.lifecycle.test.tsx": 2249, - "src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx": 742, "src/renderer/src/components/right-sidebar/source-control/listing/useSourceControlSubmoduleStatus.test.tsx": 2076, "src/renderer/src/components/settings/accounts/AccountsPane.owner-scope.test.tsx": 4057, "src/renderer/src/components/settings/agents/AgentsPane.test.tsx": 3230, @@ -4092,7 +4062,6 @@ "src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477, "src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880, "src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts": 1925, - "src/renderer/src/components/shared/useDaemonActions.test.tsx": 332, "src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostDialog.config-picker.test.tsx": 1178, "src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx": 714, "src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx": 2254, @@ -4110,7 +4079,6 @@ "src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.single-reference-details.test.tsx": 2032, "src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenu.closed-menu-work.test.tsx": 1753, "src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx": 5388, - "src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.host-scope.test.tsx": 2215, "src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.test.tsx": 7694, "src/renderer/src/components/sidebar/workspace-visibility/dialog/WorktreeVisibilityDialog.test.tsx": 2602, "src/renderer/src/components/sidebar/chat-markdown-math-typeset.test.ts": 1336, @@ -4267,7 +4235,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-startup-snapshot.test.ts": 1830, "src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-wsl-distro-stopped-hold.test.ts": 2517, "src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts": 92, - "src/renderer/src/components/terminal-pane/pty-connection/spawn/hidden-agent-resume-deferral.test.ts": 55, "src/renderer/src/components/terminal-pane/pty-connection/startup/main-pane-resume-banner.test.ts": 59, "src/renderer/src/components/terminal-pane/pty-connection/spawn/main-pane-start-wait.test.ts": 76, "src/renderer/src/components/terminal-pane/pty-connection/serialization/pane-serializer-register.test.ts": 123, @@ -4538,8 +4505,6 @@ "src/shared/agent-status/contracts/agent-status-evidence-clock.test.ts": 88, "src/shared/agent-status/title/agent-title-tracker.test.ts": 172, "src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts": 678, - "src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts": 541, - "src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-target.test.ts": 92, "src/renderer/src/lib/agent-session/resume/history/ai-vault-session-drag.test.ts": 68, "src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.test.ts": 408, "src/renderer/src/lib/agent-session/history/title-sync/ai-vault-tab-title-sync-inputs.test.ts": 476, @@ -4620,7 +4585,6 @@ "src/renderer/src/lib/workspace/search/tabs/workspace-tab-palette-activation.store.test.ts": 1994, "src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts": 2066, "src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts": 2295, - "src/renderer/src/lib/workspace/activation/worktree-activation-launch-awaiting-host.test.ts": 2161, "src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts": 2043, "src/renderer/src/lib/workspace/activation/worktree-activation-web-runtime.test.ts": 2768, "src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts": 5258, @@ -4674,7 +4638,6 @@ "src/renderer/src/runtime/browser/creation/web-runtime-browser-link-open.test.ts": 2217, "src/renderer/src/runtime/web-session-tabs-sync/tracking/web-session-tabs-removed-frame-retires-live-publisher.test.ts": 854, "src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-stream-end-resubscribe.test.tsx": 2282, - "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-ownership.test.ts": 1902, "src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts": 892, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-sync-host-tab-retraction-ghost-rows.test.ts": 1956, "src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-mirrored-draft-close.test.ts": 1833, @@ -4722,7 +4685,6 @@ "src/renderer/src/store/slices/browser/cleanup/browser-mount-admission-removal.test.ts": 1982, "src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts": 1777, "src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts": 988, - "src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts": 792, "src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts": 1886, "src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts": 2007, "src/renderer/src/store/slices/browser/browser.test.ts": 2001, @@ -4740,7 +4702,6 @@ "src/renderer/src/store/slices/editor/markdown/editor-markdown-link-activation.test.ts": 953, "src/renderer/src/store/slices/editor/tabs/editor-preview-tab-setting.test.ts": 1952, "src/renderer/src/store/slices/editor/opening/editor-read-only-tabs.test.ts": 901, - "src/renderer/src/store/slices/editor/closing/editor-recently-closed-tabs.test.ts": 1948, "src/renderer/src/store/slices/editor/focus/editor-set-active-file-guard.test.ts": 895, "src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-identity.test.ts": 1775, "src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-joins.test.ts": 1766, @@ -4816,7 +4777,6 @@ "src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-stale-catalog-version.test.ts": 1337, "src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-branch-title.test.ts": 1181, "src/renderer/src/store/slices/worktrees/listing/worktrees-hydration-purge.test.ts": 1274, - "src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts": 1132, "src/renderer/src/store/slices/worktrees/listing/worktrees-runtime-connection-generation-fence.test.ts": 1240, "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-reference-source-race.test.ts": 1063, "src/renderer/src/store/slices/worktrees/host-scoped-row-merges.test.ts": 1805, @@ -4872,7 +4832,6 @@ "src/shared/agent-session/options/agent-cli-flag-detection.test.ts": 56, "src/shared/agent-cli-install-dir-fallback.test.ts": 130, "src/shared/agent-launch/startup/agent-command-line-intent.test.ts": 95, - "src/shared/agent-status/title/agent-detection.test.ts": 188, "src/shared/agent-hook-listener/transport/agent-hook-endpoint-temp-cleanup.test.ts": 55, "src/shared/agent-hook-listener/normalization/agent-hook-listener-claude-elicitation.test.ts": 229, "src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-approval-ownership.test.ts": 258, diff --git a/config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs b/config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs deleted file mode 100644 index 73af9b0753f..00000000000 --- a/config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs +++ /dev/null @@ -1,61 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import UnitTimingReporter from './ci-unit-timing-reporter.mjs' - -const phaseDiagnostic = (overrides = {}) => ({ - environmentSetupDuration: 1.5, - prepareDuration: 2.5, - collectDuration: 30.25, - setupDuration: 4.5, - duration: 5.25, - workerId: 7, - concurrencyId: 2, - importDurations: {}, - ...overrides -}) -const phaseModule = (file, diagnostic = phaseDiagnostic(), project = 'bun') => ({ - moduleId: resolve(file), - project: { name: project }, - state: () => 'passed', - diagnostic: () => diagnostic -}) -const phaseContext = (state) => ({ - config: { root: process.cwd(), shard: { index: 1, count: 5 } }, - version: '5.0.3', - state -}) - -function withReporterOutputs(run) { - const directory = mkdtempSync(join(tmpdir(), 'orca-unit-phases-')) - const timingPath = join(directory, 'unit-timings.json') - const phasePath = join(directory, 'unit-phase-diagnostics.json') - vi.stubEnv('ORCA_UNIT_TIMING_REPORT', timingPath) - vi.stubEnv('ORCA_UNIT_PHASE_REPORT', undefined) - vi.stubEnv('ORCA_UNIT_SELECTION_PLAN', join(directory, 'missing-selection.json')) - vi.stubEnv('ORCA_SHARD_SOURCE_SHA', 'phase-source') - vi.stubEnv('GITHUB_RUN_ID', 'phase-run') - vi.stubEnv('GITHUB_RUN_ATTEMPT', '3') - try { - run({ timingPath, phasePath }) - } finally { - vi.unstubAllEnvs() - rmSync(directory, { recursive: true, force: true }) - } -} - -describe('optional unit phase diagnostics', () => { - it('preserves timing evidence when optional output targets the timing file', () => { - withReporterOutputs(({ timingPath }) => { - const reporter = new UnitTimingReporter() - reporter.onInit(phaseContext()) - const modules = [phaseModule('src/example.test.ts')] - reporter.onTestRunEnd(modules, [], 'passed') - const timing = readFileSync(timingPath, 'utf8') - vi.stubEnv('ORCA_UNIT_PHASE_REPORT', timingPath) - expect(() => reporter.onTestRunEnd(modules, [], 'passed')).not.toThrow() - expect(readFileSync(timingPath, 'utf8')).toBe(timing) - }) - }) -}) 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 b77219d1d25..eb9221657a8 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 @@ -19,7 +19,6 @@ const NODE_RUNTIME_INCLUDE = [ // The forced-probe handoff race opens only under V8's promise scheduling, which Electron main uses. 'src/main/github/api/rate-limit.test.ts', // Electron main bridges streams with Node's implementation. - 'src/main/host/electron-http-client.test.ts', 'src/main/browser/extensions/native-messaging/browser-extension-native-host-process-backpressure.test.ts', 'src/main/daemon/providers/lifecycle/testing/daemon-init-provider-installation.test.ts', 'src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts', diff --git a/mobile/src/storage/mirrored-storage-write.test.ts b/mobile/src/storage/mirrored-storage-write.test.ts deleted file mode 100644 index 8f380afa77a..00000000000 --- a/mobile/src/storage/mirrored-storage-write.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// Use the real page adapter: its resolved refusals must not put rejected values into the next shell init’s mirror. -vi.mock('@react-native-async-storage/async-storage', async () => ({ - default: (await import('../mobile-web-shell/bridge/page-storage/page-async-storage')).default -})) - -const { publishPageStorage } = - await import('../mobile-web-shell/bridge/page-storage/page-async-storage') -const { pageStorageKeysForRoute } = - await import('../mobile-web-shell/page-storage/page-storage-keys') -const { persistMirrored, readMirroredStorage, retainMirroredStorage } = - await import('./mirrored-storage-keys') - -const HOST_ID = 'host-1' -const ROUTE = '/h/host-1/session/wt-1' -const DOCK_WIDTH = 'orca:hostDockWidth' -const OTHER_HOST_PIN = 'orca:pins:host-2' -let releaseStorage = () => {} - -afterEach(() => releaseStorage()) - -beforeEach(() => { - releaseStorage = retainMirroredStorage(pageStorageKeysForRoute(HOST_ID, ROUTE)) - publishPageStorage({ [DOCK_WIDTH]: '320' }, () => true, HOST_ID, ROUTE) - return persistMirrored(DOCK_WIDTH, '320') -}) - -describe('the mirrored write path', () => { - it('leaves them alone for a key this route was never given, and logs the drop', async () => { - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - // Unlisted-key writes resolve because page callers may await them without a catch. - await expect(persistMirrored(OTHER_HOST_PIN, '["a"]')).resolves.toBeUndefined() - expect(readMirroredStorage([OTHER_HOST_PIN])[OTHER_HOST_PIN]).toBeUndefined() - expect(warned).toHaveBeenCalledWith( - '[page-bridge] storage-write-dropped', - expect.objectContaining({ key: OTHER_HOST_PIN, refusal: 'not-allowed' }) - ) - warned.mockRestore() - }) -}) diff --git a/mobile/src/worktree/catalog/use-retired-worktree-names.test.tsx b/mobile/src/worktree/catalog/use-retired-worktree-names.test.tsx deleted file mode 100644 index 448e503aa8b..00000000000 --- a/mobile/src/worktree/catalog/use-retired-worktree-names.test.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import { createElement } from 'react' -import { act, create } from 'react-test-renderer' -import { describe, expect, it } from 'vitest' -import type { RpcClient } from '../../transport/rpc/rpc-client-contract' -import { - EMPTY_RETIRED_NAME_REGISTRY, - type RetiredNameRegistry -} from '../../../../src/shared/worktree/naming/retired-name-registry' -import { useRetiredWorktreeNames } from './use-retired-worktree-names' - -type Pending = { resolve: (response: unknown) => void } - -// Defer RPC replies to control both their repo and arrival order. -function mountNames() { - const pending: Pending[] = [] - let latest: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY - - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The hook only calls this fixture's deferred sendRequest method. - const client = { - sendRequest: () => new Promise((resolve) => pending.push({ resolve })) - } as unknown as RpcClient - - function Probe({ repoId, refreshKey }: { repoId: string | null; refreshKey: string }) { - latest = useRetiredWorktreeNames(client, repoId, refreshKey) - return null - } - - let renderer!: ReturnType - act(() => { - renderer = create(createElement(Probe, { repoId: 'repo-1', refreshKey: 'a' })) - }) - return { - get names(): readonly string[] { - return latest.names - }, - rerender(props: { repoId: string | null; refreshKey: string }) { - act(() => { - renderer.update(createElement(Probe, props)) - }) - }, - async settle( - index: number, - retiredNamesByRepo: Record, - retiredNameTiersByRepo: Record = {} - ) { - await act(async () => { - // Include the real host’s ok field so acceptance exercises success rather than refusal. - pending[index]!.resolve({ - ok: true, - result: { retiredNamesByRepo, retiredNameTiersByRepo } - }) - await Promise.resolve() - }) - } - } -} - -describe('useRetiredWorktreeNames', () => { - it('drops names when the repo changes rather than showing another repo pool', async () => { - const probe = mountNames() - await probe.settle(0, { 'repo-1': ['nautilus'] }) - - probe.rerender({ repoId: 'repo-1', refreshKey: 'b' }) - probe.rerender({ repoId: 'repo-2', refreshKey: 'a' }) - expect(probe.names).toEqual([]) - await probe.settle(2, { 'repo-2': ['seahorse'] }) - await probe.settle(1, { 'repo-1': ['nautilus', 'marlin'] }) - expect(probe.names).toEqual(['seahorse']) - }) -}) diff --git a/src/main/github/pr-watch/pr-chat-action-recorder.test.ts b/src/main/github/pr-watch/pr-chat-action-recorder.test.ts deleted file mode 100644 index f01912a30d8..00000000000 --- a/src/main/github/pr-watch/pr-chat-action-recorder.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentJournalToolCallItem } from '../../../shared/agent-session/journal/agent-session-journal-types' -import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types' -import { - finishedShellCall, - pushedPullRequestHead, - pushUpdatesByCall -} from './pr-chat-action-recorder' -import { prInfoFixture } from './pr-watch-test-fixtures' - -type ToolCallRow = { itemId: string; revision: number; body: AgentJournalToolCallItem } - -function toolCallRow( - call: Omit & { output: string } -): ToolCallRow { - const head = call.output - return { - itemId: 'claude:session:toolu_01', - revision: 2, - body: { - ...call, - kind: 'tool-call', - state: 'completed', - output: { head, byteLength: head.length, digest: 'd', truncated: false } - } - } -} - -function pushedBranches(row: ToolCallRow): unknown[] { - const call = finishedShellCall('chat-1', row, 0) - return (call ? pushUpdatesByCall(call) : []).map(({ branch, newSha }) => ({ branch, newSha })) -} - -const TO_ORIGIN = 'To github.com:acme/repo.git\n' -const REVIEW_PUSHED = - "To github.com:acme/repo.git\n 8d5f74b..c512e75 HEAD -> review\nbranch 'review' set up to track 'origin/review'.\n" -const REVIEW_UPDATE = { branch: 'review', newSha: 'c512e75' } - -function pushBy(command: string, output: string): unknown[] { - return pushedBranches(toolCallRow({ name: 'Bash', input: { command }, output })) -} - -describe('push updates from recorded tool calls', () => { - it("reads Claude's Bash push and Codex's shell push", () => { - // Claude's Bash tool: git writes its update lines to stderr, which the tool merges. - const claude = toolCallRow({ - name: 'Bash', - input: { command: 'git push -u origin HEAD', description: 'Push the branch' }, - output: - "To github.com:stablyai/orca.git\n 8d5f74b..c512e75 HEAD -> brennanb2025/ci-lines\nbranch 'brennanb2025/ci-lines' set up to track 'origin/brennanb2025/ci-lines'." - }) - // Codex app-server: one string through a login shell, with its cwd and exit code. - const codex = toolCallRow({ - name: 'shell', - input: { - command: "/bin/zsh -lc 'git add -A && git commit -m wip && git push --force-with-lease'", - cwd: '/Users/me/orca/workspaces/orca/ci-lines' - }, - exitCode: 0, - output: - '[ci-lines 5d6e7f8] wip\n 1 file changed, 2 insertions(+)\nTo github.com:stablyai/orca.git\n + 1a2b3c4...5d6e7f8 ci-lines -> ci-lines (forced update)\n' - }) - expect(pushedBranches(claude)).toEqual([{ branch: 'brennanb2025/ci-lines', newSha: 'c512e75' }]) - expect(pushedBranches(codex)).toEqual([{ branch: 'ci-lines', newSha: '5d6e7f8' }]) - }) - - it("reads a push after a heredoc's declaration, past `;`", () => { - const command = "cat <<'EOF' > notes.md; git push -u origin HEAD 2>&1\nnotes\nEOF" - expect(pushBy(command, REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) - }) - - it('takes nothing from a heredoc that prints a push and its update lines', () => { - const printed = - 'git push -u origin HEAD 2>&1\nTo github.com:acme/repo.git\n 1234567..89abcde HEAD -> review\n' - for (const opener of ["<<'EOF'", '<` before a real pipe hide the push after it", () => { - expect(pushBy('printf x \\>|git push origin HEAD', REVIEW_PUSHED)).toEqual([REVIEW_UPDATE]) - }) -}) - -describe('pushedPullRequestHead', () => { - const updateOf = (output: string) => - pushUpdatesByCall({ - chatId: 'chat-1', - anchor: { itemId: 'item', revision: 1 }, - script: 'git push', - output, - finishedAt: 0 - })[0]! - // The remote as resolved through the checkout's config; here, what the `To` line parsed to. - const match = (output: string, pr: PRInfo) => { - const update = updateOf(output) - return pushedPullRequestHead(update, update.remote, pr) - } - const pr = (fields: Partial): PRInfo => - prInfoFixture({ - number: 20, - headRefName: 'review', - headSha: '89abcde0123', - headRepo: { owner: 'acme', repo: 'repo' }, - ...fields - }) - - it('binds a push to the branch, repository and forge host its own update line names', () => { - // `git push origin work:review` updated review, not the checked-out branch. - const workToReview = `${TO_ORIGIN} 1234567..89abcde work -> review\n` - expect(match(workToReview, pr({}))).toEqual({ headSha: '89abcde0123', superseded: false }) - // A new branch in another repository is not this fork PR's head. - expect( - match('To github.com:parent/repo.git\n * [new branch] HEAD -> review\n', pr({})) - ).toBeNull() - // The same commit pushed to the same owner/repo on another forge host is another repository. - expect( - match( - 'To https://github.enterprise.example/acme/repo.git\n 1234567..89abcde work -> review\n', - pr({}) - ) - ).toBeNull() - // Another push moved the PR on before the read: the proven head is kept, marked superseded. - expect(match(workToReview, pr({ headSha: 'ffff0000aaaa' }))).toEqual({ - headSha: '89abcde', - superseded: true - }) - }) -}) diff --git a/src/main/host/electron-http-client.test.ts b/src/main/host/electron-http-client.test.ts deleted file mode 100644 index 8e999b2fcdd..00000000000 --- a/src/main/host/electron-http-client.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { Readable, Writable } from 'node:stream' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -type LoginCallback = (username?: string, password?: string) => void -type ProxyChallenge = { isProxy: boolean; host: string; port: number } - -class FakeClientRequest extends Writable { - readonly body: Buffer[] = [] - readonly headers = new Map() - readonly abort = vi.fn() - ended = false - - override _write(chunk: Buffer, _encoding: BufferEncoding, callback: () => void): void { - this.body.push(chunk) - callback() - } - - override _final(callback: () => void): void { - this.ended = true - callback() - } - - setHeader(key: string, value: string): void { - this.headers.set(key, value) - } - - challenge(authInfo: ProxyChallenge): LoginCallback { - const callback = vi.fn() - this.emit('login', authInfo, callback) - return callback - } - - respond(status: number, text: string | null): Readable { - // null leaves the body stalled after headers. - const stream = text === null ? new Readable({ read() {} }) : Readable.from([Buffer.from(text)]) - const response = Object.assign(stream, { - statusCode: status, - statusMessage: 'OK', - headers: { 'content-type': 'text/plain', 'set-cookie': ['a=1', 'b=2'] } - }) - this.emit('response', response) - return response - } -} - -const mocks = vi.hoisted(() => ({ - defaultSession: { - resolveProxy: async (): Promise => 'DIRECT', - setProxy: async (): Promise => {} - }, - netFetch: vi.fn(), - netRequest: vi.fn(), - readiness: vi.fn<() => boolean | Promise>(() => true) -})) - -vi.mock('electron', () => ({ - net: { fetch: mocks.netFetch, request: mocks.netRequest }, - session: { defaultSession: mocks.defaultSession } -})) - -vi.mock('../network/proxy-settings', () => ({ - getProxySessionApplicationReadiness: mocks.readiness -})) - -import { - resetElectronProxyCredentialsForTests, - setElectronProxyCredentialsForSession -} from '../network/electron-proxy-credentials' -import { electronHttpClient } from './electron-http-client' - -const PROXY = { host: 'proxy.corp', port: 8080, username: 'user', password: 'secret' } -let native: FakeClientRequest - -// Wrapped so awaiting the request start does not also await its response. -async function startRequest(init?: RequestInit): Promise<{ pending: Promise }> { - const pending = electronHttpClient.fetch('https://api.example.com/v1', init) - await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalled()) - return { pending } -} - -beforeEach(() => { - native = new FakeClientRequest() - mocks.netRequest.mockReturnValue(native) - mocks.netFetch.mockResolvedValue(new Response('direct')) - mocks.readiness.mockReturnValue(true) -}) - -afterEach(() => { - vi.clearAllMocks() - resetElectronProxyCredentialsForTests() -}) - -describe('electronHttpClient proxy authentication', () => { - it('answers the configured proxy challenge on a cold request', async () => { - setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY) - const { pending } = await startRequest({ method: 'POST', body: 'payload', headers: { a: 'b' } }) - - const login = native.challenge({ isProxy: true, host: 'PROXY.corp', port: 8080 }) - await vi.waitFor(() => expect(native.ended).toBe(true)) - native.respond(200, 'ok') - const response = await pending - - expect(login).toHaveBeenCalledWith('user', 'secret') - expect(mocks.netRequest).toHaveBeenCalledWith( - expect.objectContaining({ session: mocks.defaultSession, method: 'POST' }) - ) - expect(native.headers.get('a')).toBe('b') - expect(Buffer.concat(native.body).toString()).toBe('payload') - expect(response.headers.get('set-cookie')).toBe('a=1, b=2') - expect(await response.text()).toBe('ok') - expect(mocks.netFetch).not.toHaveBeenCalled() - }) - - it('cancels unrelated, origin, and repeated challenges', async () => { - setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY) - await startRequest() - - expect(native.challenge({ isProxy: true, host: 'other', port: 8080 })).toHaveBeenCalledWith() - - native = new FakeClientRequest() - mocks.netRequest.mockReturnValue(native) - void electronHttpClient.fetch('https://api.example.com/v1') - await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalledTimes(2)) - expect( - native.challenge({ isProxy: false, host: 'proxy.corp', port: 8080 }) - ).toHaveBeenCalledWith() - - native = new FakeClientRequest() - mocks.netRequest.mockReturnValue(native) - void electronHttpClient.fetch('https://api.example.com/v1') - await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalledTimes(3)) - const challenge = { isProxy: true, host: 'proxy.corp', port: 8080 } - expect(native.challenge(challenge)).toHaveBeenCalledWith('user', 'secret') - expect(native.challenge(challenge)).toHaveBeenCalledWith() - }) - - it('waits for a pending proxy policy to install its credentials', async () => { - let settle: (ready: boolean) => void = () => {} - mocks.readiness.mockReturnValue(new Promise((resolve) => (settle = resolve))) - const pending = electronHttpClient.fetch('https://api.example.com/v1') - - setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY) - settle(true) - await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalled()) - native.respond(204, '') - - expect((await pending).body).toBeNull() - expect(mocks.netFetch).not.toHaveBeenCalled() - }) - - it('rejects with the caller abort reason and aborts the native request', async () => { - setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY) - const controller = new AbortController() - const { pending } = await startRequest({ signal: controller.signal }) - - const reason = new Error('stop') - controller.abort(reason) - - await expect(pending).rejects.toBe(reason) - expect(native.abort).toHaveBeenCalled() - }) - - it('cancels a stalled response body without waiting for more data', async () => { - setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY) - const { pending } = await startRequest() - const stalled = native.respond(503, null) - const response = await pending - - await response.body?.cancel() - - expect(stalled.destroyed).toBe(true) - }) -}) diff --git a/src/main/ipc/ai-vault/ai-vault-search.test.ts b/src/main/ipc/ai-vault/ai-vault-search.test.ts deleted file mode 100644 index f03341e43cf..00000000000 --- a/src/main/ipc/ai-vault/ai-vault-search.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { clearSearch, handlers, sshSearch, sshHostInfos, runtimeSearch } = vi.hoisted(() => ({ - clearSearch: vi.fn(), - handlers: new Map Promise>(), - sshSearch: vi.fn(), - sshHostInfos: vi.fn<() => { targetId: string }[]>(() => []), - runtimeSearch: vi.fn() -})) -vi.mock('../../ai-vault/scan-service/session-scanner-service-spawn', () => ({ - clearSessionSearchInService: clearSearch -})) -vi.mock('electron', () => ({ - ipcMain: { - handle: (name: string, handler: (...args: unknown[]) => Promise) => - handlers.set(name, handler) - }, - ipcRenderer: { invoke: (name: string, ...args: unknown[]) => handlers.get(name)!(null, ...args) } -})) -vi.mock('../ssh/ssh', () => ({ - requestActiveSshSessionSearch: sshSearch, - getActiveSshAiVaultHostInfos: sshHostInfos -})) - -import { createChildSessionSearchService } from '../../ai-vault-search/session-search-child-service' -import { registerAiVaultSearchHandlers } from './ai-vault-search' -import { aiVaultApi } from '../../../preload/api/ai-vault/ai-vault-bridge' -import { setSessionSearchService } from '../../ai-vault-search/session-search-service-registry' -import { fakeSearchService } from '../../../shared/ai-vault/search/ai-vault-search-test-fixture' -import { setStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -beforeEach(() => { - handlers.clear() - sshSearch.mockReset() - sshHostInfos.mockReset() - sshHostInfos.mockReturnValue([]) - runtimeSearch.mockReset() - clearSearch.mockReset() - registerAiVaultSearchHandlers({ - callRuntimeSearch: runtimeSearch - }) -}) -afterEach(() => { - setSessionSearchService(null) - setStructuredAgentSessionHost(null) -}) - -describe('desktop IPC and preload search boundary', () => { - it('maps a runtime unknown-method refusal to unavailable and keeps transport errors', async () => { - runtimeSearch.mockRejectedValue( - Object.assign(new Error('unknown method'), { code: 'method_not_found' }) - ) - expect(await aiVaultApi.searchSessions({ query: 'needle' }, 'runtime:env-1')).toEqual({ - kind: 'unavailable', - reason: 'no-service' - }) - // Status is the one read where "no such method" must not collapse into "off". - await expect(aiVaultApi.searchStatus('runtime:env-1')).rejects.toThrow('host-too-old') - runtimeSearch.mockRejectedValue( - Object.assign(new Error('runtime disconnected'), { code: 'connection_lost' }) - ) - await expect(aiVaultApi.searchSessions({ query: 'needle' }, 'runtime:env-1')).rejects.toThrow( - 'runtime disconnected' - ) - }) - - it('refuses an unroutable host instead of widening it to every host', async () => { - const local = fakeSearchService() - setSessionSearchService(local) - for (const scope of ['nope', 'ssh:', 'runtime:a|b']) { - await expect( - handlers.get('aiVault:searchSessions')!(null, { query: 'needle' }, scope) - ).rejects.toThrow('not available for this execution host') - await expect(handlers.get('aiVault:searchStatus')!(null, scope)).rejects.toThrow( - 'not available for this execution host' - ) - } - expect(local.search).not.toHaveBeenCalled() - expect(local.status).not.toHaveBeenCalled() - expect(sshSearch).not.toHaveBeenCalled() - expect(runtimeSearch).not.toHaveBeenCalled() - }) - - it('maps an unknown-method refusal to host-too-old and keeps every other failure', async () => { - runtimeSearch.mockRejectedValue( - Object.assign(new Error('Unknown method: aiVault.setSearchEnabled'), { code: -32601 }) - ) - await expect(aiVaultApi.setSearchEnabled('runtime:env-1', true)).rejects.toThrow('host-too-old') - - runtimeSearch.mockRejectedValue(Object.assign(new Error('not paired'), { code: 'forbidden' })) - await expect(aiVaultApi.setSearchEnabled('runtime:env-1', true)).rejects.toThrow('not paired') - }) - - it('refuses local, SSH, unroutable hosts and a non-boolean', async () => { - await expect(aiVaultApi.setSearchEnabled('local', true)).rejects.toThrow('through Settings') - await expect(aiVaultApi.setSearchEnabled('ssh:box', true)).rejects.toThrow('unsupported') - await expect(handlers.get('aiVault:setSearchEnabled')!(null, 'nope', true)).rejects.toThrow( - 'not available for this execution host' - ) - await expect( - handlers.get('aiVault:setSearchEnabled')!(null, 'runtime:env-1', 'yes') - ).rejects.toThrow() - expect(runtimeSearch).not.toHaveBeenCalled() - expect(sshSearch).not.toHaveBeenCalled() - }) -}) - -it('preserves a child reader failure through registry, IPC and preload', async () => { - const service = fakeSearchService() - service.search.mockRejectedValue(new Error('reader deadline exceeded')) - setSessionSearchService( - createChildSessionSearchService({ - search: service.search, - status: service.status, - reconcile: service.reconcile - }) - ) - await expect(aiVaultApi.searchSessions({ query: 'needle' }, 'local')).rejects.toThrow( - 'reader deadline exceeded' - ) -}) diff --git a/src/main/ipc/diagnostics.test.ts b/src/main/ipc/diagnostics.test.ts deleted file mode 100644 index d0a9b93a21d..00000000000 --- a/src/main/ipc/diagnostics.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { CollectedBundle } from '../observability/bundle' -import type * as NodeFs from 'node:fs' - -const handlers = new Map unknown>() - -const { - handleMock, - mkdirSyncMock, - readFileSyncMock, - writeFileSyncMock, - showMessageBoxMock, - openPathMock, - collectDiagnosticBundleMock, - deleteDiagnosticBundleMock, - getDiagnosticsStatusMock, - uploadDiagnosticBundleMock -} = vi.hoisted(() => ({ - handleMock: vi.fn(), - mkdirSyncMock: vi.fn(), - readFileSyncMock: vi.fn(), - writeFileSyncMock: vi.fn(), - showMessageBoxMock: vi.fn(), - openPathMock: vi.fn(), - collectDiagnosticBundleMock: vi.fn(), - deleteDiagnosticBundleMock: vi.fn(), - getDiagnosticsStatusMock: vi.fn(), - uploadDiagnosticBundleMock: vi.fn() -})) - -vi.mock('node:fs', async () => { - const actual = await vi.importActual('node:fs') - return { - ...actual, - mkdirSync: mkdirSyncMock, - readFileSync: readFileSyncMock, - writeFileSync: writeFileSyncMock - } -}) - -vi.mock('electron', () => ({ - app: { getPath: () => '/tmp', getVersion: () => '1.2.3-test' }, - dialog: { showMessageBox: showMessageBoxMock }, - ipcMain: { handle: handleMock }, - shell: { openPath: openPathMock } -})) - -vi.mock('../observability', () => ({ - collectDiagnosticBundle: collectDiagnosticBundleMock, - deleteDiagnosticBundle: deleteDiagnosticBundleMock, - getDiagnosticsStatus: getDiagnosticsStatusMock, - uploadDiagnosticBundle: uploadDiagnosticBundleMock -})) - -import { registerDiagnosticsHandlers } from './diagnostics' - -function captureHandlers(): void { - handlers.clear() - for (const call of handleMock.mock.calls) { - const [channel, handler] = call as [ - string, - typeof handlers extends Map ? V : never - ] - handlers.set(channel, handler) - } -} - -function makeBundle(overrides: Partial = {}): CollectedBundle { - return { - bundleSubmissionId: 'abcdefghijklmnopqrstuv', - payload: '{"type":"bundle-header"}\n', - bytes: 25, - spanCount: 0, - ...overrides - } -} - -describe('diagnostics IPC handlers', () => { - beforeEach(() => { - handleMock.mockReset() - mkdirSyncMock.mockReset() - readFileSyncMock.mockReset() - writeFileSyncMock.mockReset() - showMessageBoxMock.mockReset() - showMessageBoxMock.mockResolvedValue({ response: 0 }) - openPathMock.mockReset() - openPathMock.mockResolvedValue('') - collectDiagnosticBundleMock.mockReset() - deleteDiagnosticBundleMock.mockReset() - getDiagnosticsStatusMock.mockReset() - uploadDiagnosticBundleMock.mockReset() - delete (globalThis as { ORCA_BUILD_IDENTITY?: unknown }).ORCA_BUILD_IDENTITY - delete (globalThis as { ORCA_DIAGNOSTICS_TOKEN_URL?: unknown }).ORCA_DIAGNOSTICS_TOKEN_URL - process.env.ORCA_DIAGNOSTICS_TOKEN_URL = 'https://diagnostics.example.com/diagnostics/token' - getDiagnosticsStatusMock.mockReturnValue({ - localFileEnabled: true, - bundleEnabled: true, - traceFilePath: '/tmp/main.trace.ndjson', - traceFamilySize: 0 - }) - collectDiagnosticBundleMock.mockReturnValue(makeBundle()) - readFileSyncMock.mockReturnValue(makeBundle().payload) - uploadDiagnosticBundleMock.mockResolvedValue({ ticketId: 'ticketabcdefghijklmnop' }) - deleteDiagnosticBundleMock.mockResolvedValue(undefined) - registerDiagnosticsHandlers() - captureHandlers() - }) - - it('rejects upload without a main-collected bundle preview', async () => { - const upload = handlers.get('diagnostics:uploadBundle')! - await expect(upload({}, 'rendererMintedBundleId')).rejects.toThrow(/expired/) - expect(uploadDiagnosticBundleMock).not.toHaveBeenCalled() - }) - - it('rechecks the retained preview after upload confirmation', async () => { - const bundle = makeBundle({ bundleSubmissionId: 'bundleabcdefghijklmnop' }) - collectDiagnosticBundleMock.mockReturnValue(bundle) - const collect = handlers.get('diagnostics:collectBundle')! - const openPreview = handlers.get('diagnostics:openBundlePreview')! - const discard = handlers.get('diagnostics:discardBundlePreview')! - const upload = handlers.get('diagnostics:uploadBundle')! - showMessageBoxMock.mockImplementation(async () => { - await discard({}, bundle.bundleSubmissionId) - return { response: 0 } - }) - - await collect({}, 30) - await openPreview({}, bundle.bundleSubmissionId) - await expect(upload({}, bundle.bundleSubmissionId)).rejects.toThrow(/expired/) - - expect(uploadDiagnosticBundleMock).not.toHaveBeenCalled() - }) - - it('requires opening the retained review file before sending', async () => { - const bundle = makeBundle({ bundleSubmissionId: 'bundleabcdefghijklmnop' }) - collectDiagnosticBundleMock.mockReturnValue(bundle) - const collect = handlers.get('diagnostics:collectBundle')! - const upload = handlers.get('diagnostics:uploadBundle')! - - await collect({}, 30) - await expect(upload({}, bundle.bundleSubmissionId)).rejects.toThrow(/open.*review file/) - expect(uploadDiagnosticBundleMock).not.toHaveBeenCalled() - }) - - it('expires retained bundle previews without another diagnostics call', async () => { - vi.useFakeTimers() - try { - const bundle = makeBundle({ bundleSubmissionId: 'bundleabcdefghijklmnop' }) - collectDiagnosticBundleMock.mockReturnValue(bundle) - const collect = handlers.get('diagnostics:collectBundle')! - const upload = handlers.get('diagnostics:uploadBundle')! - - await collect({}, 30) - await vi.advanceTimersByTimeAsync(15 * 60 * 1000 + 1) - - await expect(upload({}, bundle.bundleSubmissionId)).rejects.toThrow(/expired/) - } finally { - vi.useRealTimers() - } - }) - - it('does not expose retained bundle payloads through collection IPC', async () => { - const bundle = makeBundle({ - bundleSubmissionId: 'bundleabcdefghijklmnop', - payload: '{"secret":"retained in main"}\n' - }) - collectDiagnosticBundleMock.mockReturnValue(bundle) - const collect = handlers.get('diagnostics:collectBundle')! - - const preview = await collect({}, 30) - expect(JSON.stringify(preview)).not.toContain('retained in main') - }) -}) diff --git a/src/main/ipc/filesystem/access/filesystem-path-containment-remote-enoent.test.ts b/src/main/ipc/filesystem/access/filesystem-path-containment-remote-enoent.test.ts deleted file mode 100644 index 78232365d1f..00000000000 --- a/src/main/ipc/filesystem/access/filesystem-path-containment-remote-enoent.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { isENOENT, isPathAbsentError } from './filesystem-path-containment' - -/** Relay JSON-RPC preserves Node ENOENT messages but replaces string codes; remote creation must still recognize expected absence. */ -describe('isENOENT across the SSH relay boundary', () => { - it('recognises an error rebuilt from the relay with a numeric transport code', () => { - // Relay response reconstruction preserves the message and replaces the code. - const fromRelay = new Error( - "ENOENT: no such file or directory, lstat '/home/neil/projects/orca-test1234'" - ) - Object.defineProperty(fromRelay, 'code', { value: -32000 }) - - expect(isENOENT(fromRelay), 'a remote missing path must read as absent, not as a failure').toBe( - true - ) - }) - - it('recognises it through the IPC wrapper the renderer sees', () => { - const throughIpc = new Error( - "Error invoking remote method 'worktrees:create': Error: ENOENT: no such file or directory, lstat '/home/neil/projects/orca-test1234-3'" - ) - - expect(isENOENT(throughIpc)).toBe(true) - }) - - it('does not treat a different errno as absent', () => { - const denied = new Error("EACCES: permission denied, lstat '/root/x'") as NodeJS.ErrnoException - denied.code = 'EACCES' - - expect(isENOENT(denied)).toBe(false) - }) - - it('does not match a message that merely mentions the word', () => { - // Match the canonical phrase so unrelated ENOENT mentions cannot bypass collision checks. - expect(isENOENT(new Error('fix: handle ENOENT better'))).toBe(false) - expect(isENOENT(new Error('branch enoent-handling created'))).toBe(false) - }) -}) - -describe('isPathAbsentError', () => { - it('treats a path under a file as absent, but not a denied one', () => { - // Terminal hard-wrap guesses may probe a child under a file (#32128). - const underFile = Object.assign(new Error("ENOTDIR: not a directory, stat '/r/a.txt/b.txt'"), { - code: 'ENOTDIR' - }) - const denied = Object.assign(new Error("EACCES: permission denied, stat '/root/x'"), { - code: 'EACCES' - }) - - expect(isPathAbsentError(underFile)).toBe(true) - expect(isPathAbsentError(denied)).toBe(false) - }) -}) diff --git a/src/main/ipc/filesystem/filesystem-search-file-paths.test.ts b/src/main/ipc/filesystem/filesystem-search-file-paths.test.ts deleted file mode 100644 index d323518409c..00000000000 --- a/src/main/ipc/filesystem/filesystem-search-file-paths.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { ChildProcess } from 'node:child_process' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../../persistence/loading-store/store' -import type * as GitRunner from '../../git/command-runner/host-routing/wsl-aware-spawn' -import type * as BundledRipgrepPath from '../../ripgrep/bundled-ripgrep-path' - -const { - bundledRipgrepCommandMock, - getLocalGitOptionsForRegisteredWorktreeMock, - resolveAuthorizedPathMock, - wslAwareSpawnMock -} = vi.hoisted(() => ({ - bundledRipgrepCommandMock: vi.fn(), - getLocalGitOptionsForRegisteredWorktreeMock: vi.fn(), - resolveAuthorizedPathMock: vi.fn(), - wslAwareSpawnMock: vi.fn() -})) - -vi.mock('../../git/command-runner/host-routing/wsl-aware-spawn', async (importOriginal) => ({ - ...(await importOriginal()), - wslAwareSpawn: wslAwareSpawnMock -})) - -vi.mock('./access/filesystem-auth', () => ({ - resolveAuthorizedPath: resolveAuthorizedPathMock -})) - -vi.mock('../../ripgrep/bundled-ripgrep-path', async (importOriginal) => ({ - ...(await importOriginal()), - bundledRipgrepCommand: bundledRipgrepCommandMock -})) - -vi.mock('../local-worktree-runtime-options', () => ({ - getLocalGitOptionsForRegisteredWorktree: getLocalGitOptionsForRegisteredWorktreeMock -})) - -import { searchQuickOpenFilePaths } from './filesystem-search-file-paths' - -function createMockProcess(spawned = true): ChildProcess { - const child = new EventEmitter() as ChildProcess - ;(child as unknown as Record).stdout = new EventEmitter() - ;( - (child as unknown as Record).stdout as EventEmitter & { - setEncoding: () => void - } - ).setEncoding = vi.fn() - ;(child as unknown as Record).stderr = new EventEmitter() - ;(child as unknown as Record).kill = vi.fn() - ;(child as unknown as Record).exitCode = null - ;(child as unknown as Record).signalCode = null - Object.defineProperty(child, 'pid', { configurable: true, value: spawned ? 1 : undefined }) - return child -} - -const UNUSED_STORE: Store = Object.create(null) - -function createSpawnError(code: string): NodeJS.ErrnoException { - return Object.assign(new Error(`spawn rg ${code}`), { code }) -} - -async function flushMicrotasks(): Promise { - for (let index = 0; index < 8; index++) { - await Promise.resolve() - } -} - -describe('searchQuickOpenFilePaths', () => { - beforeEach(() => { - vi.clearAllMocks() - resolveAuthorizedPathMock.mockImplementation(async (path) => path) - getLocalGitOptionsForRegisteredWorktreeMock.mockReturnValue({}) - bundledRipgrepCommandMock.mockImplementation((options?: { wsl?: boolean }) => - options?.wsl ? '/bundled/linux/rg' : '/bundled/rg' - ) - }) - - it('preserves control characters within ranked paths', async () => { - const child = createMockProcess() - wslAwareSpawnMock.mockReturnValue(child) - const promise = searchQuickOpenFilePaths('/repo', UNUSED_STORE, { - query: 'target', - limit: 2 - }) - await flushMicrotasks() - child.stdout?.emit('data', 'first\ntarget.ts\0target.ts\r\0') - child.emit('close', 0, null) - expect((await promise).paths.sort()).toEqual(['first\ntarget.ts', 'target.ts\r'].sort()) - }) - - it('rejects and stops an oversized path rather than ranking a truncated suffix', async () => { - const child = createMockProcess() - wslAwareSpawnMock.mockReturnValue(child) - const promise = searchQuickOpenFilePaths('/repo', UNUSED_STORE, { - query: 'target', - limit: 2 - }) - await flushMicrotasks() - child.stdout?.emit('data', 'x'.repeat(64 * 1024 + 1)) - await expect(promise).rejects.toThrow('file path exceeds the listing limit') - expect(child.kill).toHaveBeenCalledTimes(1) - child.stdout?.emit('data', 'target.ts\0') - child.emit('close', 0, null) - }) - - it('finds fuzzy matches after 100k paths without returning excluded worktrees', async () => { - const child = createMockProcess() - wslAwareSpawnMock.mockReturnValue(child) - const promise = searchQuickOpenFilePaths('/repo', {} as Store, { - query: 's4354tgt', - limit: 2, - excludePaths: ['/repo/nested'] - }) - await flushMicrotasks() - - expect(wslAwareSpawnMock).toHaveBeenCalledTimes(1) - expect(wslAwareSpawnMock.mock.calls[0][0]).toBe('/bundled/rg') - expect(wslAwareSpawnMock.mock.calls[0][1]).toContain('--no-ignore-vcs') - child.stdout?.emit( - 'data', - `${Array.from({ length: 100_100 }, (_, index) => `data/payload-${index}.bin`).join('\0')}\0` - ) - child.stdout?.emit('data', 'nested/src/sta-4354-target.ts\0src/sta-4354-target.ts\0') - child.emit('close', 0, null) - - await expect(promise).resolves.toEqual({ - paths: ['src/sta-4354-target.ts'], - totalCount: 1, - truncated: false - }) - }) - - it('retries a transient rg spawn failure instead of reporting the bundled rg broken', async () => { - const failed = createMockProcess(false) - const succeeded = createMockProcess() - wslAwareSpawnMock.mockReturnValueOnce(failed).mockReturnValueOnce(succeeded) - const promise = searchQuickOpenFilePaths('/repo', {} as Store, { - query: 'sta4354gitignored', - limit: 32 - }) - await flushMicrotasks() - - failed.emit('error', createSpawnError('EAGAIN')) - await flushMicrotasks() - - expect(wslAwareSpawnMock).toHaveBeenCalledTimes(2) - succeeded.stdout?.emit('data', 'data/chunk-077568/sta-4354-gitignored-target.bin\0') - succeeded.emit('close', 0, null) - - await expect(promise).resolves.toEqual({ - paths: ['data/chunk-077568/sta-4354-gitignored-target.bin'], - totalCount: 1, - truncated: false - }) - }) - - // Model error then negative close so the async cwd check faces the real spawn ordering. - - // Classify WSL cd failure 97 before generic unavailable checks for codes above rg's 0/1/2. - - it('names the unreachable root when the workspace is gone, not the bundled binary', async () => { - const child = createMockProcess(false) - wslAwareSpawnMock.mockReturnValue(child) - resolveAuthorizedPathMock.mockImplementation(async () => '/definitely/not/here') - const promise = searchQuickOpenFilePaths('/repo', {} as Store, { - query: 'target', - limit: 32 - }) - await flushMicrotasks() - - child.emit('error', createSpawnError('ENOENT')) - child.emit('close', -2, null) - - await expect(promise).rejects.toThrow('Search root is not reachable: /definitely/not/here') - }) -}) diff --git a/src/main/ipc/runtime.test.ts b/src/main/ipc/runtime.test.ts deleted file mode 100644 index fb4080195b4..00000000000 --- a/src/main/ipc/runtime.test.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock, onMock, removeAllListenersMock, removeHandlerMock, fromWebContentsMock } = - vi.hoisted(() => ({ - handleMock: vi.fn(), - onMock: vi.fn(), - removeAllListenersMock: vi.fn(), - removeHandlerMock: vi.fn(), - fromWebContentsMock: vi.fn() - })) - -vi.mock('electron', () => ({ - BrowserWindow: { - fromWebContents: fromWebContentsMock - }, - ipcMain: { - handle: handleMock, - on: onMock, - removeAllListeners: removeAllListenersMock, - removeHandler: removeHandlerMock - } -})) -import { registerRuntimeHandlers } from './runtime' -import { EphemeralVmFailureError } from '../../shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-failure-copy' - -describe('registerRuntimeHandlers', () => { - beforeEach(() => { - handleMock.mockReset() - onMock.mockReset() - removeAllListenersMock.mockReset() - removeHandlerMock.mockReset() - fromWebContentsMock.mockReset() - }) - - it("passes the orchestration contract fence for the window's own mutations", async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fence answers before any other runtime member is read. - registerRuntimeHandlers({ getRuntimeId: () => 'runtime-1' } as never) - const registration = handleMock.mock.calls.find(([channel]) => channel === 'runtime:call') - const frame = {} - const response = await registration![1]( - { senderFrame: frame, sender: { mainFrame: frame, id: 1, once: vi.fn(), on: vi.fn() } }, - { - method: 'orchestration.approvalAnswer', - params: { dispatch: 'ctx_1', prompt: 'apr_1', decision: 'deny', reason: 'no' } - } - ) - expect(response.error?.code).not.toBe('orchestration_migration_required') - }) - - // #36923: the window's wake shares the runtime's one VM wake path with its sleep's suspend. - it("routes the window's recipe VM wake through the runtime", async () => { - const record = { id: 'vm-1', status: 'running' } - const runtime = { wakeWorkspaceVm: vi.fn().mockResolvedValue(record) } - - registerRuntimeHandlers(runtime as never) - - const registration = handleMock.mock.calls.find( - ([channel]) => channel === 'ephemeralVm:resumeWorkspace' - ) - await expect(registration![1]({}, { workspaceId: 'repo::/vm' })).resolves.toEqual({ - ok: true, - runtime: record - }) - expect(runtime.wakeWorkspaceVm).toHaveBeenCalledWith('repo::/vm') - }) - - it('returns coded VM wake and suspend failures as values so the code reaches the window', async () => { - const failure = { - error: 'Resume exited with code 3.', - errorCode: 'resumeExited', - errorParams: { exitCode: 3 } - } - const runtime = { - wakeWorkspaceVm: vi.fn().mockRejectedValue(new EphemeralVmFailureError(failure)), - suspendWorkspaceVm: vi.fn().mockRejectedValue(new Error('Suspend failed.')) - } - registerRuntimeHandlers(runtime as never) - const handler = (channel: string) => - handleMock.mock.calls.find(([registered]) => registered === channel)![1] - - await expect( - handler('ephemeralVm:resumeWorkspace')({}, { workspaceId: 'repo::/vm' }) - ).resolves.toEqual({ ok: false, ...failure }) - await expect( - handler('ephemeralVm:suspendWorkspace')({}, { workspaceId: 'repo::/vm' }) - ).resolves.toEqual({ ok: false, error: 'Suspend failed.' }) - expect(runtime.suspendWorkspaceVm).toHaveBeenCalledWith('repo::/vm') - }) - - // #37067: a phone's re-read on the add's reposChanged came before this publish. - - it('rejects a graph publication queued by a superseded main frame', () => { - const runtime = { - syncWindowGraph: vi.fn(), - getStatus: vi.fn(), - getRuntimeId: vi.fn() - } - registerRuntimeHandlers(runtime as never) - const handler = handleMock.mock.calls.find( - ([channel]) => channel === 'runtime:syncWindowGraph' - )![1] - const sender = { mainFrame: { generation: 2 } } - fromWebContentsMock.mockReturnValue({ id: 17 }) - - expect(() => - handler({ sender, senderFrame: { generation: 1 } }, { tabs: [], leaves: [] }) - ).toThrow('Runtime graph sync must originate from the current main frame') - expect(runtime.syncWindowGraph).not.toHaveBeenCalled() - }) -}) - -it('cancels the GitHub host handler through the existing local subscription boundary', async () => { - handleMock.mockClear() - onMock.mockClear() - const entered = Promise.withResolvers() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture supplies every runtime method reached by this upload subscription. - registerRuntimeHandlers({ - getRuntimeId: () => 'local', - uploadGitHubAttachment: (_params: unknown, _bytes: Buffer, signal: AbortSignal) => { - entered.resolve(signal) - return new Promise((_resolve, reject) => - signal.addEventListener('abort', () => reject(signal.reason), { once: true }) - ) - } - } as never) - const frame = {} - const sender = { - mainFrame: frame, - id: 14237, - once: vi.fn(), - on: vi.fn(), - send: vi.fn(), - isDestroyed: () => false - } - const event = { senderFrame: frame, sender } - const handler = (channel: string) => handleMock.mock.calls.find(([name]) => name === channel)![1] - const started = await handler('runtime:call')(event, { - method: 'clipboard.startImageUpload', - params: { expectedBase64Length: 8, fileName: 'image.png' } - }) - expect(started.ok).toBe(true) - await handler('runtime:call')(event, { - method: 'clipboard.appendImageUploadChunk', - params: { uploadId: started.result.uploadId, offset: 0, contentBase64: 'aW1hZ2U=' } - }) - handler('runtime:subscribe')(event, { - subscriptionId: 'image-cancel', - method: 'github.uploadAttachment', - params: { - uploadId: started.result.uploadId, - target: { kind: 'repo', repo: 'repo', source: 'origin' }, - fileName: 'image.png', - contentType: 'image/png' - } - }) - const signal = await entered.promise - const unsubscribe = onMock.mock.calls.find(([name]) => name === 'runtime:unsubscribe')![1] - unsubscribe(event, { subscriptionId: 'image-cancel' }) - expect(signal.aborted).toBe(true) -}) diff --git a/src/main/ipc/ssh/ssh.test.ts b/src/main/ipc/ssh/ssh.test.ts deleted file mode 100644 index 4f1d0504571..00000000000 --- a/src/main/ipc/ssh/ssh.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = await vi.hoisted(async () => { - const { createSshIpcMocks } = await import('./ssh-ipc-module-mocks') - return createSshIpcMocks() -}) - -vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) -vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) -vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) -vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) -vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) -vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) - -import type { SshConnectionState, SshTarget } from '../../../shared/remote-runtime/ssh/ssh-types' -import { createSshIpcHarness } from './ssh-ipc-test-harness' -import { decideHostServer, publishUnservedHostServer } from './ssh-host-server-connect' -import { - beginSshHostCensus, - recordSshConnectionOpened -} from '../../ssh/connection/ssh-connection-attribution' -import type { SshConnection } from '../../ssh/connection/ssh-connection' -import { - clearSshHostServerStatus, - setSshHostServerStatus -} from '../../ssh/host-server/ssh-host-server-status' - -const { mockSshStore, mockConnectionManager } = mocks - -const target: SshTarget = { - id: 'ssh-1', - label: 'Server', - host: 'example.com', - port: 22, - username: 'deploy' -} - -function asTransport(value: { id: string }): SshConnection { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attribution keys on identity only. - return value as unknown as SshConnection -} - -describe('SSH IPC handlers', () => { - const harness = createSshIpcHarness(mocks) - const { handlers, mockWindow } = harness - - beforeEach(harness.reset) - - it('fails a host the managed server does not serve, with no fallback', async () => { - const decision = { - route: 'unserved' as const, - reason: 'orcad_unavailable' as const, - detail: 'unsupported_host' - } - const opened = { id: 'decision-transport' } - mockSshStore.getTarget.mockReturnValue(target) - vi.mocked(decideHostServer).mockImplementationOnce(async () => { - recordSshConnectionOpened(asTransport(opened)) - mockConnectionManager.getConnection.mockReturnValue(opened) - return decision - }) - - await expect(handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' })).rejects.toThrow( - 'This SSH host isn’t supported' - ) - expect(publishUnservedHostServer).toHaveBeenCalledWith(target, decision) - expect(mockConnectionManager.disconnectConnection).toHaveBeenCalledWith('ssh-1', opened) - expect(mockConnectionManager.connect).not.toHaveBeenCalled() - }) - - it('holds a raw connected the server decision causes', async () => { - const conn = { hasCachedCredential: () => false } - mockSshStore.getTarget.mockReturnValue(target) - mockConnectionManager.getConnection.mockReturnValue(conn) - let broadcastsDuringDecision: unknown[] = [] - vi.mocked(decideHostServer).mockImplementationOnce(async () => { - await Promise.resolve() - const callbacks = mockConnectionManager.callbacksRef.current as { - onStateChange: (targetId: string, state: SshConnectionState) => void - } - callbacks.onStateChange('ssh-1', { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0 - }) - broadcastsDuringDecision = mockWindow.webContents.send.mock.calls - .filter(([channel]) => channel === 'ssh:state-changed') - .map(([, payload]) => payload) - return { route: 'managed', environmentId: 'env-test' } - }) - - await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) - expect(broadcastsDuringDecision).not.toContainEqual( - expect.objectContaining({ state: expect.objectContaining({ status: 'connected' }) }) - ) - expect(broadcastsDuringDecision.at(-1)).toMatchObject({ state: { status: 'connecting' } }) - }) - - it("holds a census's raw 'connected' outside any connect", () => { - const end = beginSshHostCensus('ssh-1') - try { - const callbacks = mockConnectionManager.callbacksRef.current as { - onStateChange: (targetId: string, state: SshConnectionState) => void - } - mockWindow.webContents.send.mockClear() - callbacks.onStateChange('ssh-1', { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0 - }) - expect(mockWindow.webContents.send).toHaveBeenCalledWith( - 'ssh:state-changed', - expect.objectContaining({ state: expect.objectContaining({ status: 'connecting' }) }) - ) - } finally { - end() - } - }) - - // Tunnel startup can serve a host without an SSH connect, so connect-only restoration left saved forwards off (#32484). - it.each([ - { kind: 'managed', environmentId: 'env-test' } as const, - { kind: 'relay', reason: 'orcad_unavailable', bridged: true } as const - ])('restores saved forwards whenever a $kind status is published', async (status) => { - const conn = { id: 'conn-1', getConnectGeneration: () => 1 } - mockSshStore.getTarget.mockReturnValue({ - ...target, - portForwards: [{ localPort: 8080, remoteHost: '127.0.0.1', remotePort: 3000 }] - }) - mockConnectionManager.getConnection.mockReturnValue(conn) - clearSshHostServerStatus('ssh-1') - try { - setSshHostServerStatus('ssh-1', status) - await vi.waitFor(() => - expect(mocks.mockPortForwardManager.addForward).toHaveBeenCalledWith( - 'ssh-1', - conn, - 8080, - '127.0.0.1', - 3000, - undefined - ) - ) - } finally { - clearSshHostServerStatus('ssh-1') - } - }) - - it('leaves saved forwards alone while the server decision is unsettled', async () => { - mockSshStore.getTarget.mockReturnValue({ - ...target, - portForwards: [{ localPort: 8080, remoteHost: '127.0.0.1', remotePort: 3000 }] - }) - mockConnectionManager.getConnection.mockReturnValue({ - id: 'conn-1', - getConnectGeneration: () => 1 - }) - try { - setSshHostServerStatus('ssh-1', { kind: 'setting-up', phase: 'deploying' }) - setSshHostServerStatus('ssh-1', { kind: 'relay', reason: 'orcad_unavailable' }) - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(mocks.mockPortForwardManager.addForward).not.toHaveBeenCalled() - } finally { - clearSshHostServerStatus('ssh-1') - } - }) -}) diff --git a/src/main/ipc/worktrees/git/worktree-git-status-ref-watch.test.ts b/src/main/ipc/worktrees/git/worktree-git-status-ref-watch.test.ts deleted file mode 100644 index 62accf44432..00000000000 --- a/src/main/ipc/worktrees/git/worktree-git-status-ref-watch.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - clearActiveGitStatusRefBinding, - updateActiveGitStatusRefBinding, - type GitStatusRefBindingRequest, - type GitStatusRefWatchTarget -} from './worktree-git-status-ref-watch' - -function makeTarget(): GitStatusRefWatchTarget { - return { - kind: 'git-common', - path: 'C:\\repo\\.git', - repos: new Map([['repo-1', { repoId: 'repo-1', repoName: 'repo', nestWorkspaces: false }]]), - gitStatusRefPaths: new Set() - } -} - -describe('worktree git status ref watch binding', () => { - afterEach(() => clearActiveGitStatusRefBinding()) - - function request(overrides: Partial = {}) { - return { - worktreeId: 'repo-1::C:\\repo', - worktreePath: 'C:\\repo', - executionHostId: 'local', - branch: 'refs/heads/feature/main', - upstreamName: 'origin/feature/main', - ...overrides - } - } - - it('binds a custom refspec destination exactly', async () => { - const target = makeTarget() - await updateActiveGitStatusRefBinding( - request(), - () => [target], - async () => 'refs/custom/origin/main' - ) - - expect([...target.gitStatusRefPaths]).toEqual(['C:/repo/.git/refs/custom/origin/main']) - }) - - it('does not spend the dynamic ref stat on a slash-named local upstream', async () => { - const target = makeTarget() - await updateActiveGitStatusRefBinding( - request(), - () => [target], - async () => 'refs/heads/feature/base' - ) - - expect(target.gitStatusRefPaths).toEqual(new Set()) - }) - - it('keeps a slash-containing remote name exact', async () => { - const target = makeTarget() - await updateActiveGitStatusRefBinding( - request(), - () => [target], - async () => 'refs/remotes/team/fork/feature/main' - ) - - expect([...target.gitStatusRefPaths]).toEqual([ - 'C:/repo/.git/refs/remotes/team/fork/feature/main' - ]) - }) - - it('does not resolve the exact ref again on unchanged status ticks', async () => { - const target = makeTarget() - const resolve = vi.fn(async () => 'refs/remotes/origin/feature/main') - - await updateActiveGitStatusRefBinding(request(), () => [target], resolve) - await updateActiveGitStatusRefBinding(request(), () => [target], resolve) - - expect(resolve).toHaveBeenCalledOnce() - }) - - it('applies an in-flight resolution to a replacement watch', async () => { - const first = makeTarget() - const replacement = makeTarget() - let current = [first] - let finish: (ref: string) => void = () => {} - const pending = new Promise((resolve) => { - finish = resolve - }) - - const update = updateActiveGitStatusRefBinding( - request(), - () => current, - () => pending - ) - current = [replacement] - finish('refs/remotes/origin/feature/main') - await update - - expect(first.gitStatusRefPaths).toEqual(new Set()) - expect([...replacement.gitStatusRefPaths]).toEqual([ - 'C:/repo/.git/refs/remotes/origin/feature/main' - ]) - - const latest = makeTarget() - current = [latest] - const resolve = vi.fn(async () => 'refs/remotes/origin/feature/main') - await updateActiveGitStatusRefBinding(request(), () => current, resolve) - expect(resolve).not.toHaveBeenCalled() - expect([...latest.gitStatusRefPaths]).toEqual(['C:/repo/.git/refs/remotes/origin/feature/main']) - }) -}) diff --git a/src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts b/src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts deleted file mode 100644 index 519e985222d..00000000000 --- a/src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import type { GitWorktreeInfo } from '../../../../shared/worktree/types' - -const { listRepoWorktreesMock, pruneLineageMock, pruneMetadataMock, registerWorktreeRootsMock } = - vi.hoisted(() => ({ - listRepoWorktreesMock: vi.fn(), - pruneLineageMock: vi.fn(), - pruneMetadataMock: vi.fn(), - registerWorktreeRootsMock: vi.fn() - })) - -vi.mock('../../../workspaces/catalog/repo-worktrees', () => ({ - listRepoWorktreesForDetectedScan: listRepoWorktreesMock -})) -vi.mock('../../../workspaces/execution-host/project-runtime-git-options', () => ({ - getLocalProjectWorktreeGitOptions: () => ({}) -})) -vi.mock('../removal/registered-worktree-roots-cache', () => ({ - getRegisteredWorktreeRootsRevision: () => 1, - registerWorktreeRootsForRepo: registerWorktreeRootsMock -})) -vi.mock('../../../workspaces/catalog/worktree-lineage-pruning', () => ({ - pruneLineageForMissingRepoWorktrees: pruneLineageMock -})) -vi.mock('./authoritative-local-worktree-metadata-pruning', () => ({ - pruneMetadataMissingFromAuthoritativeLocalScan: pruneMetadataMock -})) - -const { - DETECTED_WORKTREE_SCAN_CACHE_TTL_MS, - __resetDetectedWorktreeScanCacheForTests, - applyFreshDetectedWorktreeScanSideEffects, - invalidateDetectedWorktreeScanCache, - listDetectedGitWorktrees -} = await import('./detected-worktree-scan-cache') -const { setWorktreeCatalogRouteResolver } = - await import('../../../workspaces/catalog/repo-worktree-catalog-route') -const { invalidateLocalWorktreeMetadataPruneInputs } = - await import('../../../workspaces/catalog/local-worktree-metadata-prune-gate') - -const repo = { id: 'repo-1', path: '/repos/one', displayName: 'one' } as Repo - -function worktreeAt(path: string): GitWorktreeInfo { - return { path, head: 'abc', branch: 'main', isBare: false, isMainWorktree: path === repo.path } -} - -const captureExpectation = vi.fn(() => ({ repo: { id: repo.id }, metadata: [] })) -const store = { captureNativeLocalWorktreeMetadataScanExpectation: captureExpectation } as never - -function advancePastListingTtl(): void { - vi.setSystemTime(Date.now() + DETECTED_WORKTREE_SCAN_CACHE_TTL_MS + 1) -} - -describe('detected worktree scan hygiene gate', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(1_000_000) - listRepoWorktreesMock.mockReset().mockResolvedValue([worktreeAt(repo.path)]) - captureExpectation.mockClear() - pruneLineageMock.mockReset() - pruneMetadataMock - .mockReset() - .mockResolvedValue({ scanGenerationCurrent: true, preservedMetadataCandidateIds: new Set() }) - registerWorktreeRootsMock.mockReset() - __resetDetectedWorktreeScanCacheForTests() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('runs hygiene once and then never again while nothing changes', async () => { - const first = await listDetectedGitWorktrees(store, repo) - expect(first.hygieneDue).toBe(true) - expect(first.metadataPrune).toBeDefined() - - for (let poll = 0; poll < 20; poll += 1) { - advancePastListingTtl() - const scan = await listDetectedGitWorktrees(store, repo) - expect(scan.fresh).toBe(true) - expect(scan.hygieneDue).toBe(false) - expect(scan.metadataPrune).toBeUndefined() - } - expect(captureExpectation).toHaveBeenCalledTimes(1) - }) - - it('re-runs hygiene after a worktree lifecycle event', async () => { - await listDetectedGitWorktrees(store, repo) - invalidateDetectedWorktreeScanCache(repo.id) - - expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(true) - expect(captureExpectation).toHaveBeenCalledTimes(2) - }) - - it('re-runs hygiene when ownership state may have released a row', async () => { - await listDetectedGitWorktrees(store, repo) - advancePastListingTtl() - expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(false) - - invalidateLocalWorktreeMetadataPruneInputs() - - advancePastListingTtl() - expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(true) - expect(captureExpectation).toHaveBeenCalledTimes(2) - }) - - it('re-runs hygiene when the listing changes with no event to report it', async () => { - await listDetectedGitWorktrees(store, repo) - advancePastListingTtl() - expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(false) - - // Model an external removal with no change notification. - listRepoWorktreesMock.mockResolvedValue([worktreeAt(repo.path), worktreeAt('/repos/one-wt')]) - advancePastListingTtl() - await listDetectedGitWorktrees(store, repo) - - advancePastListingTtl() - expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(true) - }) - - it('stops deleting once the owner retires the route during the prune helper', async () => { - let live = true - setWorktreeCatalogRouteResolver(() => - live ? { repoPath: repo.path, runtimeKey: 'local:default' } : null - ) - try { - const scan = await listDetectedGitWorktrees(store, repo) - let helperSawCurrent: boolean | undefined - pruneMetadataMock.mockImplementation(async (args: { isCallerCurrent: () => boolean }) => { - live = false - helperSawCurrent = args.isCallerCurrent() - return { scanGenerationCurrent: true, preservedMetadataCandidateIds: new Set() } - }) - - const applied = await applyFreshDetectedWorktreeScanSideEffects( - store, - repo, - scan.gitWorktrees, - scan.metadataPrune, - { sideEffectToken: scan.sideEffectToken, hygieneDue: scan.hygieneDue } - ) - - expect(helperSawCurrent).toBe(false) - expect(applied).toBe(false) - expect(pruneLineageMock).not.toHaveBeenCalled() - expect(scan.authorityCurrent?.()).toBe(false) - } finally { - setWorktreeCatalogRouteResolver(null) - } - }) -}) diff --git a/src/main/managed-server/install/remote-install-lock-termination.test.ts b/src/main/managed-server/install/remote-install-lock-termination.test.ts deleted file mode 100644 index da282da7ad2..00000000000 --- a/src/main/managed-server/install/remote-install-lock-termination.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand: vi.fn() -})) - -import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { acquireInstallLock, isRelayInstallLockStale } from './remote-install-lock' -import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' -import { unusedSshConnection } from '../testing/managed-host-transport.test-fixture' - -const conn = unusedSshConnection() -const mockExec = vi.mocked(execCommand) -const nextAcquisition = ['OPEN', '', 'OK', 'OPEN'] - -const lockFailureStages = [ - { - stage: 'claim probe after acquisition', - replies: ['OPEN', '', 'OK'], - recovery: ['', 'OK', 'OPEN'] - }, - { - stage: 'release after acquisition', - replies: ['OPEN', '', 'OK', 'LOCKED'], - recovery: ['OK', 'OPEN'] - }, - { - stage: 'stale lock takeover', - replies: ['OPEN', '', 'BUSY'], - recovery: nextAcquisition - }, - { - stage: 'claim probe after stale takeover', - replies: ['OPEN', '', 'BUSY', 'OK'], - recovery: ['', ...nextAcquisition] - }, - { - stage: 'release after stale takeover', - replies: ['OPEN', '', 'BUSY', 'OK', 'LOCKED'], - recovery: nextAcquisition - } -] - -beforeEach(() => { - mockExec.mockReset() - mockExec.mockResolvedValue('OPEN') - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'info').mockImplementation(() => {}) -}) - -afterEach(() => { - vi.restoreAllMocks() - vi.useRealTimers() -}) - -describe.each([ - { platform: 'linux-x64' as const, remoteDir: '/relay/version' }, - { platform: 'win32-x64' as const, remoteDir: 'C:/relay/version' } -])('install lock termination on $platform', ({ platform, remoteDir }) => { - const host = getRemoteHostPlatform(platform) - - it.each(lockFailureStages)('stops after unconfirmed $stage', async ({ replies }) => { - const error = Object.assign(new Error('SSH teardown not confirmed'), { - sshChannelCloseConfirmed: false - }) - for (const reply of replies) { - mockExec.mockResolvedValueOnce(reply) - } - mockExec.mockRejectedValueOnce(error) - - await expect(acquireInstallLock(conn, remoteDir, host)).rejects.toBe(error) - expect(mockExec).toHaveBeenCalledTimes(replies.length + 1) - }) - - it.each(lockFailureStages)( - 'keeps recovery after confirmed $stage failure', - async ({ replies, recovery }) => { - vi.useFakeTimers() - for (const reply of replies) { - mockExec.mockResolvedValueOnce(reply) - } - mockExec.mockRejectedValueOnce( - Object.assign(new Error('SSH command failed after closing'), { - sshChannelCloseConfirmed: true - }) - ) - for (const reply of recovery) { - mockExec.mockResolvedValueOnce(reply) - } - - const acquiring = acquireInstallLock(conn, remoteDir, host) - await vi.advanceTimersByTimeAsync(1_000) - - await expect(acquiring).resolves.toBeUndefined() - expect(mockExec).toHaveBeenCalledTimes(replies.length + recovery.length + 1) - } - ) - - it('preserves takeover uncertainty when the caller also aborts', async () => { - const controller = new AbortController() - const error = Object.assign(new Error('SSH teardown not confirmed'), { - sshChannelCloseConfirmed: false - }) - mockExec - .mockResolvedValueOnce('OPEN') - .mockResolvedValueOnce('') - .mockResolvedValueOnce('BUSY') - .mockImplementationOnce(async () => { - controller.abort(new Error('deploy aborted')) - throw error - }) - - await expect( - acquireInstallLock(conn, remoteDir, host, { signal: controller.signal }) - ).rejects.toBe(error) - expect(mockExec).toHaveBeenCalledTimes(4) - }) - - it('preserves uncertainty from the stale lock age probe', async () => { - const error = Object.assign(new Error('SSH teardown not confirmed'), { - sshChannelCloseConfirmed: false - }) - mockExec.mockRejectedValueOnce(error) - - await expect(isRelayInstallLockStale(conn, remoteDir, host)).rejects.toBe(error) - expect(mockExec).toHaveBeenCalledTimes(1) - }) - - it('keeps a confirmed stale age probe failure as not stale', async () => { - mockExec.mockRejectedValueOnce( - Object.assign(new Error('SSH command failed after closing'), { - sshChannelCloseConfirmed: true - }) - ) - - await expect(isRelayInstallLockStale(conn, remoteDir, host)).resolves.toBe(false) - expect(mockExec).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts b/src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts deleted file mode 100644 index f371e7442ca..00000000000 --- a/src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { rmSync } from 'node:fs' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getManagedOrcadFenceEnvironmentId } from '../../../shared/remote-runtime/ssh/managed-orcad-ssh-owner' -import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store' -import { - listOrcadMigrationSourceCutovers, - writeOrcadMigrationSourceCutover -} from '../../persistence/migrating-orcad-catalog/cutover-journals/orcad-migration-cutover-journal' -import { orcadMigrationCutoverFixture } from '../migration/cutover/testing/orcad-migration-cutover-fixture' -import { createManagedLifecycleHarness } from './orcad-managed-lifecycle-test-fixture' -import { isManagedOrcadSshTarget } from '../../ssh/targets/ssh-target-runtime-ownership' -import { addManagedOrcadEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' - -const mocks = vi.hoisted(() => { - const state: { store: unknown } = { store: null } - return { - state, - connect: vi.fn(), - resolveContext: vi.fn(), - closeTunnel: vi.fn(), - retire: vi.fn(), - releaseHost: vi.fn() - } -}) - -vi.mock('../../ssh/targets/ssh-target-registry', () => ({ - getSshConnectionManager: () => ({ connect: mocks.connect }), - getSshTargetRegistryStore: () => mocks.state.store -})) -vi.mock('../install/orcad-remote-context', () => ({ - resolveOrcadRemoteContext: mocks.resolveContext -})) -vi.mock('./orcad-managed-tunnel', () => ({ - closeOrcadManagedTunnel: mocks.closeTunnel, - ensureOrcadManagedTunnel: vi.fn() -})) - -const { - forgetManagedOrcadEnvironment, - forgetRedundantManagedOrcadEnvironment, - stopManagedOrcadEnvironment -} = await import('./orcad-runtime-decommission') - -let harness: ReturnType - -const policy = (isActive = false) => ({ - isActiveEnvironment: () => isActive, - retireLocalState: mocks.retire, - releaseHostTransport: mocks.releaseHost -}) - -beforeEach(() => { - vi.resetAllMocks() - harness = createManagedLifecycleHarness() - mocks.state.store = harness.targetStore - mocks.connect.mockRejectedValue(new Error('connect ECONNREFUSED 127.0.0.1:2841')) - mocks.resolveContext.mockRejectedValue(new Error('connect ECONNREFUSED 127.0.0.1:2841')) -}) - -afterEach(() => rmSync(harness.userDataPath, { recursive: true, force: true })) - -describe('a managed server whose host is gone (P1-E)', () => { - it('cannot be stopped, since the host can never prove orcad exited', async () => { - await expect( - stopManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }, policy()) - ).rejects.toThrow('ECONNREFUSED') - expect(listEnvironments(harness.userDataPath)).toHaveLength(1) - expect(isManagedOrcadSshTarget(harness.current())).toBe(true) - }) - - it('is forgotten locally without contacting the host, which frees its SSH target', async () => { - writeOrcadMigrationSourceCutover(harness.userDataPath, { - ...orcadMigrationCutoverFixture('migration-1', 'ssh-1', { environmentId: 'environment-1' }), - phase: 'destination-committed', - sourceRetainedAt: '2026-10-01T00:00:00.000Z' - }) - await expect( - forgetManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }, policy()) - ).resolves.toEqual({ - outcome: 'forgotten', - // No host observation means local forgetting cannot report proven exit. - verdict: 'unverifiable', - environmentId: 'environment-1', - sshTargetId: 'ssh-1' - }) - expect(mocks.connect).not.toHaveBeenCalled() - expect(mocks.resolveContext).not.toHaveBeenCalled() - expect(listEnvironments(harness.userDataPath)).toEqual([]) - expect(getManagedOrcadFenceEnvironmentId(harness.current())).toBeNull() - expect(isManagedOrcadSshTarget(harness.current())).toBe(false) - expect(harness.flushes).toHaveLength(1) - expect(mocks.retire).toHaveBeenCalledWith('environment-1') - expect(mocks.closeTunnel).toHaveBeenCalledWith('environment-1') - // An unserved host never stays connected, so Set location can't offer it (#37767). - expect(mocks.releaseHost).toHaveBeenCalledWith('ssh-1') - expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([]) - }) - - it('refuses to forget the Active Server and keeps every link', async () => { - await expect( - forgetManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }, policy(true)) - ).resolves.toMatchObject({ outcome: 'refused', code: 'orcad_forget_active_environment' }) - expect(listEnvironments(harness.userDataPath)).toHaveLength(1) - expect(getManagedOrcadFenceEnvironmentId(harness.current())).toBe('environment-1') - expect(mocks.retire).not.toHaveBeenCalled() - expect(mocks.closeTunnel).not.toHaveBeenCalled() - expect(mocks.releaseHost).not.toHaveBeenCalled() - }) -}) - -describe('a managed server saved under a second SSH alias', () => { - // Same host key in its padded spelling, reached through its own SSH target. - const addTwin = () => - addManagedOrcadEnvironment(harness.userDataPath, { - id: 'environment-2', - name: 'Managed alias', - pairingCode: encodePairingOffer({ - v: PAIRING_OFFER_VERSION, - endpoint: 'ws://127.0.0.1:46769/', - deviceToken: 'alias-device-token', - publicKeyB64: 'public-key=' - }), - orcadDeployment: { - sshTargetId: 'ssh-2', - sshTargetGeneration: 1, - localPort: 46_769, - remotePort: 6_768 - } - }) - - it('forgets the redundant entry and leaves the other one managing the server', async () => { - addTwin() - await expect( - forgetRedundantManagedOrcadEnvironment( - harness.userDataPath, - { selector: 'Managed' }, - policy() - ) - ).resolves.toMatchObject({ outcome: 'forgotten', environmentId: 'environment-1' }) - expect(mocks.connect).not.toHaveBeenCalled() - expect(listEnvironments(harness.userDataPath).map(({ id }) => id)).toEqual(['environment-2']) - }) - - it('refuses when the other entry is gone by the time the removal runs', async () => { - await expect( - forgetRedundantManagedOrcadEnvironment( - harness.userDataPath, - { selector: 'Managed' }, - policy() - ) - ).resolves.toMatchObject({ outcome: 'refused', code: 'orcad_forget_no_managed_twin' }) - expect(listEnvironments(harness.userDataPath)).toHaveLength(1) - expect(getManagedOrcadFenceEnvironmentId(harness.current())).toBe('environment-1') - expect(mocks.closeTunnel).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-rows.test.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-rows.test.ts deleted file mode 100644 index e60ae7a6039..00000000000 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-rows.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -// Refused events must consume no keys, rows or admission budget. - -import { afterEach, describe, expect, it } from 'vitest' -import { parseAgentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key' -import { - backgroundTask, - closeProviderTimelineRigs, - messageText, - openProviderTimelineRig, - pendingApproval, - providerItemId, - providerTurnItemId, - refusingSink -} from './provider-timeline-assembler-test-support' - -afterEach(closeProviderTimelineRigs) - -const messages = async (rig: Awaited>) => - (await rig.rows()).filter((row) => row.body.kind === 'message') - -describe('a refused event takes nothing', () => { - it('allocates no key and no request row, and its retry lands once', async () => { - const rig = await openProviderTimelineRig() - let refusing = false - const assembler = rig.assemble({ sink: refusingSink(rig.sink, () => refusing) }) - const refused = { accepted: false, reason: 'backpressure' } - const turnOpen = { type: 'turn.open', at: 1_000 } as const - const frame = { type: 'provider.frame', frameKind: 'mystery', payload: { a: 1 } } as const - const request = { type: 'request.open', request: 'p1', body: pendingApproval } as const - refusing = true - expect(assembler.apply(turnOpen).admission).toEqual(refused) - expect(assembler.openTurnId).toBeNull() - refusing = false - expect(assembler.apply(turnOpen).admission).toEqual({ accepted: true }) - expect(assembler.openTurnId).toBe('m:gen-1%3At1') - refusing = true - expect(assembler.apply(frame).admission).toEqual(refused) - expect(assembler.apply(request).admission).toEqual(refused) - refusing = false - expect(assembler.apply(frame).admission).toEqual({ accepted: true }) - expect(assembler.apply(request).admission).toEqual({ accepted: true }) - assembler.apply({ - type: 'text.delta', - item: { stream: 'reply' }, - channel: 'assistant', - text: 'Hi' - }) - assembler.flush() - - const rows = (await rig.rows()).filter((row) => row.body.kind !== 'turn') - expect(rows.map((row) => row.itemId)).toEqual([ - expect.stringContaining('frame%3Am%3Agen-1%253Af2'), - providerItemId('request', 'p1'), - expect.stringContaining('item%3Am%3Agen-1%253As3') - ]) - expect(messageText(rows[2]?.body)).toBe('Hi') - }) -}) - -describe('a row keeps the turn it opened in', () => { - it('takes a background task update in the turn it opened in, after that turn ended', async () => { - const rig = await openProviderTimelineRig() - rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 }) - rig.assembler.apply({ - type: 'item.open', - item: 'background-tool', - body: backgroundTask('background-tool', 'working') - }) - rig.assembler.apply({ type: 'turn.end', turn: 't1', at: 2_000, state: 'completed' }) - // Completed turns still own later updates to their existing rows. - rig.assembler.apply({ - type: 'item.update', - item: 'background-tool', - body: backgroundTask('background-tool', 'done') - }) - expect(await rig.row(providerItemId('item', 'background-tool'))).toMatchObject({ - turnScope: { kind: 'turn', turnItemId: providerTurnItemId('t1') }, - body: backgroundTask('background-tool', 'done') - }) - }) -}) - -describe('streamed text has the same lifecycle as the item it streams into', () => { - it('keeps interleaved same-id streams on separate threads apart', async () => { - const rig = await openProviderTimelineRig({ ownThread: () => 'root' }) - rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 }) - rig.assembler.apply({ - type: 'text.delta', - item: { id: 'm1' }, - channel: 'assistant', - text: 'Root', - join: { thread: 'root', turn: 't1' } - }) - rig.assembler.apply({ - type: 'text.delta', - item: { id: 'm1' }, - channel: 'assistant', - text: 'Child', - join: { thread: 'child', turn: 'child-turn' } - }) - rig.assembler.apply({ type: 'turn.end', turn: 't1', at: 2_000, state: 'completed' }) - - expect((await messages(rig)).map((row) => [row.itemId, messageText(row.body)])).toEqual([ - [providerItemId('item', 'm1', { thread: 'root' }), 'Root'], - [providerItemId('item', 'm1', { thread: 'child' }), 'Child'] - ]) - }) - - it('settles a message on text.close, so a late delta cannot erase what it said', async () => { - const rig = await openProviderTimelineRig() - rig.assembler.apply({ - type: 'text.delta', - item: { id: 'm1' }, - channel: 'assistant', - text: 'Prefix' - }) - rig.assembler.apply({ type: 'text.close', item: { id: 'm1' } }) - expect( - rig.assembler.apply({ - type: 'text.delta', - item: { id: 'm1' }, - channel: 'assistant', - text: 'Suffix' - }).dropped - ).toBe('item-settled') - rig.assembler.flush() - - expect(messageText((await rig.row(providerItemId('item', 'm1')))?.body)).toBe('Prefix') - }) -}) - -describe('the budget counts the work actually open', () => { - it('frees an answered request incarnation without waiting for its turn to end', async () => { - const rig = await openProviderTimelineRig() - rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 }) - for (let incarnation = 1; incarnation <= 129; incarnation += 1) { - expect( - rig.assembler.apply({ type: 'request.open', request: 'approval', body: pendingApproval }) - .admission - ).toEqual({ accepted: true }) - await rig.rows() - const identity = parseAgentJournalItemKey( - providerItemId('request', 'approval', { incarnation }) - ) - if (!identity) { - throw new Error('the request has a journal key') - } - await rig.journal.appendItem( - identity, - { - ...pendingApproval, - resolution: { - state: 'resolved', - selectedOptionId: 'allow', - resolvedBy: 'phone', - resolvedAt: 1_100 - } - }, - { fence: 1, turnScope: { kind: 'turn', turnItemId: providerTurnItemId('t1') } } - ) - } - }) -}) diff --git a/src/main/persistence/preferences/active-view-preference.test.ts b/src/main/persistence/preferences/active-view-preference.test.ts deleted file mode 100644 index 667b765d724..00000000000 --- a/src/main/persistence/preferences/active-view-preference.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { ActiveViewPreference, getActiveViewPreferenceFile } from './active-view-preference' - -describe('ActiveViewPreference', () => { - let dir: string - let dataFile: string - - beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orca-active-view-')) - dataFile = join(dir, 'orca-data.json') - }) - - afterEach(() => { - vi.useRealTimers() - rmSync(dir, { recursive: true, force: true }) - }) - - it('migrates the legacy durable-state value into the profile sidecar', async () => { - vi.useFakeTimers() - const preference = new ActiveViewPreference(dataFile, 'tasks') - - expect(preference.get()).toBe('tasks') - expect(existsSync(getActiveViewPreferenceFile(dataFile))).toBe(false) - - expect(preference.set('tasks')).toBe(false) - vi.advanceTimersByTime(100) - await preference.waitForPendingWrite() - - expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({ - activeView: 'tasks' - }) - }) - - it('coalesces rapid switches into one tiny preference write', async () => { - vi.useFakeTimers() - const preference = new ActiveViewPreference(dataFile, 'terminal') - - preference.set('settings') - vi.advanceTimersByTime(50) - preference.set('automations') - vi.advanceTimersByTime(50) - expect(existsSync(getActiveViewPreferenceFile(dataFile))).toBe(false) - - vi.advanceTimersByTime(50) - await preference.waitForPendingWrite() - - expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({ - activeView: 'automations' - }) - }) - - it('flushes synchronously for an immediate graceful exit', () => { - vi.useFakeTimers() - const preference = new ActiveViewPreference(dataFile, 'terminal') - - preference.set('settings') - preference.flushOrThrow() - - expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({ - activeView: 'settings' - }) - vi.advanceTimersByTime(100) - expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({ - activeView: 'settings' - }) - }) - - it('ignores an invalid sidecar and invalid updates', () => { - writeFileSync(getActiveViewPreferenceFile(dataFile), '{"activeView":"unknown"}', 'utf-8') - const preference = new ActiveViewPreference(dataFile, 'not-a-view') - - expect(preference.get()).toBe('terminal') - expect(preference.set('also-not-a-view')).toBe(false) - expect(preference.get()).toBe('terminal') - }) - - it('rejects inherited object keys from a corrupt sidecar', () => { - // Inherited keys pass `in` checks but are invalid views. - writeFileSync(getActiveViewPreferenceFile(dataFile), '{"activeView":"constructor"}', 'utf-8') - const preference = new ActiveViewPreference(dataFile, 'tasks') - - expect(preference.get()).toBe('tasks') - expect(preference.set('__proto__')).toBe(false) - expect(preference.get()).toBe('tasks') - }) -}) diff --git a/src/main/persistence/restoring-sessions/session-worktree-ownership.test.ts b/src/main/persistence/restoring-sessions/session-worktree-ownership.test.ts deleted file mode 100644 index 5041686ea7f..00000000000 --- a/src/main/persistence/restoring-sessions/session-worktree-ownership.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' - -import { collectWorkspaceSessionWorktreeOwners } from './session-worktree-ownership' - -function sessionWith(field: keyof WorkspaceSessionState, value: unknown): WorkspaceSessionState { - return { ...getDefaultWorkspaceSession(), [field]: value } as WorkspaceSessionState -} - -describe('workspace session worktree ownership', () => { - it('prefers an exact candidate id over workspace-key prefix parsing', () => { - const prefixedId = 'folder::/workspace/target' - const session = sessionWith('tabsByWorktree', { [prefixedId]: [] }) - - expect([...collectWorkspaceSessionWorktreeOwners(session, new Set([prefixedId]))]).toEqual([ - prefixedId - ]) - }) - - it('matches canonically equivalent Unicode worktree owners', () => { - const candidateId = 'repo-1::/workspace/Café'.normalize('NFC') - const ownerId = candidateId.normalize('NFD') - const session = sessionWith('activeWorktreeId', ownerId) - - expect([...collectWorkspaceSessionWorktreeOwners(session, new Set([candidateId]))]).toEqual([ - candidateId - ]) - }) - - it('matches Windows worktree owners across drive case and slash spelling', () => { - const candidateId = 'repo-1::D:/Agentic/game2' - const session = sessionWith('activeWorktreeId', 'repo-1::d:\\agentic\\game2') - - expect([...collectWorkspaceSessionWorktreeOwners(session, new Set([candidateId]))]).toEqual([ - candidateId - ]) - }) - - it('matches macOS /private/tmp session owners to /tmp metadata', () => { - const candidateId = 'repo-1::/private/tmp/orca/target' - const session = sessionWith('activeWorktreeId', 'repo-1::/tmp/orca/target') - - expect([ - ...collectWorkspaceSessionWorktreeOwners(session, new Set([candidateId]), 'darwin') - ]).toEqual([candidateId]) - }) - - it('preserves every candidate that shares an owner comparison key', () => { - const nfcId = 'repo-1::/workspace/Café'.normalize('NFC') - const nfdId = nfcId.normalize('NFD') - const session = sessionWith('activeWorktreeId', nfcId) - - expect( - [...collectWorkspaceSessionWorktreeOwners(session, new Set([nfcId, nfdId]))].sort() - ).toEqual([nfcId, nfdId].sort()) - }) -}) diff --git a/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts b/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts deleted file mode 100644 index 8fb19067b63..00000000000 --- a/src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDefaultPersistedState } from '../../../shared/constants' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { Repo } from '../../../shared/repo-types' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { - captureNativeLocalWorktreeMetadataScanExpectation, - pruneSessionlessMissingLocalWorktreeMetadataForRepo -} from './missing-local-worktree-metadata-pruning' - -const REPO_ID = 'repo-1' -const WORKTREE_ID = `${REPO_ID}::/workspace/stale` -const LOCAL_ALIAS = `local|${WORKTREE_ID}` -const IDENTITY_KEY = 'local-identity' - -function makeRepo(id = REPO_ID): Repo { - return { - id, - path: `/workspace/${id}`, - displayName: id, - badgeColor: '#000', - addedAt: 0 - } -} - -function makeMeta(worktreeId = WORKTREE_ID): WorktreeMeta { - return { - instanceId: `instance-${worktreeId}`, - hostId: 'local', - displayName: worktreeId, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 - } -} - -function makeState(): PersistedState { - const state = getDefaultPersistedState('/home/test') - state.repos = [makeRepo()] - return state -} - -function makeCanonicalOnlyState(): { - state: PersistedState - meta: WorktreeMeta -} { - const state = makeState() - const meta = makeMeta() - state.worktreeMetaByIdentity = { [IDENTITY_KEY]: meta } - state.worktreeIdentityAliases = { [LOCAL_ALIAS]: [IDENTITY_KEY] } - return { state, meta } -} - -function pruneCaptured(state: PersistedState): string[] { - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - return pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata) -} - -describe('local worktree metadata scan expectations', () => { - it('captures canonical-only local metadata and removes its orphaned identity row', () => { - const { state } = makeCanonicalOnlyState() - - expect(pruneCaptured(state)).toEqual([WORKTREE_ID]) - expect(state.worktreeMeta[WORKTREE_ID]).toBeUndefined() - expect(state.worktreeIdentityAliases?.[LOCAL_ALIAS]).toBeUndefined() - expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeUndefined() - }) - - it('does not sweep an unrelated unaliased canonical row during pruning', () => { - const { state, meta } = makeCanonicalOnlyState() - const unrelated = makeMeta(`${REPO_ID}::/workspace/unrelated`) - state.worktreeMetaByIdentity!.unrelated = unrelated - - expect(pruneCaptured(state)).toEqual([WORKTREE_ID]) - expect(state.worktreeMetaByIdentity).toEqual({ unrelated }) - expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).not.toBeDefined() - expect(meta).not.toBe(unrelated) - }) - - it('preserves metadata when an alias array is replaced with identical contents', () => { - const { state } = makeCanonicalOnlyState() - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - state.worktreeIdentityAliases![LOCAL_ALIAS] = [IDENTITY_KEY] - - expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual( - [] - ) - expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeDefined() - }) - - it.each([ - [ - 'added', - (state: PersistedState) => { - state.worktreeIdentityAliases![`ssh:builder|${WORKTREE_ID}`] = [IDENTITY_KEY] - } - ], - [ - 'removed', - (state: PersistedState) => { - delete state.worktreeIdentityAliases![LOCAL_ALIAS] - } - ] - ] as const)('preserves metadata when an alias is %s during the scan', (_label, mutate) => { - const { state } = makeCanonicalOnlyState() - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - mutate(state) - - expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual( - [] - ) - expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeDefined() - }) - - it('preserves a legacy row created after a canonical-only scan capture', () => { - const { state } = makeCanonicalOnlyState() - const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!) - state.worktreeMeta[WORKTREE_ID] = makeMeta() - - expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual( - [] - ) - expect(state.worktreeMeta[WORKTREE_ID]).toBeDefined() - }) -}) diff --git a/src/main/persistence/tracking-repos/persistence-workspace-attachments.test.ts b/src/main/persistence/tracking-repos/persistence-workspace-attachments.test.ts deleted file mode 100644 index cf2da270807..00000000000 --- a/src/main/persistence/tracking-repos/persistence-workspace-attachments.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import { - closeTestStores, - createStore, - makeRepo, - testState, - writeDataFile -} from '../persistence-test-harness' -import { getWorkspaceAttachments } from '../../../shared/workspace-attachments/workspace-attachments' -import type { WorkspaceAttachment } from '../../../shared/worktree/types' -import { mergeWorktree } from '../../ipc/worktree-metadata-merge' -import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' - -vi.mock('electron', () => ({ - app: { getPath: () => testState.dir }, - safeStorage: { - isEncryptionAvailable: () => false - } -})) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) -const pr = (number: number): WorkspaceAttachment => ({ provider: 'github', type: 'pr', number }) - -describe('workspace attachment persistence', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-attachments-')) - }) - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('round-trips collections and active selection through host-qualified metadata and git projections', async () => { - writeDataFile({ repos: [makeRepo({ id: 'repo', path: '/work', connectionId: 'test' })] }) - const store = await createStore() - store.setWorktreeMeta(hostWorktreeTarget({ id: 'repo::/work', hostId: 'ssh:test' }), { - linkedPR: 7 - }) - store.setWorktreeMeta(hostWorktreeTarget({ id: 'repo::/work', hostId: 'ssh:test' }), { - linkedPR: 8 - }) - store.flush() - const restored = await createStore() - const meta = restored.getWorktreeMetaForHost('repo::/work', 'ssh:test') - expect(meta?.linkedItems).toEqual([pr(7), pr(8)]) - expect(meta?.linkedPR).toBe(8) - const projected = mergeWorktree( - 'repo', - { path: '/work', head: 'abc', branch: 'feature', isBare: false, isMainWorktree: false }, - meta - ) - expect(projected.linkedItems).toEqual([pr(7), pr(8)]) - expect( - restored.setWorktreeMeta(hostWorktreeTarget({ id: 'repo::/work', hostId: 'ssh:test' }), { - linkedItems: [pr(7)] - }).linkedPR - ).toBe(7) - restored.flush() - expect( - (await createStore()).getWorktreeMetaForHost('repo::/work', 'ssh:test')?.linkedItems - ).toEqual([pr(7)]) - }) - - it('loads scalar-only metadata and repairs malformed duplicate collection entries', async () => { - writeDataFile({ - worktreeMeta: { - legacy: { linkedPR: 7 }, - repaired: { linkedPR: 7, linkedItems: [pr(7), null, {}, pr(7), pr(8)] } - } - }) - const store = await createStore() - expect(getWorkspaceAttachments(store.getWorktreeMeta('legacy'))).toEqual([pr(7)]) - expect(store.getWorktreeMeta('repaired')?.linkedItems).toEqual([pr(7), pr(8)]) - store.setWorktreeMeta(hostWorktreeTarget({ id: 'legacy', hostId: 'local' }), { linkedPR: 8 }) - expect(store.getWorktreeMeta('legacy')?.linkedItems).toEqual([pr(7), pr(8)]) - }) - - it('retains multiple repo-less folder tasks and clears the active task when its collection is emptied', async () => { - const store = await createStore() - const group = store.createProjectGroup({ - name: 'Docs', - parentPath: '/docs', - createdFrom: 'folder-scan' - }) - const task = (number: number) => ({ - provider: 'github' as const, - type: 'issue' as const, - number, - title: `Issue ${number}`, - url: `https://github.com/a/docs/issues/${number}` - }) - const workspace = store.createFolderWorkspace({ projectGroupId: group.id, linkedTask: task(7) }) - store.updateFolderWorkspace(workspace.id, { linkedTask: task(8) }) - expect(workspace.linkedItems).toHaveLength(2) - store.flush() - const restored = await createStore() - expect(restored.getFolderWorkspace(workspace.id)?.linkedItems).toHaveLength(2) - expect(restored.updateFolderWorkspace(workspace.id, { linkedItems: [] })?.linkedTask).toBeNull() - restored.flush() - expect((await createStore()).getFolderWorkspace(workspace.id)?.linkedItems).toEqual([]) - }) - it('applies stale client add/remove deltas atomically for worktrees and folders', async () => { - const store = await createStore() - store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), { - linkedItems: [pr(1)] - }) - const firstClient = { linkedItemsBase: [pr(1)], linkedItems: [pr(1), pr(2)] } - const secondClient = { linkedItemsBase: [pr(1)], linkedItems: [pr(3)] } - store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), firstClient) - store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), secondClient) - expect(store.getWorktreeMeta('wt')?.linkedItems).toEqual([pr(2), pr(3)]) - expect(store.getWorktreeMeta('wt')).not.toHaveProperty('linkedItemsBase') - const group = store.createProjectGroup({ - name: 'Folder', - parentPath: '/docs', - createdFrom: 'folder-scan' - }) - const folder = store.createFolderWorkspace({ projectGroupId: group.id, linkedItems: [pr(1)] }) - store.updateFolderWorkspace(folder.id, firstClient) - store.updateFolderWorkspace(folder.id, secondClient) - expect(folder.linkedItems).toEqual([pr(2), pr(3)]) - expect(folder).not.toHaveProperty('linkedItemsBase') - store.flush() - const restored = await createStore() - expect(restored.getWorktreeMeta('wt')?.linkedItems).toEqual([pr(2), pr(3)]) - expect(restored.getFolderWorkspace(folder.id)?.linkedItems).toEqual([pr(2), pr(3)]) - }) - - it('keeps the current review target when a stale collection edit resolved another review', async () => { - const store = await createStore() - const currentTarget = { remoteName: 'origin', branchName: 'pr-2' } - store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), { - linkedItems: [pr(2)], - linkedPR: 2, - pushTarget: currentTarget - }) - store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), { - linkedItemsBase: [], - linkedItems: [pr(1)], - linkedPR: 1, - linkedItemsSelectionChanged: false, - pushTarget: { remoteName: 'origin', branchName: 'pr-1' } - }) - expect(store.getWorktreeMeta('wt')).toMatchObject({ - linkedPR: 2, - linkedItems: [pr(2), pr(1)], - pushTarget: currentTarget - }) - store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), { - linkedItemsBase: [pr(2), pr(1)], - linkedItems: [pr(2), pr(1)], - linkedPR: 1, - linkedItemsSelectionChanged: true, - pushTarget: { remoteName: 'origin', branchName: 'pr-1' } - }) - expect(store.getWorktreeMeta('wt')).toMatchObject({ - linkedPR: 1, - pushTarget: { remoteName: 'origin', branchName: 'pr-1' } - }) - }) -}) diff --git a/src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts b/src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts deleted file mode 100644 index c41bd686ced..00000000000 --- a/src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { WORKTREE_META_PERSISTED_DEFAULTS } from '../../../shared/worktree/metadata/meta-persisted-defaults' -import type { PersistedState } from '../../../shared/persisted-state-types' -import { - gcStaleWorktreeMeta, - normalizeWorktreeLinkedItemMetadata -} from './worktree-metadata-normalization' - -// Surviving rows must restore the defaults omitted by serialization. -function makeMeta(): WorktreeMeta { - return { createdAt: 1, ...WORKTREE_META_PERSISTED_DEFAULTS } as WorktreeMeta -} - -function makeState(overrides: Partial): PersistedState { - return { - worktreeMeta: {}, - worktreeLineageById: {}, - workspaceLineageByChildKey: {}, - ...overrides - } as PersistedState -} - -describe('normalizeWorktreeLinkedItemMetadata', () => { - it('drops malformed canonical metadata entries', () => { - const state = makeState({ - worktreeMetaByIdentity: { - valid: makeMeta(), - malformed: null - } as unknown as PersistedState['worktreeMetaByIdentity'], - worktreeIdentityAliases: { 'local|r1::/tmp/wt': ['valid', 'malformed'] } - }) - - expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) - expect(state.worktreeIdentityAliases).toEqual({ 'local|r1::/tmp/wt': ['valid'] }) - }) - - it('preserves every host canonical row when one legacy locator row is malformed', () => { - const localKey = 'wt2:local:local-instance' - const remoteKey = 'wt2:ssh%3Abuilder:remote-instance' - const worktreeId = 'r1::/tmp/wt' - const state = makeState({ - worktreeMeta: { [worktreeId]: null } as unknown as PersistedState['worktreeMeta'], - worktreeMetaByIdentity: { [localKey]: makeMeta(), [remoteKey]: makeMeta() }, - worktreeIdentityAliases: { - [`local|${worktreeId}`]: [localKey], - [`ssh:builder|${worktreeId}`]: [remoteKey] - } - }) - - expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) - expect(state.worktreeMeta).toEqual({}) - expect(state.worktreeIdentityAliases).toEqual({ - [`local|${worktreeId}`]: [localKey], - [`ssh:builder|${worktreeId}`]: [remoteKey] - }) - }) - - it('preserves valid canonical state when the whole legacy projection is malformed', () => { - const identityKey = 'wt2:ssh%3Abuilder:remote-instance' - const alias = 'ssh:builder|r1::/tmp/wt' - const state = makeState({ - worktreeMeta: null as unknown as PersistedState['worktreeMeta'], - worktreeMetaByIdentity: { [identityKey]: makeMeta() }, - worktreeIdentityAliases: { [alias]: [identityKey] } - }) - - expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) - expect(state.worktreeMeta).toEqual({}) - expect(state.worktreeIdentityAliases).toEqual({ [alias]: [identityKey] }) - }) - - it('prunes canonical metadata left unreachable by dangling-alias cleanup', () => { - const liveKey = 'wt2:local:live' - const orphanKey = 'wt2:local:orphan' - const state = makeState({ - worktreeMetaByIdentity: { [liveKey]: makeMeta(), [orphanKey]: makeMeta() }, - worktreeIdentityAliases: { - 'local|r1::/tmp/live': [liveKey], - 'local|r1::/tmp/dangling': ['missing-key'] - } - }) - - expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true) - expect(state.worktreeIdentityAliases).toEqual({ 'local|r1::/tmp/live': [liveKey] }) - }) -}) - -describe('gcStaleWorktreeMeta', () => { - it('keeps an archived workspace whose checkout was deleted on purpose', () => { - const worktreeId = 'r1::/definitely/missing/orca/archived' - const state = makeState({ - repos: [], - projects: [], - worktreeMeta: { - [worktreeId]: { - ...makeMeta(), - hostId: 'local', - comment: 'resume after review', - isArchived: true, - archivedCheckout: { branch: 'feature/archived', archivedAt: 1 }, - // Epoch-start activity is past any grace period, so only the archive mark keeps it. - lastActivityAt: 1 - } - } - }) - - expect(gcStaleWorktreeMeta(state)).toBe(0) - expect(state.worktreeMeta[worktreeId]?.comment).toBe('resume after review') - }) -}) diff --git a/src/main/plugins/catalog/plugin-kill-list-service.test.ts b/src/main/plugins/catalog/plugin-kill-list-service.test.ts deleted file mode 100644 index 1b183b7668b..00000000000 --- a/src/main/plugins/catalog/plugin-kill-list-service.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PluginKillList } from '../../../shared/plugins/catalog/plugin-kill-list' -import { PLUGIN_KILL_LIST_RETRY_MS, PluginKillListService } from './plugin-kill-list-service' - -const roots: string[] = [] - -async function tempRoot(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-plugin-kill-list-')) - roots.push(root) - return root -} - -function killList(date = '2026-07-12T20:00:00Z'): PluginKillList { - return { - version: 1, - generatedAt: date, - plugins: [{ pluginKey: 'community.unsafe', reason: 'Malware advisory' }] - } -} - -afterEach(async () => { - vi.useRealTimers() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('PluginKillListService', () => { - it('loads cached revocations before any network refresh', async () => { - const root = await tempRoot() - const first = new PluginKillListService({ - pluginsDataDir: root, - fetcher: async () => killList() - }) - await first.refresh() - const fetcher = vi.fn(async () => killList()) - const restarted = new PluginKillListService({ pluginsDataDir: root, fetcher }) - - await restarted.initialize() - - expect(restarted.reason('community.unsafe')).toBe('Malware advisory') - expect(fetcher).not.toHaveBeenCalled() - }) - - it('keeps accepting genuine lists after a far-future snapshot is published', async () => { - const root = await tempRoot() - const fetcher = vi - .fn<() => Promise>() - .mockResolvedValueOnce(killList('9999-12-31T23:59:59Z')) - .mockResolvedValueOnce(killList('2026-07-12T20:00:00Z')) - const service = new PluginKillListService({ pluginsDataDir: root, fetcher }) - - await expect(service.refresh()).rejects.toThrow() - await expect(service.refresh()).resolves.toMatchObject({ - generatedAt: '2026-07-12T20:00:00Z' - }) - expect(service.reason('community.unsafe')).toBe('Malware advisory') - const restarted = new PluginKillListService({ pluginsDataDir: root, fetcher }) - await restarted.initialize() - expect(restarted.snapshot()?.generatedAt).toBe('2026-07-12T20:00:00Z') - }) - - it('keeps cached revocations live when the device clock runs far behind', async () => { - const root = await tempRoot() - const generatedAt = new Date().toISOString() - const published = new PluginKillListService({ - pluginsDataDir: root, - fetcher: async () => killList(generatedAt) - }) - await published.refresh() - // A skewed RTC/restored VM clock must not undo cached revocation. - vi.useFakeTimers() - vi.setSystemTime(new Date(Date.parse(generatedAt) - 30 * 24 * 60 * 60 * 1000)) - const restarted = new PluginKillListService({ - pluginsDataDir: root, - fetcher: async () => killList(generatedAt) - }) - - await restarted.initialize() - - expect(restarted.snapshot()?.generatedAt).toBe(generatedAt) - expect(restarted.reason('community.unsafe')).toBe('Malware advisory') - // Refused refreshes must preserve existing revocation. - await expect(restarted.refresh()).rejects.toThrow() - expect(restarted.reason('community.unsafe')).toBe('Malware advisory') - }) - - it('refreshes periodically while plugins are on so long sessions see revocations', async () => { - vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }) - let revoked = false - const service = new PluginKillListService({ - pluginsDataDir: await tempRoot(), - fetcher: async () => - revoked - ? killList('2026-07-13T20:00:00Z') - : { version: 1, generatedAt: '2026-07-12T20:00:00Z', plugins: [] } - }) - await service.refresh() - const changed = vi.fn() - service.onChanged(changed) - service.syncPeriodicRefresh(true, 1000) - service.syncPeriodicRefresh(true, 1000) - revoked = true - - vi.advanceTimersByTime(1000) - await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1)) - expect(service.reason('community.unsafe')).toBe('Malware advisory') - - service.syncPeriodicRefresh(false) - vi.advanceTimersByTime(5000) - await Promise.resolve() - expect(changed).toHaveBeenCalledTimes(1) - expect(vi.getTimerCount()).toBe(0) - }) -}) - -describe('PluginKillListService retry', () => { - it('retries 15 minutes after a failed refresh instead of waiting a full interval', async () => { - vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'] }) - let online = false - const service = new PluginKillListService({ - pluginsDataDir: await tempRoot(), - fetcher: async () => { - if (!online) { - throw new Error('offline') - } - return killList() - } - }) - service.syncPeriodicRefresh(true) - await expect(service.refresh()).rejects.toThrow('offline') - online = true - await vi.advanceTimersByTimeAsync(PLUGIN_KILL_LIST_RETRY_MS) - await vi.waitFor(() => expect(service.reason('community.unsafe')).toBe('Malware advisory')) - service.dispose() - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/main/plugins/view/plugin-view-target.test.ts b/src/main/plugins/view/plugin-view-target.test.ts deleted file mode 100644 index 9920d0aaa36..00000000000 --- a/src/main/plugins/view/plugin-view-target.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - PluginHostListEntry, - PluginHostStatus -} from '../../../shared/plugins/plugin-list-entry' -import type { ValidDiscoveredPlugin } from '../discovery/plugin-discovery' -import { - resolvePluginViewEditor, - resolvePluginViewPanel, - type PluginViewSource -} from './plugin-view-target' - -const KEY = 'acme.todos' - -function source( - status: PluginHostStatus, - contributes: { panels?: unknown[]; customEditors?: unknown[] } = {} -): PluginViewSource { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resolver reads only pluginKey, status and error. - const entry = { pluginKey: KEY, status, error: 'boom' } as PluginHostListEntry - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resolver reads only rootDir, contentHash and these contributions. - const plugin = { - pluginKey: KEY, - rootDir: '/plugins/acme.todos', - contentHash: `sha256-${'a'.repeat(64)}`, - manifest: { - contributes: { - panels: contributes.panels ?? [], - customEditors: contributes.customEditors ?? [] - } - } - } as unknown as ValidDiscoveredPlugin - return { - list: async () => [entry], - findValidPlugin: (key) => (key === KEY ? plugin : null) - } -} - -const PANELS = [ - { id: 'todos', title: 'Todos', entry: 'src/panel.tsx', ui: 'components' }, - { id: 'stats', title: 'Stats', entry: 'stats.html' } -] - -describe('resolvePluginViewPanel', () => { - it('defaults to the first panel and stamps the guest revision', async () => { - await expect( - resolvePluginViewPanel(source('idle', { panels: PANELS }), KEY, undefined) - ).resolves.toEqual({ - pluginKey: KEY, - panelId: 'todos', - title: 'Todos', - ui: 'components', - guestRevision: 'sha256-aaaaaaaaa' - }) - await expect( - resolvePluginViewPanel(source('running', { panels: PANELS }), KEY, 'stats') - ).resolves.toMatchObject({ panelId: 'stats', ui: 'html' }) - }) - - it('names the panels it has when the id is wrong', async () => { - await expect( - resolvePluginViewPanel(source('idle', { panels: PANELS }), KEY, 'nope') - ).rejects.toMatchObject({ - code: 'invalid_argument', - data: { nextSteps: ['Its panels: todos, stats.'] } - }) - await expect(resolvePluginViewPanel(source('idle'), KEY, undefined)).rejects.toThrow( - /contributes no panels/ - ) - }) - - it('refuses an unknown plugin and one that is not running', async () => { - await expect( - resolvePluginViewPanel(source('idle', { panels: PANELS }), 'acme.other', undefined) - ).rejects.toMatchObject({ code: 'plugin_not_found' }) - await expect( - resolvePluginViewPanel(source('pending', { panels: PANELS }), KEY, undefined) - ).rejects.toThrow(/waiting for approval/) - await expect( - resolvePluginViewPanel(source('errored', { panels: PANELS }), KEY, undefined) - ).rejects.toThrow(/is errored: boom/) - }) -}) - -describe('resolvePluginViewEditor', () => { - const editors = [{ id: 'notes', title: 'Notes', extensions: ['.notes'], filenames: [] }] - - it('picks the first editor that takes the file', async () => { - await expect( - resolvePluginViewEditor(source('idle', { customEditors: editors }), KEY, '/w/plan.notes') - ).resolves.toEqual({ pluginKey: KEY, editorId: 'notes', title: 'Notes' }) - }) - - it('says which files its editors open when none takes this one', async () => { - await expect( - resolvePluginViewEditor(source('idle', { customEditors: editors }), KEY, '/w/plan.md') - ).rejects.toMatchObject({ data: { nextSteps: ['notes opens *.notes.'] } }) - await expect(resolvePluginViewEditor(source('idle'), KEY, '/w/a.md')).rejects.toThrow( - /no custom editors/ - ) - }) -}) diff --git a/src/renderer/src/components/artifacts/ArtifactPreview.test.tsx b/src/renderer/src/components/artifacts/ArtifactPreview.test.tsx deleted file mode 100644 index c0fe35da001..00000000000 --- a/src/renderer/src/components/artifacts/ArtifactPreview.test.tsx +++ /dev/null @@ -1,81 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' -import { act, cleanup, render, screen, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ArtifactPreview } from './ArtifactPreview' - -function dispatchLoadFailure( - webview: Element, - failure: { errorCode: number; isMainFrame: boolean } -): void { - const event = new Event('did-fail-load') - Object.assign(event, { - errorCode: failure.errorCode, - errorDescription: 'failed', - validatedURL: 'https://share.onorca.dev/a/report', - isMainFrame: failure.isMainFrame - }) - webview.dispatchEvent(event) -} - -describe('ArtifactPreview', () => { - beforeEach(() => { - Object.assign(window, { - api: { - browser: { sessionResolvePartition: vi.fn().mockResolvedValue('persist:orca-default') } - } - }) - }) - - afterEach(() => { - vi.useRealTimers() - cleanup() - }) - - it('ignores child-frame failures and aborted navigations', async () => { - render() - const webview = await waitFor(() => { - const element = document.querySelector('webview') - expect(element).not.toBeNull() - if (!element) { - throw new Error('preview webview not attached') - } - return element - }) - - act(() => dispatchLoadFailure(webview, { errorCode: -105, isMainFrame: false })) - expect(screen.queryByText('Preview unavailable')).not.toBeInTheDocument() - act(() => dispatchLoadFailure(webview, { errorCode: -3, isMainFrame: true })) - expect(screen.queryByText('Preview unavailable')).not.toBeInTheDocument() - act(() => webview.dispatchEvent(new Event('did-stop-loading'))) - expect(screen.queryByText('Preview unavailable')).not.toBeInTheDocument() - - act(() => dispatchLoadFailure(webview, { errorCode: -105, isMainFrame: true })) - expect(screen.getByText('Preview unavailable')).toBeInTheDocument() - }) - - it('stops waiting when navigation stalls', async () => { - vi.useFakeTimers() - render() - await act(async () => { - await Promise.resolve() - await Promise.resolve() - }) - expect(document.querySelector('webview')).not.toBeNull() - - act(() => vi.advanceTimersByTime(20_000)) - - expect(screen.getByText('Preview unavailable')).toBeInTheDocument() - }) - - it('stops waiting when preview-session resolution stalls', () => { - vi.useFakeTimers() - vi.mocked(window.api.browser.sessionResolvePartition).mockReturnValue(new Promise(() => {})) - render() - - act(() => vi.advanceTimersByTime(20_000)) - - expect(screen.getByText('Preview unavailable')).toBeInTheDocument() - }) -}) diff --git a/src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts b/src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts deleted file mode 100644 index 30d1de67d08..00000000000 --- a/src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createHoverPreviewCache } from './native-chat-hover-preview-cache' - -describe('createHoverPreviewCache', () => { - it('starts a fresh request after the pending binding retires and preserves its replacement', async () => { - const cache = createHoverPreviewCache({ freshMs: 60_000, maxEntries: 100 }) - let live = true - let finish: (value: string) => void = () => {} - const old = cache.load( - 'a', - () => new Promise((resolve) => (finish = resolve)), - () => live - ) - live = false - let finishNew: (value: string) => void = () => {} - const current = cache.load('a', () => new Promise((resolve) => (finishNew = resolve))) - finish('old') - expect(await old).toBeNull() - const joined = cache.load('a', async () => 'unexpected') - finishNew('new') - expect(await current).toBe('new') - expect(await joined).toBe('new') - expect(cache.read('a')).toBe('new') - }) - - it('coalesces pending requests while their binding remains live', async () => { - const cache = createHoverPreviewCache({ freshMs: 60_000, maxEntries: 100 }) - let finish: (value: string) => void = () => {} - const first = cache.load( - 'a', - () => new Promise((resolve) => (finish = resolve)), - () => true - ) - const second = cache.load( - 'a', - async () => 'unexpected', - () => true - ) - finish('result') - expect(await first).toBe('result') - expect(await second).toBe('result') - }) - - it('does not publish a response whose owner rejects it at cache commit', async () => { - const cache = createHoverPreviewCache({ freshMs: 60_000, maxEntries: 100 }) - const response = Promise.withResolvers() - let current = true - const pending = cache.load( - 'alice', - () => response.promise, - () => current - ) - response.resolve('bob response') - current = false - await expect(pending).resolves.toBeNull() - expect(cache.read('alice')).toBeNull() - }) - - it('keeps the last answer through a reread that fails, and rereads past one started earlier', async () => { - const cache = createHoverPreviewCache({ freshMs: 60_000, maxEntries: 100 }) - await cache.load('pr', async () => 'closed') - let finishEarly: (value: string) => void = () => {} - cache.expire('pr') - const early = cache.load('pr', () => new Promise((resolve) => (finishEarly = resolve))) - expect(cache.read('pr')).toBe('closed') - - // The chat reopened the pull request while that read was out. - cache.expire('pr') - const after = cache.load('pr', async () => 'open') - finishEarly('closed') - await early - expect(await after).toBe('open') - expect(cache.read('pr')).toBe('open') - - cache.expire('pr') - await cache.load('pr', async () => null) - expect(cache.read('pr')).toBe('open') - }) -}) diff --git a/src/renderer/src/components/native-chat/session/options/structured/use-structured-agent-session-options.interaction-mode.test.tsx b/src/renderer/src/components/native-chat/session/options/structured/use-structured-agent-session-options.interaction-mode.test.tsx deleted file mode 100644 index bc421ee5fa5..00000000000 --- a/src/renderer/src/components/native-chat/session/options/structured/use-structured-agent-session-options.interaction-mode.test.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof' -// @vitest-environment happy-dom -import { - answer, - mutateWith, - renderOptions, - REOPENED, - currentValue -} from './use-structured-agent-session-options.test-fixture' -import { forgetStructuredSessionSelection } from '@/lib/agent-session/options/structured-agent-session-selection-controller' - -import { act, waitFor } from '@testing-library/react' -import { expect, it, vi } from 'vitest' - -vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (importOriginal) => ({ - ...(await importOriginal()), - runtimeEnvironmentSupportsCapability: async () => true -})) - -it('projects transmitted mode admission to the optimistic exit control and recovers after settlement', async () => { - const sessionId = 'mode-admission-projection' - forgetStructuredSessionSelection(sessionId) - let interactionMode: 'default' | 'plan' = 'default' - const reply = Promise.withResolvers<{ - key: string - value: string - options: Record - }>() - answer({ - options: async () => ({ - models: [], - current: { interactionMode, acceptedInputSources: { interactionMode: 'saved' } } - }) - }) - const { mutate } = mutateWith(async (_method, _fingerprint, fields) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the option writer sends the fixture its key/value fields. - const pick = fields as { key: string; value: string } - return pick.key === 'interactionMode' ? reply.promise : { key: pick.key, value: pick.value } - }) - const hook = renderOptions({ ...REOPENED, sessionId }, mutate) - try { - await waitFor(() => - expect(hook.result.current.optionSurface.admits?.('interactionMode', 'plan')).toBe(true) - ) - let pending: Promise | undefined - act(() => { - pending = hook.result.current.setStructuredOption('interactionMode', 'plan') - }) - await waitFor(() => - expect(currentValue(hook.result.current.optionSnapshot, 'interactionMode')).toBe('plan') - ) - expect( - hook.result.current.optionSnapshot.find((entry) => entry.id === 'interactionMode')?.settable - ).toBe(false) - await act(async () => { - await hook.result.current.setStructuredOption('effort', 'high') - }) - expect( - hook.result.current.optionSnapshot.find((entry) => entry.id === 'interactionMode')?.settable - ).toBe(false) - interactionMode = 'plan' - await act(async () => { - reply.resolve({ key: 'interactionMode', value: 'plan', options: { interactionMode: 'plan' } }) - await pending - }) - await waitFor(() => - expect( - hook.result.current.optionSnapshot.find((entry) => entry.id === 'interactionMode')?.settable - ).toBe(true) - ) - } finally { - hook.unmount() - forgetStructuredSessionSelection(sessionId) - } -}) diff --git a/src/renderer/src/components/native-chat/session/status/use-native-chat-hook-status.test.ts b/src/renderer/src/components/native-chat/session/status/use-native-chat-hook-status.test.ts deleted file mode 100644 index e966c85d1fb..00000000000 --- a/src/renderer/src/components/native-chat/session/status/use-native-chat-hook-status.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../../shared/agent-status/contracts/agent-status-freshness' -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' - -vi.mock('@/store', async () => { - const { createTestStore } = await import('@/store/testing/app-store-test-fixture') - return { useAppStore: createTestStore() } -}) - -import { useAppStore } from '@/store' -import { useNativeChatHookStatus } from './use-native-chat-hook-status' -import { useNativeChatTerminalTurnTiming } from '../../conversation/turns/use-native-chat-terminal-turn-timing' - -afterEach(() => { - cleanup() - for (const key of Object.keys(useAppStore.getState().agentStatusByPaneKey)) { - useAppStore.getState().removeAgentStatus(key) - } - vi.useRealTimers() -}) - -it('preserves its pane status across another pane update and observes its own status and expiry', async () => { - vi.useFakeTimers() - const start = AGENT_STATUS_STALE_AFTER_MS * 10 - vi.setSystemTime(start) - const messages: NativeChatMessage[] = [ - { id: 'turn', role: 'user', blocks: [], timestamp: start, source: 'transcript' } - ] - const store = useAppStore.getState() - for (const paneKey of ['own:1', 'other:1']) { - store.setAgentStatus( - paneKey, - { state: 'working', prompt: 'task', agentType: 'claude' }, - undefined, - { updatedAt: start, evidenceObservedAt: start, turnStartedAt: start } - ) - } - const status = renderHook(() => useNativeChatHookStatus('own:1')) - const timing = renderHook(() => useNativeChatTerminalTurnTiming('own:1', messages, false)) - act(() => { - store.setAgentStatus('other:1', { state: 'done', prompt: 'task' }) - useAppStore.setState((state) => ({ agentStatusEpoch: state.agentStatusEpoch + 1 })) - }) - expect(status.result.current[0]).toBe('working') - act(() => { - vi.setSystemTime(start + 5_000) - store.setAgentStatus('own:1', { state: 'done', prompt: 'task' }, undefined, { - turnStartedAt: start - }) - }) - expect(status.result.current[0]).toBe('done') - expect(timing.result.current.settledTurns.get('turn')).toEqual({ - startedAt: start, - workedSeconds: 5 - }) - act(() => store.setAgentStatus('own:1', { state: 'working', prompt: 'next task' })) - const entry = useAppStore.getState().agentStatusByPaneKey['own:1'] - await act(async () => { - await new Promise((resolve) => queueMicrotask(resolve)) - vi.advanceTimersByTime(AGENT_STATUS_STALE_AFTER_MS + 1) - }) - expect(useAppStore.getState().agentStatusByPaneKey['own:1']).toBe(entry) - expect(status.result.current[0]).toBeNull() - expect(timing.result.current.settledTurns.get('turn')).toBeNull() -}) diff --git a/src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-retained-session.test.ts b/src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-retained-session.test.ts deleted file mode 100644 index 344b43797ec..00000000000 --- a/src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-retained-session.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -// @vitest-environment happy-dom - -import { act, createElement } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatMessage } from '../../../../../../../shared/native-chat/native-chat-types' -import type { - NativeChatLiveSession, - UseNativeChatLiveSessionArgs -} from './native-chat-live-session-contract' - -const { liveSession } = vi.hoisted(() => ({ liveSession: vi.fn() })) - -vi.mock('./use-native-chat-live-session', () => ({ useNativeChatLiveSession: liveSession })) - -import { useNativeChatRetainedSession } from './use-native-chat-retained-session' - -const ARGS: UseNativeChatLiveSessionArgs = { - paneKey: 'tab:leaf', - agent: 'claude', - sessionId: 'session', - runtimeEnvironmentId: 'owner-a' -} - -function message(id: string): NativeChatMessage { - return { id, role: 'assistant', blocks: [], timestamp: 0, source: 'transcript' } -} - -function session( - readPhase: NativeChatLiveSession['readPhase'], - messages: NativeChatMessage[], - sessionId: string | null = 'session' -): NativeChatLiveSession { - return { - agent: 'claude', - sessionId, - messages, - status: readPhase === 'loading' ? 'loading' : 'ready', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase - } -} - -describe('useNativeChatRetainedSession', () => { - let root: Root | null = null - let latest: NativeChatLiveSession | null = null - - function Probe(props: UseNativeChatLiveSessionArgs): null { - latest = useNativeChatRetainedSession(props) - return null - } - - async function render(props: UseNativeChatLiveSessionArgs): Promise { - if (!root) { - root = createRoot(document.createElement('div')) - } - await act(async () => root?.render(createElement(Probe, props))) - } - - afterEach(() => { - act(() => root?.unmount()) - root = null - latest = null - liveSession.mockReset() - }) - it.each(['loading', 'error'] as const)( - 'releases expanded fallback rows during %s', - async (phase) => { - const rows = Array.from({ length: 800 }, (_, index) => message(`row-${index}`)) - liveSession.mockReturnValue(session('ready', rows)) - await render(ARGS) - const trimHistory = vi.fn() - liveSession.mockReturnValue({ ...session(phase, []), trimHistory }) - await render(ARGS) - expect(latest?.messages).toHaveLength(800) - act(() => latest?.trimHistory?.()) - liveSession.mockReturnValue({ ...session(phase, []), trimHistory, olderHistoryGeneration: 1 }) - await render(ARGS) - expect(latest?.messages).toHaveLength(300) - expect(latest?.messages[0]?.id).toBe('row-500') - expect(latest?.messages.at(-1)?.id).toBe('row-799') - expect(trimHistory).toHaveBeenCalledOnce() - } - ) -}) diff --git a/src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx b/src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx deleted file mode 100644 index 1cc96a6bc2d..00000000000 --- a/src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx +++ /dev/null @@ -1,74 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentSessionCancelResult } from '../../../../../../shared/agent-session/agent-session-wire' -import type { AgentChildWorkView } from '../../../../../../shared/agent-status/child-work/agent-status-child-work-view' -import { structuredSessionBackgroundTasksView } from '../../../../../../shared/structured-session-background-tasks-view' -import { NativeChatStructuredSessionStatus } from './NativeChatStructuredSessionStatus' -import { useStructuredSessionTaskStop } from './use-structured-session-task-stop' - -vi.mock('./use-structured-session-child-row-context', () => ({ - useStructuredSessionChildRowContext: () => undefined -})) - -afterEach(cleanup) - -function Strip(props: { tasks: Parameters[1] }) { - const stop = useStructuredSessionTaskStop('session-1', props.tasks) - return ( - - ) -} - -function helper(invocation: AgentChildWorkView['invocation']): AgentChildWorkView { - return { - id: 'helper', - providerId: 'thread-helper', - kind: 'agent', - description: 'audit_build', - state: 'working', - membership: 'live', - firstObservedAt: Date.now() - 65_000, - observedAt: Date.now() - 1_000, - stoppable: true, - invocation - } -} - -describe('NativeChatStructuredSessionStatus', () => { - it("offers Stop again on a helper's next run, which reuses the stopped run's row id", async () => { - let finish: (result: AgentSessionCancelResult) => void = () => {} - const stopBackgroundTask = vi.fn( - () => new Promise((resolve) => (finish = resolve)) - ) - const strip = (children: AgentChildWorkView[]) => ( - - ) - const { rerender } = render(strip([helper({ invocationId: 'turn-1', generation: 1 })])) - fireEvent.click(screen.getByRole('button', { expanded: false })) - fireEvent.click(screen.getByLabelText('Stop audit_build')) - await act(async () => finish({ cancelled: true })) - expect(screen.getByLabelText('Stop audit_build')).toBeDisabled() - - // The helper's next run, with no render between: same provider id, a new invocation. - rerender(strip([helper({ invocationId: 'turn-2', generation: 2 })])) - expect(screen.getByLabelText('Stop audit_build')).toBeEnabled() - }) -}) diff --git a/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts b/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts deleted file mode 100644 index dafde43ea40..00000000000 --- a/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { showWorkspaceForFile } from './plugin-view-editor-workspace' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' - -const activation = vi.hoisted(() => ({ activateAndRevealWorkspace: vi.fn() })) -vi.mock('@/lib/workspace/activation/worktree-activation', () => activation) -const initialState = useAppStore.getState() -afterEach(() => { - useAppStore.setState(initialState, true) - vi.clearAllMocks() -}) - -it('refuses a retired file owner without registering its deleting directory as a folder', async () => { - const addRepoPath = vi.fn() - const row = makeWorktree({ - id: 'r::/work/feature', - repoId: 'r', - path: '/work/feature', - hostId: 'local', - removing: true, - removalRecorded: true - }) - useAppStore.setState({ - worktreesByRepo: { r: [row] }, - folderWorkspaces: [], - activeWorktreeId: null, - addRepoPath - }) - await expect( - showWorkspaceForFile(['/work/feature/document.ext'], '/work/feature') - ).resolves.toBeNull() - expect(addRepoPath).not.toHaveBeenCalled() - expect(activation.activateAndRevealWorkspace).not.toHaveBeenCalled() - - useAppStore.setState({ worktreesByRepo: { r: [{ ...row, removalRecorded: undefined }] } }) - await expect( - showWorkspaceForFile(['/work/feature/document.ext'], '/work/feature') - ).resolves.toMatchObject({ worktreeId: row.id }) - expect(addRepoPath).not.toHaveBeenCalled() - expect(activation.activateAndRevealWorkspace).toHaveBeenCalledWith(row.id, { - providesInitialSurface: true, - executionHostId: 'local' - }) -}) - -it('still registers a genuinely unowned file folder and opens it', async () => { - const row = makeWorktree({ - id: 'added::/new/folder', - repoId: 'added', - path: '/new/folder', - hostId: 'local' - }) - const addRepoPath = vi.fn(async () => { - useAppStore.setState({ worktreesByRepo: { added: [row] } }) - return { - id: 'added', - path: '/new/folder', - displayName: 'added', - badgeColor: 'blue', - addedAt: 1 - } - }) - const fetchWorktrees = vi.fn().mockResolvedValue(true) - useAppStore.setState({ - worktreesByRepo: {}, - folderWorkspaces: [], - activeWorktreeId: null, - addRepoPath, - fetchWorktrees - }) - await expect( - showWorkspaceForFile(['/new/folder/document.ext'], '/new/folder') - ).resolves.toMatchObject({ worktreeId: row.id, addedRepoId: 'added' }) - expect(addRepoPath).toHaveBeenCalledWith('/new/folder', 'folder', { runtimeEnvironmentId: null }) - expect(fetchWorktrees).toHaveBeenCalledWith('added') - expect(activation.activateAndRevealWorkspace).toHaveBeenCalledWith(row.id, { - providesInitialSurface: true, - executionHostId: 'local' - }) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-account-peer.test.tsx b/src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-account-peer.test.tsx deleted file mode 100644 index e870bc19f0e..00000000000 --- a/src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-account-peer.test.tsx +++ /dev/null @@ -1,80 +0,0 @@ -// @vitest-environment happy-dom - -import type * as I18n from '@/i18n/i18n' -import { expect, it, vi } from 'vitest' - -import { - NativeAccountInputs, - NativeAccountEvidence, - nativeEvidenceCovers -} from './ai-vault-native-account-index' -import { accountSettings, installAccountFixture } from './ai-vault-account-test-fixture' - -vi.mock('@/i18n/i18n', async (importOriginal) => ({ - ...(await importOriginal()), - translate: (_key: string, fallback: string) => fallback -})) -installAccountFixture() - -it('compares real coverage under the same evidence across ordered candidates and A/B/A roots', () => { - const settings = accountSettings(4) - const saved = settings.claudeManagedAccounts[0]! - const candidates = [ - { ...saved }, - { ...saved, managedAuthPath: '/other', email: 'other@example.com' } - ] - const a = new NativeAccountInputs({ ...settings, claudeManagedAccounts: candidates }) - const evidence = new NativeAccountEvidence(a, { - claude: { - accounts: [ - { ...saved, email: 'old-first@example.com' }, - { ...saved, email: 'old-second@example.com' } - ], - activeAccountId: null - } - }) - const binding = { kind: 'claude' as const, path: saved.managedAuthPath, scope: 'host' } - const b = new NativeAccountInputs({ - ...settings, - claudeManagedAccounts: candidates.toReversed() - }) - expect(nativeEvidenceCovers(binding, b, evidence)).toBe(false) - const again = new NativeAccountInputs( - { ...settings, claudeManagedAccounts: candidates.map((account) => ({ ...account })) }, - b - ) - expect(nativeEvidenceCovers(binding, again, evidence)).toBe(true) - const orderOnly = new NativeAccountInputs({ - ...settings, - claudeManagedAccounts: candidates.map((account, i) => ({ ...account, updatedAt: i + 2 })) - }) - expect(nativeEvidenceCovers(binding, orderOnly, evidence)).toBe(false) - const modern = new NativeAccountEvidence(a, { - claude: { - accounts: [ - { ...saved, home: '/routed' }, - { ...candidates[1]!, id: 'other', home: '/routed' } - ], - activeAccountId: null - } - }) - const routed = { ...binding, path: '/routed' } - expect(nativeEvidenceCovers(routed, orderOnly, modern)).toBe(false) - const codex = settings.codexManagedAccounts[0]! - const firstPath = [codex, { ...codex, id: 'other', email: 'other@example.com' }] - const paths = new NativeAccountInputs({ ...settings, codexManagedAccounts: firstPath }) - const pathEvidence = new NativeAccountEvidence(paths, { - codex: { accounts: firstPath, activeAccountId: null } - }) - const swapped = new NativeAccountInputs({ - ...settings, - codexManagedAccounts: firstPath.toReversed() - }) - expect( - nativeEvidenceCovers( - { kind: 'codex', scope: 'host', path: codex.managedHomePath }, - swapped, - pathEvidence - ) - ).toBe(false) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/scanning/AiVaultScanProgressStrip.test.tsx b/src/renderer/src/components/right-sidebar/ai-vault/scanning/AiVaultScanProgressStrip.test.tsx deleted file mode 100644 index 5033316b9ed..00000000000 --- a/src/renderer/src/components/right-sidebar/ai-vault/scanning/AiVaultScanProgressStrip.test.tsx +++ /dev/null @@ -1,67 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook, waitFor } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { AiVaultScanProgress } from '../../../../../../shared/ai-vault/scanning/ai-vault-scan-progress' -import { aiVaultLocalScanKey } from '../../../../../../shared/ai-vault/scanning/ai-vault-local-scan-key' - -import { resetAiVaultSessionResultCacheForTest } from './ai-vault-session-result-cache' -import { - resetAiVaultScanProgressStoreForTests, - useAiVaultScanProgress -} from './ai-vault-scan-progress-store' - -afterEach(() => { - cleanup() - resetAiVaultScanProgressStoreForTests() - resetAiVaultSessionResultCacheForTest() - vi.unstubAllGlobals() -}) - -const FINISHED: AiVaultScanProgress = { - scanId: 'scan-a', - stage: 'finished', - agents: [ - { agent: 'claude', files: 24_968, databases: 0, walking: false }, - { agent: 'codex', files: 77_483, databases: 0, walking: false }, - { agent: 'opencode', files: 0, databases: 1, walking: false } - ], - read: { done: 2_000, total: 2_000 }, - startedAt: 0, - settledAt: 90_000 -} - -it('keeps a narrower cached panel off the broader key while a late matching panel loads it', async () => { - const lowerDepth = { scopePaths: ['/project'], includeAntigravityIdeSessions: true, limit: 100 } - const broader = aiVaultLocalScanKey({ ...lowerDepth, limit: 1000 }) - const narrower = aiVaultLocalScanKey(lowerDepth) - expect(broader).not.toBe(narrower) - const cachedProgress = FINISHED - let push: (update: { scanKey: string; progress: AiVaultScanProgress | null }) => void = () => - undefined - vi.stubGlobal('api', { - aiVault: { - getScanProgress: (scanKey: string) => - Promise.resolve(scanKey === broader ? cachedProgress : null), - onScanProgress: (callback: typeof push) => { - push = callback - return () => undefined - } - } - }) - const local = renderHook(() => useAiVaultScanProgress('local', broader)) - const narrowerPanel = renderHook(() => useAiVaultScanProgress('local', narrower)) - const remote = renderHook(() => useAiVaultScanProgress('runtime:server-1', broader)) - const allHosts = renderHook(() => useAiVaultScanProgress('all', broader)) - await waitFor(() => expect(local.result.current?.progress).toBe(cachedProgress)) - act(() => push({ scanKey: broader, progress: cachedProgress })) - - expect(local.result.current?.progress).toBe(cachedProgress) - expect(narrowerPanel.result.current).toBeNull() - act(() => - push({ scanKey: broader, progress: { ...cachedProgress, scanId: 'later', stage: 'finding' } }) - ) - expect(narrowerPanel.result.current).toBeNull() - // Without remote progress evidence, retain the existing spinner/error presentation. - expect(remote.result.current).toBeNull() - expect(allHosts.result.current).toBeNull() -}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx deleted file mode 100644 index e6a704d65db..00000000000 --- a/src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx +++ /dev/null @@ -1,95 +0,0 @@ -// @vitest-environment happy-dom - -import { act, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { SearchResult } from '../../../../../../shared/file-search/code-search-types' -import { useFileSearchRunner } from './useFileSearchRunner' - -const mocks = vi.hoisted(() => ({ - getConnectionId: vi.fn(), - getState: vi.fn(), - searchRuntimeFiles: vi.fn() -})) - -vi.mock('@/lib/workspace/ownership/connection-context', () => ({ - getConnectionId: mocks.getConnectionId -})) - -vi.mock('@/runtime/files/search/runtime-file-search-client', () => ({ - searchRuntimeFiles: mocks.searchRuntimeFiles -})) - -vi.mock('@/store/index', () => ({ - useAppStore: Object.assign( - vi.fn((selector: (state: ReturnType) => unknown) => - selector(mocks.getState()) - ), - { getState: mocks.getState } - ) -})) - -const RESULTS: SearchResult = { - files: [], - totalMatches: 0, - truncated: false -} - -function renderSearchRunner(state: Record, worktreeId: string) { - const updates: Record[] = [] - mocks.getState.mockImplementation(() => state) - mocks.searchRuntimeFiles.mockResolvedValue(RESULTS) - - const hook = renderHook(() => - useFileSearchRunner({ - activeWorktreeId: worktreeId, - worktreePath: '/repo', - updateActiveSearchState: (update) => updates.push(update) - }) - ) - - return { hook, updates } -} - -async function finishSearch(executeSearch: (query: string) => void): Promise { - await act(async () => { - executeSearch('owner') - await vi.advanceTimersByTimeAsync(300) - }) -} - -describe('useFileSearchRunner result ownership', () => { - beforeEach(() => { - vi.useFakeTimers() - mocks.getConnectionId.mockReturnValue(null) - }) - - afterEach(() => { - vi.useRealTimers() - vi.clearAllMocks() - }) - - it('ignores an older rejection after a newer search has succeeded', async () => { - const { hook, updates } = renderSearchRunner( - { settings: {}, repos: [], worktreesByRepo: {}, fileSearchStateByWorktree: {} }, - 'missing-repo::/repo' - ) - const log = vi.spyOn(console, 'error').mockImplementation(() => {}) - let rejectOldSearch: (reason: Error) => void = () => {} - mocks.searchRuntimeFiles.mockImplementationOnce( - () => - new Promise((_resolve, reject) => { - rejectOldSearch = reject - }) - ) - await finishSearch(hook.result.current.executeSearch) - await finishSearch(hook.result.current.executeSearch) - await act(async () => rejectOldSearch(new Error('old failure'))) - expect(Object.assign({}, ...updates)).toMatchObject({ - error: null, - results: RESULTS, - loading: false - }) - expect(updates.some((update) => update.error === 'old failure')).toBe(false) - log.mockRestore() - }) -}) diff --git a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts b/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts deleted file mode 100644 index 2029d79e160..00000000000 --- a/src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry' - -const readRuntimeDirectoryPage = vi.fn() -const readRuntimeDirectory = vi.fn() -let hostPages = true -vi.mock('@/runtime/files/reads/runtime-directory-page-client', () => ({ - readRuntimeDirectoryPage: (...args: unknown[]) => readRuntimeDirectoryPage(...args), - runtimeDirectoryPagesSupported: () => hostPages -})) -vi.mock('@/runtime/files/reads/runtime-directory-read', () => ({ - readRuntimeDirectory: (...args: unknown[]) => readRuntimeDirectory(...args) -})) -vi.mock('../navigation/file-explorer-operation-owner', () => ({ - getFileExplorerOperationOwner: () => ({ kind: 'local' }), - getFileExplorerOperationRoute: () => ({ target: { kind: 'local' }, connectionId: null }), - getFileExplorerOwnerUnresolvedMessage: () => 'unresolved' -})) - -import { appendFileExplorerDirPage } from './file-explorer-dir-pages' - -import type { DirCache } from './file-explorer-types' - -const file = (name: string): DirEntry => ({ name, isDirectory: false, isSymlink: false }) -const names = (count: number, from = 0): DirEntry[] => - Array.from({ length: count }, (_, index) => file(`f${String(from + index).padStart(5, '0')}`)) - -/** A host folder of `total` sorted files: refused whole past `wholeLimit`, served in pages. */ - -beforeEach(() => { - readRuntimeDirectoryPage.mockReset() - readRuntimeDirectory.mockReset() - hostPages = true -}) - -describe('paged folder listing', () => { - it('appends a page in order, keeping a row the watcher already added once', () => { - const owner = { kind: 'local' as const } - const cache: DirCache = { - children: [ - { name: 'f00000', path: '/w/f00000', relativePath: 'f00000', isDirectory: false, depth: 0 }, - { name: 'f00003', path: '/w/f00003', relativePath: 'f00003', isDirectory: false, depth: 0 } - ], - operationOwner: owner, - more: { after: { name: 'f00000', isDirectory: false } } - } - const appended = appendFileExplorerDirPage( - cache, - { entries: names(3, 1), operationOwner: owner }, - '/w', - -1, - '/w' - ) - expect(appended.children.map((child) => child.name)).toEqual([ - 'f00000', - 'f00001', - 'f00002', - 'f00003' - ]) - expect(appended.more).toBeUndefined() - }) - - it('does not extend rows with a page from another host', () => { - const cache: DirCache = { - children: [], - operationOwner: { kind: 'local' }, - more: { after: { name: 'f00000', isDirectory: false } } - } - const appended = appendFileExplorerDirPage( - cache, - { entries: names(1), operationOwner: { kind: 'ssh', connectionId: 'c' } }, - '/w', - -1, - '/w' - ) - expect(appended).toEqual({ children: [], operationOwner: { kind: 'local' } }) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-jira-review-title.test.tsx b/src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-jira-review-title.test.tsx deleted file mode 100644 index 1881dd6c150..00000000000 --- a/src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-jira-review-title.test.tsx +++ /dev/null @@ -1,83 +0,0 @@ -// @vitest-environment happy-dom - -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it } from 'vitest' -import { useCreatePullRequestDialogFields } from './useCreatePullRequestDialogFields' -import type { HostedReviewCreationEligibility } from '../../../../../../shared/source-control/hosted-review/hosted-review-contracts' -import type { WorkspaceAttachmentMetadata } from '../../../../../../shared/workspace-attachments/workspace-attachment-legacy' - -const workspace: WorkspaceAttachmentMetadata = { - linkedWorkItem: { - provider: 'jira', - type: 'issue', - number: 0, - jiraIdentifier: 'team_alpha9-7', - title: 'Restore login', - url: 'https://jira.example.com/jira/browse/team_alpha9-7' - } -} -const fields = { - base: 'main', - title: 'team_alpha9-7 TEAM_ALPHA9-7 Restore login', - body: 'Generated body', - draft: false -} -const revisions = { base: 0, title: 0, body: 0, draft: 0 } - -function options(provider: 'github' | 'gitlab') { - const eligibility: HostedReviewCreationEligibility = { - provider, - review: null, - canCreate: true, - blockedReason: null, - nextAction: null, - reviewLookupOutcome: 'not_found', - defaultBaseRef: 'main', - title: 'Restore login', - body: 'Details' - } - return { - open: true, - repoId: 'repo-1', - worktreeId: 'wt-1', - worktreePath: '/repo/wt', - branch: 'user/team_alpha9-7-restore-login', - eligibility, - settings: null, - target: { kind: 'local' as const }, - submitting: false, - workspace - } -} -afterEach(cleanup) - -describe('Jira review title ownership', () => { - it('keeps a title edited during or before regeneration', () => { - const { result } = renderHook(() => useCreatePullRequestDialogFields(options('gitlab'))) - act(() => { - result.current.setTitle('My exact manual title') - }) - act(() => { - result.current.applyGeneratedFields(fields, revisions) - }) - expect(result.current.title).toBe('My exact manual title') - const laterRevisions = { ...result.current.fieldRevisions } - act(() => { - result.current.applyGeneratedFields(fields, laterRevisions) - }) - expect(result.current.title).toBe('My exact manual title') - expect(result.current.body).toBe('Generated body') - }) - it('keeps a manual title when eligibility refreshes on the same branch', () => { - const input = options('github') - const { result, rerender } = renderHook( - ({ eligibility }) => useCreatePullRequestDialogFields({ ...input, eligibility }), - { initialProps: { eligibility: input.eligibility } } - ) - act(() => { - result.current.setTitle('Manual title') - }) - rerender({ eligibility: { ...input.eligibility, title: 'Refreshed title' } }) - expect(result.current.title).toBe('Manual title') - }) -}) diff --git a/src/renderer/src/components/shared/useDaemonActions.test.tsx b/src/renderer/src/components/shared/useDaemonActions.test.tsx deleted file mode 100644 index aadea3b83f1..00000000000 --- a/src/renderer/src/components/shared/useDaemonActions.test.tsx +++ /dev/null @@ -1,99 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' - -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { runCleanupMock, snapshotMock, toastErrorMock, toastInfoMock, toastSuccessMock } = - vi.hoisted(() => ({ - runCleanupMock: vi.fn(), - snapshotMock: vi.fn(), - toastErrorMock: vi.fn(), - toastInfoMock: vi.fn(), - toastSuccessMock: vi.fn() - })) - -vi.mock('./kill-all-terminal-surfaces', () => ({ - runKillAllTerminalSurfaces: runCleanupMock, - snapshotKillAllTerminalSurfaceIds: snapshotMock -})) - -vi.mock('sonner', () => ({ - toast: { - error: toastErrorMock, - info: toastInfoMock, - success: toastSuccessMock, - warning: vi.fn() - } -})) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback -})) - -import type { KillAllTerminalSurfacesSummary } from './kill-all-terminal-surfaces' -import { useDaemonActions } from './useDaemonActions' - -function rejectedSummary(): KillAllTerminalSurfacesSummary { - return { - targetCount: 1, - closeAttemptCount: 1, - absentTargetCount: 1, - failedCloseAttemptCount: 0, - exactKillAcceptedCount: 1, - exactKillRejectedCount: 0, - closeDurationMs: 1, - maxCloseBatchDurationMs: 1, - closeYieldCount: 0, - closePhaseExceededLongTaskBudget: false, - daemon: { status: 'rejected' } - } -} - -function deferred(): { promise: Promise; resolve: (value: T) => void } { - let resolve!: (value: T) => void - const promise = new Promise((resolvePromise) => { - resolve = resolvePromise - }) - return { promise, resolve } -} - -describe('useDaemonActions kill-all cleanup', () => { - beforeEach(() => { - vi.clearAllMocks() - snapshotMock.mockReturnValue(['confirmed-tab']) - }) - - it('snapshots before start and does not revoke cleanup when the caller unmounts', async () => { - const cleanup = deferred() - const sequence: string[] = [] - const onKillAllStart = vi.fn(() => sequence.push('start')) - const onKillAllError = vi.fn() - const onKillAllSettled = vi.fn() - snapshotMock.mockImplementation(() => { - sequence.push('snapshot') - return ['confirmed-tab'] - }) - runCleanupMock.mockImplementation(() => { - sequence.push('cleanup') - return cleanup.promise - }) - const { result, unmount } = renderHook(() => - useDaemonActions({ onKillAllStart, onKillAllError, onKillAllSettled }) - ) - - let completion!: Promise - act(() => { - completion = result.current.runKillAll() - }) - - expect(sequence).toEqual(['snapshot', 'start', 'cleanup']) - expect(runCleanupMock).toHaveBeenCalledWith(['confirmed-tab']) - unmount() - cleanup.resolve(rejectedSummary()) - await completion - - expect(toastErrorMock).toHaveBeenCalledTimes(1) - expect(onKillAllError).not.toHaveBeenCalled() - expect(onKillAllSettled).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.host-scope.test.tsx b/src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.host-scope.test.tsx deleted file mode 100644 index 77b5ac78aaf..00000000000 --- a/src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.host-scope.test.tsx +++ /dev/null @@ -1,93 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import type { Repo } from '../../../../../../shared/repo-types' -import type { Worktree, WorkspaceAttachment } from '../../../../../../shared/worktree/types' - -import WorktreeMetaDialog from './WorktreeMetaDialog' - -vi.mock('./WorktreeDisplayNameField', () => ({ WorktreeDisplayNameField: () => null })) -vi.mock('./WorktreeLinkedItemsField', () => ({ - WorktreeLinkedItemsField: ({ items, repo }: { items: WorkspaceAttachment[]; repo?: Repo }) => ( -
- {repo?.path ?? 'none'} - {items.map((item) => ( - {item.title} - ))} -
- ) -})) - -const initialState = useAppStore.getInitialState() -const update = vi.fn(async () => ({ ok: true as const })) -const localRepo: Repo = { - id: 'repo', - path: '/local', - displayName: 'Local', - badgeColor: '', - addedAt: 1 -} -const remoteRepo: Repo = { ...localRepo, path: '/remote', executionHostId: 'ssh:box' } -function workspace(hostId?: Worktree['hostId']): Worktree { - return { - id: 'shared-id', - repoId: 'repo', - path: '/workspace', - branch: 'feature', - head: 'abc', - isBare: false, - isMainWorktree: false, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1, - displayName: 'Workspace', - comment: 'note', - hostId, - linkedPR: null, - linkedIssue: null, - linkedLinearIssue: null, - linkedItems: [ - { - provider: 'github', - type: 'issue', - number: hostId ? 2 : 1, - title: hostId ? 'Remote task' : 'Local task' - } - ] - } -} -function open( - executionHostId: string, - rows: Worktree[] = [workspace(), workspace('ssh:box')], - repos: Repo[] = [localRepo, remoteRepo] -): void { - useAppStore.setState({ - repos, - worktreesByRepo: { repo: rows }, - updateWorktreeMeta: update, - activeModal: 'edit-meta', - modalData: { worktreeId: 'shared-id', repoId: 'repo', executionHostId } - }) - render() -} - -describe('workspace details exact host selection', () => { - beforeEach(() => { - useAppStore.setState(initialState, true) - update.mockClear() - }) - afterEach(cleanup) - - it('does not fall back to another host when the requested workspace disappeared', () => { - open('ssh:missing', [workspace()]) - expect(screen.getByTestId('owner-repo').textContent).toBe('none') - expect(screen.queryByText('Local task')).toBeNull() - const save = screen.getByRole('button', { name: 'Save' }) - expect(save.hasAttribute('disabled')).toBe(true) - fireEvent.click(save) - expect(update).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/spawn/hidden-agent-resume-deferral.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/spawn/hidden-agent-resume-deferral.test.ts deleted file mode 100644 index 88e5795d2b8..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/spawn/hidden-agent-resume-deferral.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - deferHiddenAgentResume, - noteHiddenAgentResumePtyEnded -} from './hidden-agent-resume-deferral' -import type { ColdRestoreAgentResumeStartup } from '../startup/fresh-spawn-types' -import type { ConnectPanePtySession } from '../connect-pane-pty-session' - -const wakeRequests = vi.hoisted(() => ({ take: vi.fn(() => false) })) -vi.mock('@/lib/agent-session/resume/sleeping-agent-wake-requests', () => ({ - takeSleepingAgentWakeRequest: wakeRequests.take -})) -vi.mock('../reattach/deferred-session-reattach-connect', () => ({ - startDeferredSessionReattach: vi.fn() -})) - -function hiddenPaneSession(): ConnectPanePtySession { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deferHiddenAgentResume reads only these session members. - return { - disposed: false, - cacheKey: 'tab-1:leaf-1', - deps: { isVisibleRef: { current: false } }, - transport: { getPtyId: () => null }, - hibernatedWakeTarget: null, - hibernatedWakeInFlightClaimKey: null, - wakeHibernatedAgentPane: () => Promise.resolve('pty-1') - } as unknown as ConnectPanePtySession -} - -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deferHiddenAgentResume reads only the record entry. -const startup = { - sleepingRecordEntry: { paneKey: 'tab-1:leaf-1', record: { paneKey: 'tab-1:leaf-1' } } -} as unknown as ColdRestoreAgentResumeStartup - -describe('deferHiddenAgentResume', () => { - it('holds again once a pane a background wake released has gone back to sleep', () => { - const session = hiddenPaneSession() - wakeRequests.take.mockReturnValueOnce(true) - - expect(deferHiddenAgentResume(session, startup)).toBe(false) - // A fallback in the same connect keeps the background wake's release. - expect(deferHiddenAgentResume(session, startup)).toBe(false) - - noteHiddenAgentResumePtyEnded(session) - expect(deferHiddenAgentResume(session, startup)).toBe(true) - }) - - it('releases the hold under a record key the pane no longer holds', async () => { - const { isPaneSpawnDeferred } = - await import('@/components/terminal-pane/session-restore/spawn-deferral/pane-spawn-deferral-registry') - const session = hiddenPaneSession() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deferHiddenAgentResume reads only the record entry. - const legacyStartup = { - sleepingRecordEntry: { paneKey: 'tab-1:2', record: { paneKey: 'tab-1:2' } } - } as unknown as ColdRestoreAgentResumeStartup - - expect(deferHiddenAgentResume(session, legacyStartup)).toBe(true) - expect(isPaneSpawnDeferred('tab-1:2')).toBe(true) - expect(deferHiddenAgentResume(session, startup)).toBe(true) - - expect(isPaneSpawnDeferred('tab-1:2')).toBe(false) - expect(isPaneSpawnDeferred('tab-1:leaf-1')).toBe(true) - }) -}) diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts deleted file mode 100644 index b21c2b6e869..00000000000 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import type { AiVaultResumePlatformState } from './ai-vault-resume-platform' -import { getDefaultSettings } from '../../../../../../shared/constants' -import { TEST_REPO } from '../../../../store/repos/repo.test-fixture' -import { makeWorktree } from '../../../../store/slices/worktrees/worktree.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { buildAiVaultDropRepinStartup } from './ai-vault-resume-command' - -vi.mock('@/lib/workspace/creation/new-workspace', () => ({ - CLIENT_PLATFORM: 'darwin' -})) - -const RECORDED_HOME = '/tmp/orca/codex-accounts/aaaa/home' -const SELECTED_HOME = '/tmp/orca/codex-accounts/bbbb/home' - -function makeState(): AiVaultResumePlatformState { - return { - activeRepoId: 'repo-1', - activeWorktreeId: 'repo-1::worktree-1', - detectedWorktreesByRepo: {}, - sshConnectionStates: new Map(), - sshStateByEnvironment: new Map(), - runtimeStatusByEnvironmentId: new Map(), - folderWorkspaces: [], - projectGroups: [], - repos: [{ ...TEST_REPO, id: 'repo-1', path: '/Users/ada/repo' }], - projects: [ - { - displayName: 'repo', - badgeColor: '', - createdAt: 0, - updatedAt: 0, - id: 'repo-1', - sourceRepoIds: ['repo-1'] - } - ], - settings: { - ...getDefaultSettings('/tmp'), - agentDefaultArgs: { claude: '', codex: '' }, - agentDefaultEnv: { claude: {}, codex: {} } - }, - worktreesByRepo: { - 'repo-1': [ - makeWorktree({ id: 'repo-1::worktree-1', repoId: 'repo-1', path: '/Users/ada/repo' }) - ] - } - } -} - -function payload(overrides: { - sessionCwd?: string | null - sessionFilePath?: string -}): Parameters[0]['payload'] { - return { - agent: 'codex', - sessionId: 'session-1', - sessionExecutionHostId: 'local', - sessionFilePath: `${RECORDED_HOME}/sessions/2026/07/20/rollout-x.jsonl`, - ...overrides - } -} - -describe('buildAiVaultDropRepinStartup', () => { - it('repins a payload whose session has no cwd instead of keeping the wrong-account command', () => { - const startup = buildAiVaultDropRepinStartup({ - state: makeState(), - payload: payload({ sessionCwd: null }), - substituteCodexHome: SELECTED_HOME, - worktreeId: 'repo-1::worktree-1' - }) - - expect(startup).not.toBeNull() - expect(startup?.command).toContain(`CODEX_HOME='${SELECTED_HOME}'`) - expect(startup?.command).not.toContain(RECORDED_HOME) - expect(startup?.command).not.toContain('cd ') - }) - - it('declines a payload from an older serializer that never carried sessionCwd', () => { - const startup = buildAiVaultDropRepinStartup({ - state: makeState(), - payload: payload({}), - substituteCodexHome: SELECTED_HOME, - worktreeId: 'repo-1::worktree-1' - }) - - expect(startup).toBeNull() - }) -}) diff --git a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-target.test.ts b/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-target.test.ts deleted file mode 100644 index 7032bd43218..00000000000 --- a/src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-target.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AppState } from '@/store/types' -import { getAiVaultResumeWorkspaceTargetStatus } from './ai-vault-resume-target' -import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope' - -type ResumeTargetState = Pick< - AppState, - 'folderWorkspaces' | 'projectGroups' | 'repos' | 'worktreesByRepo' -> - -function makeState( - overrides: Partial> -): ResumeTargetState { - return { - folderWorkspaces: [], - projectGroups: [], - repos: [], - worktreesByRepo: {}, - ...overrides - } as unknown as ResumeTargetState -} - -describe('ai vault resume target ownership', () => { - it('uses the composite worktree repo id when worktree discovery is incomplete', () => { - expect( - getAiVaultResumeWorkspaceTargetStatus( - makeState({ - repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'runtime:env-1' }] - }), - 'repo-1::/repo/orca' - ) - ).toBe('runtime') - }) - - it('resolves explicit workspace keys through the target worktree host', () => { - expect( - getAiVaultResumeWorkspaceTargetStatus( - makeState({ - worktreesByRepo: { - 'repo-1': [{ id: 'repo-1::/repo/orca', repoId: 'repo-1', hostId: 'runtime:env-1' }] - }, - repos: [{ id: 'repo-1', connectionId: 'ssh-1', executionHostId: 'ssh:ssh-1' }] - }), - 'worktree:repo-1::/repo/orca' - ) - ).toBe('runtime') - }) - - it('prefers runtime project-group ownership over stale SSH folder connection ids', () => { - expect( - getAiVaultResumeWorkspaceTargetStatus( - makeState({ - folderWorkspaces: [ - { - id: 'folder-1', - projectGroupId: 'group-1', - name: 'Platform', - folderPath: '/repo/platform', - connectionId: 'ssh-1' - } - ], - projectGroups: [ - { id: 'group-1', connectionId: 'ssh-1', executionHostId: 'runtime:env-1' } - ] - }), - folderWorkspaceKey('folder-1') - ) - ).toBe('runtime') - }) - - it('treats mixed local and SSH folder workspace targets as unknown', () => { - expect( - getAiVaultResumeWorkspaceTargetStatus( - makeState({ - folderWorkspaces: [ - { - id: 'folder-1', - projectGroupId: 'group-1', - name: 'Platform', - folderPath: '/repo/platform' - } - ], - projectGroups: [{ id: 'group-1' }], - repos: [ - { id: 'repo-local', path: '/repo/platform/web', connectionId: null }, - { id: 'repo-ssh', path: '/repo/platform/api', connectionId: 'ssh-1' } - ] - }), - folderWorkspaceKey('folder-1') - ) - ).toBe('unknown') - }) -}) diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation-launch-awaiting-host.test.ts b/src/renderer/src/lib/workspace/activation/worktree-activation-launch-awaiting-host.test.ts deleted file mode 100644 index 356fcdb278f..00000000000 --- a/src/renderer/src/lib/workspace/activation/worktree-activation-launch-awaiting-host.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' - -const admit = vi.hoisted(() => vi.fn()) -vi.mock('sonner', () => ({ toast: { info: vi.fn(), error: vi.fn() } })) -vi.mock('@/lib/agent-session/launch/structured-agent-session-host-admission', () => ({ - admitStructuredLaunchOnHost: admit -})) - -import { useAppStore } from '@/store/index' -import { activateAndRevealWorktree } from './worktree-activation' -import * as activationGate from './worktree-agent-activation-gate' -import { - makeCreatedAgentWorktree as makeWorktree, - seedEmptyActivatableWorktree -} from './worktree-activation-created-agent.test-fixture' -import { registerWorktreeActivationReset } from './worktree-activation.test-fixture' -import { beginHostAdmittedStructuredLaunch } from '../../agent-session/launch/structured-agent-session-launch-admission' -import { adoptAgentSessionLaunchVerdict } from '../../agent-session/launch/routing/agent-session-launch-plan' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' - -const initial = useAppStore.getState() -registerWorktreeActivationReset() -afterEach(() => { - vi.unstubAllGlobals() - vi.restoreAllMocks() - useAppStore.setState(initial, true) -}) - -// Clicking the still-empty workspace while its chat waits on this machine used to seed -// "Terminal 1" beside the chat, through the activation's reseed rather than the watcher. -it('does not seed a shell when the workspace is re-activated while its chat waits on its host', async () => { - const worktree = makeWorktree() - seedEmptyActivatableWorktree(worktree) - vi.stubGlobal('window', { api: { runtime: { call: vi.fn() }, pty: { listSessions: vi.fn() } } }) - const gate = vi.spyOn(activationGate, 'gateWorktreeAgentActivation').mockResolvedValue('empty') - let answer!: (admission: { kind: 'admitted' }) => void - admit.mockReturnValue(new Promise((resolve) => (answer = resolve))) - const openAdmitted = vi.fn(() => ({ settlement: new Promise(() => {}), cancel: vi.fn() })) - beginHostAdmittedStructuredLaunch({ - plan: { - ...adoptAgentSessionLaunchVerdict({ - route: 'structured-native-chat', - requestId: 'request-1', - agent: 'claude', - worktreeId: worktree.id - }), - agent: 'claude' - }, - hooks: {}, - worktreeId: worktree.id, - executionHostId: LOCAL_EXECUTION_HOST_ID, - target: { kind: 'local' }, - openAdmitted, - onHostDeclined: () => ({ opened: true }) - }) - - activateAndRevealWorktree(worktree.id, { notifyHostRuntime: false }) - await gate.mock.results[0]?.value - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(useAppStore.getState().tabsByWorktree[worktree.id] ?? []).toEqual([]) - - answer({ kind: 'admitted' }) - await vi.waitFor(() => expect(openAdmitted).toHaveBeenCalledOnce()) - expect(useAppStore.getState().tabsByWorktree[worktree.id] ?? []).toEqual([]) -}) diff --git a/src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-output-cadence.test.ts b/src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-output-cadence.test.ts deleted file mode 100644 index 63effe9c81a..00000000000 --- a/src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-output-cadence.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamJson -} from '../../../../../shared/terminal/stream/terminal-stream-protocol' -import { - getRemoteRuntimeTerminalMultiplexer, - resetRemoteRuntimeTerminalMultiplexersForTests -} from './registry/remote-runtime-terminal-multiplexer-registry' -import { replaceRuntimeEnvironmentRevisions } from '../../rpc/environment-revisions/runtime-environment-revision' -import { stubRuntimeEnvironmentBridge } from '../../rpc/testing/runtime-environment-bridge-fixture' - -type SubscribeCallbacks = { onResponse: (response: unknown) => void } - -// Why: hosts that predate opcode 20 reject it, so the client may send it only after the capability echo. -describe('remote terminal output cadence negotiation', () => { - let hostCapabilities: Record - let cadenceFrames: unknown[] - - beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeTerminalMultiplexersForTests() - replaceRuntimeEnvironmentRevisions([]) - cadenceFrames = [] - const subscribe = vi.fn(async (_args: unknown, next: SubscribeCallbacks) => { - queueMicrotask(() => next.onResponse({ ok: true, result: { type: 'ready' } })) - return { - unsubscribe: vi.fn(), - sendBinary: (bytes: Uint8Array) => { - const frame = decodeTerminalStreamFrame(bytes) - if (frame?.opcode === TerminalStreamOpcode.Subscribe) { - const payload = decodeTerminalStreamJson<{ streamId: number }>(frame.payload) - next.onResponse({ - ok: true, - result: { - type: 'subscribed', - streamId: payload?.streamId ?? 0, - capabilities: hostCapabilities - } - }) - } else if (frame?.opcode === TerminalStreamOpcode.SetOutputCadence) { - cadenceFrames.push(decodeTerminalStreamJson(frame.payload)) - } - } - } - }) - stubRuntimeEnvironmentBridge({ subscribe }) - }) - - async function subscribeAndBackground(): Promise { - const stream = await getRemoteRuntimeTerminalMultiplexer('env-1').subscribeTerminal({ - terminal: 'terminal-1', - client: { id: 'desktop-1', type: 'desktop' }, - outputCadence: 'focused', - callbacks: { onData: () => {}, onSnapshot: () => {} } - }) - stream.setOutputCadence('background') - } - - it('never sends a cadence frame to a host that did not echo the capability', async () => { - hostCapabilities = { outputPause: 1 } - await subscribeAndBackground() - expect(cadenceFrames).toEqual([]) - }) - - it('sends the cadence to a host that echoed the capability', async () => { - hostCapabilities = { outputPause: 1, outputCadence: 1 } - await subscribeAndBackground() - expect(cadenceFrames).toEqual([{ cadence: 'background' }]) - }) -}) diff --git a/src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-ownership.test.ts b/src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-ownership.test.ts deleted file mode 100644 index ac3923589c9..00000000000 --- a/src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-ownership.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import type { RuntimeMobileSessionFileTab } from '../../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import type { OpenFile } from '../../../store/slices/editor/types/open-file' -import { applyWebSessionTabsSnapshot } from '../snapshot-api' -import { - ENV, - NOW, - WT, - makeSnapshot, - makeState, - resetWebSessionTabsSyncTestState -} from '../testing/web-session-tabs-sync.test-fixture' - -const filePath = '/repo/readme.txt' -const hostTab: RuntimeMobileSessionFileTab = { - type: 'file', - id: 'retained-tab', - title: 'readme.txt', - filePath, - relativePath: 'readme.txt', - language: 'plaintext', - isDirty: false, - isActive: true -} -function file(overrides: Partial = {}): OpenFile { - return { - id: filePath, - filePath, - relativePath: 'readme.txt', - worktreeId: WT, - language: 'plaintext', - isDirty: false, - runtimeEnvironmentId: null, - mode: 'edit', - ...overrides - } -} -function snapshot(tabs = [hostTab]) { - return makeSnapshot(tabs, { activeTabId: hostTab.id, activeTabType: 'file' }) -} - -describe('host editor file ownership', () => { - beforeEach(resetWebSessionTabsSyncTestState) - - it('shares a pending retained file with a newly published split listed first', () => { - const retained = file({ isDirty: true, pendingOwnerMigration: true }) - const state = makeState({ - openFiles: [retained], - unifiedTabsByWorktree: { - [WT]: [ - { - id: hostTab.id, - entityId: retained.id, - worktreeId: WT, - groupId: 'legacy-group', - executionHostId: 'ssh:legacy-target', - contentType: 'editor', - label: 'readme.txt', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: NOW, - isPreview: false - } - ] - } - }) - const patch = applyWebSessionTabsSnapshot( - state, - snapshot([{ ...hostTab, id: 'new-split', isActive: false }, hostTab]), - ENV, - NOW - ) - expect(patch.openFiles ?? state.openFiles).toEqual([retained]) - expect(patch.unifiedTabsByWorktree?.[WT]?.map((tab) => tab.entityId)).toEqual([ - retained.id, - retained.id - ]) - }) - - it('does not borrow another host’s disk signature or overwrite its file ID', () => { - const other = file({ runtimeEnvironmentId: 'other-host', lastKnownDiskSignature: 'other-disk' }) - const patch = applyWebSessionTabsSnapshot( - makeState({ openFiles: [other] }), - snapshot(), - ENV, - NOW - ) - expect(patch?.openFiles).toHaveLength(2) - expect(patch?.openFiles?.[0]).toBe(other) - expect(patch?.openFiles?.[1]).toMatchObject({ - runtimeEnvironmentId: ENV - }) - expect(patch?.openFiles?.[1]?.lastKnownDiskSignature).toBeUndefined() - }) -}) diff --git a/src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts b/src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts deleted file mode 100644 index 2338f8681f0..00000000000 --- a/src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { getDefaultBrowserProfileForHost } from '../hosts/browser-host-state' -import { - createBrowserMockApi, - createTestStore, - resetBrowserRuntimeMocks -} from '../browser-slice-test-harness' - -const createWebRuntimeSessionBrowserTabMock = vi.hoisted(() => vi.fn()) -const runtimeEnvironmentCall = vi.fn() -const runtimeEnvironmentTransportCall = vi.fn() - -vi.mock('@/runtime/browser/creation/web-runtime-browser-creation', () => ({ - createWebRuntimeSessionBrowserTab: createWebRuntimeSessionBrowserTabMock -})) - -const mockApi = createBrowserMockApi(runtimeEnvironmentTransportCall) - -// @ts-expect-error test window mock -globalThis.window = { api: mockApi } - -describe('createBrowserSlice runtime guard', () => { - beforeEach(() => { - resetBrowserRuntimeMocks({ - runtimeEnvironmentCall, - runtimeEnvironmentTransportCall, - createWebRuntimeSessionBrowserTabMock - }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - }) - - it('drops the default profile pick once a refreshed list no longer has it', async () => { - const store = createTestStore() - const listed = (id: string) => ({ - id, - scope: id === 'default' ? ('default' as const) : ('isolated' as const), - partition: `persist:${id}`, - label: id, - source: null - }) - await store.getState().setDefaultBrowserSessionProfileId('work') - expect(store.getState().settings?.browserDefaultProfileIdByHostId).toEqual({ local: 'work' }) - mockApi.browser.sessionListProfiles - .mockResolvedValueOnce([listed('default'), listed('work')]) - .mockResolvedValueOnce([listed('default')]) - - await store.getState().fetchBrowserSessionProfiles('local') - expect(getDefaultBrowserProfileForHost(store.getState(), 'local')).toBe('work') - - await store.getState().fetchBrowserSessionProfiles('local') - expect(getDefaultBrowserProfileForHost(store.getState(), 'local')).toBeNull() - }) - - it('keeps the newest listing when an older one answers last', async () => { - const store = createTestStore() - const listed = (id: string) => ({ - id, - scope: id === 'default' ? ('default' as const) : ('isolated' as const), - partition: `persist:${id}`, - label: id, - source: null - }) - const older = Promise.withResolvers[]>() - mockApi.browser.sessionListProfiles - .mockReturnValueOnce(older.promise) - .mockResolvedValueOnce([listed('default')]) - - const olderFetch = store.getState().fetchBrowserSessionProfiles('local') - await store.getState().fetchBrowserSessionProfiles('local') - older.resolve([listed('default'), listed('deleted')]) - await olderFetch - - expect(store.getState().browserSessionProfilesByHostId.local).toEqual([listed('default')]) - }) -}) diff --git a/src/renderer/src/store/slices/editor/closing/editor-recently-closed-tabs.test.ts b/src/renderer/src/store/slices/editor/closing/editor-recently-closed-tabs.test.ts deleted file mode 100644 index 1dbac886f78..00000000000 --- a/src/renderer/src/store/slices/editor/closing/editor-recently-closed-tabs.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { createEditorTabsStore } from '../editor-slice-test-harness' - -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 { toastErrorMock } = vi.hoisted(() => ({ - toastErrorMock: vi.fn() -})) - -vi.mock('sonner', () => ({ - toast: { error: toastErrorMock } -})) - -const { notifyHostOfMirroredEditorCloseMock } = vi.hoisted(() => ({ - notifyHostOfMirroredEditorCloseMock: vi.fn() -})) -vi.mock('@/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab', () => ({ - notifyHostOfMirroredEditorClose: (...args: unknown[]) => - notifyHostOfMirroredEditorCloseMock(...args) -})) - -describe('createEditorSlice recently closed editor tabs', () => { - it('restores the exact same-path owner instead of moving the local editor', () => { - const store = createEditorTabsStore() - const localId = store.getState().openFile({ - filePath: '/repo/notes.md', - relativePath: 'notes.md', - worktreeId: 'wt-1', - language: 'markdown', - mode: 'edit' - }) - const remoteId = store.getState().openFile({ - filePath: '/repo/notes.md', - relativePath: 'notes.md', - worktreeId: 'wt-1', - language: 'markdown', - runtimeEnvironmentId: 'env-1', - mode: 'edit' - }) - store.getState().setTabBarOrder('wt-1', [localId, remoteId]) - - store.getState().closeFile(remoteId) - expect(store.getState().reopenClosedEditorTab('wt-1')).toBe(true) - - const openIds = store.getState().openFiles.map((file) => file.id) - expect(openIds).toEqual([localId, remoteId]) - expect(store.getState().tabBarOrderByWorktree['wt-1']).toEqual([localId, remoteId]) - }) - - it('keeps same-path edit and diff tabs as separate entities on reopen', () => { - const store = createEditorTabsStore() - const editId = store.getState().openFile({ - filePath: '/repo/notes.md', - relativePath: 'notes.md', - worktreeId: 'wt-1', - language: 'markdown', - mode: 'edit' - }) - store.getState().openDiff('wt-1', '/repo/notes.md', 'notes.md', 'markdown', false) - const diffId = 'wt-1::diff::unstaged::notes.md' - store.getState().setTabBarOrder('wt-1', [editId, diffId]) - - store.getState().closeFile(diffId) - expect(store.getState().reopenClosedEditorTab('wt-1')).toBe(true) - - expect(store.getState().openFiles.map((file) => file.id)).toEqual([editId, diffId]) - expect(store.getState().tabBarOrderByWorktree['wt-1']).toEqual([editId, diffId]) - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts b/src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts deleted file mode 100644 index 4c37a932173..00000000000 --- a/src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation' -import { - createTestStore, - resetRemoteRuntimeMocks, - resetWorktreeSliceModuleMemory -} from '../worktrees-slice-test-harness' - -const requestWorktreeBaseFallbackNotice = vi.hoisted(() => vi.fn()) - -vi.mock('sonner', () => ({ - toast: { - warning: vi.fn(), - info: vi.fn(), - success: vi.fn(), - error: vi.fn(), - dismiss: vi.fn() - } -})) - -vi.mock('@/components/worktree-base-fallback-notice', () => ({ - requestWorktreeBaseFallbackNotice -})) - -beforeEach(() => { - resetWorktreeSliceModuleMemory() -}) - -function makePendingCreation( - creationId: string, - overrides: Partial = {} -): PendingWorktreeCreation { - return { - creationId, - phase: 'fetching', - status: 'creating', - startedAt: 1000, - indeterminate: false, - loaderVisible: false, - request: { - repoId: 'repo1', - name: 'feature', - setupDecision: 'inherit', - agent: null, - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null - }, - ...overrides - } -} - -describe('pending worktree creation state', () => { - beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - }) - - it('keeps composer picks when stale preparation lands with prior chat options', () => { - const store = createTestStore() - const request = { - ...makePendingCreation('c1').request, - agent: 'codex' as const, - launchInputs: { - sessionOptions: { effort: 'high', permissionMode: 'ask' }, - chatSessionOptions: { effort: 'high' } - } - } - store.getState().beginPendingWorktreeCreation(makePendingCreation('c1', { request })) - store.getState().updatePendingWorktreeCreation('c1', { - chatSessionOptions: { effort: 'low' } - }) - store.getState().updatePendingWorktreeCreation('c1', { - chatSessionOptions: { fastMode: 'true' } - }) - - store.getState().updatePendingWorktreeCreation('c1', { - request: { - ...request, - setupDecision: 'skip', - hookPreparation: undefined, - executionHostId: 'runtime:host-1', - launchInputs: { ...request.launchInputs, agentArgs: '--sandbox workspace-write' } - }, - phase: 'creating' - }) - - const current = store.getState().pendingWorktreeCreations.c1 - expect(current?.request).toMatchObject({ - setupDecision: 'skip', - executionHostId: 'runtime:host-1', - launchInputs: { - sessionOptions: { effort: 'high', permissionMode: 'ask' }, - agentArgs: '--sandbox workspace-write', - chatSessionOptions: { effort: 'low', fastMode: 'true' } - } - }) - expect(current?.request.launchInputs?.chatSessionOptions?.model).toBeUndefined() - expect(current?.phase).toBe('creating') - }) -}) diff --git a/src/shared/agent-status/title/agent-detection.test.ts b/src/shared/agent-status/title/agent-detection.test.ts deleted file mode 100644 index 66783050189..00000000000 --- a/src/shared/agent-status/title/agent-detection.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { extractAllOscTitles, extractLastOscTitle } from './osc-title-extraction' - -describe('OSC title extraction', () => { - it('recovers when an abandoned incomplete OSC title is followed by a fresh title', () => { - const data = '\x1b]0;abandoned\x1b]0;Fresh title\x07' - - expect(extractLastOscTitle(data)).toBe('Fresh title') - expect(extractAllOscTitles(data)).toEqual(['Fresh title']) - }) -})